main content

create custom environment using step and reset functions -凯发k8网页登录

this example shows how to create a custom environment by writing your own matlab® step and reset functions.

using the rlfunctionenv function, you can create a matlab reinforcement learning environment from an observation specification, an action specification, and step and reset functions that you supply. you can then train a reinforcement learning agent in this environment. for this example, the necessary step and reset functions are already defined.

creating an environment using custom functions is especially useful for simpler environments that do not need many helper functions and have no special visualization requirements. for more complex environments, you can create an environment object using a template class. for more information, see create custom environment from class template.

for more information on creating reinforcement learning environments, see reinforcement learning environments and create custom simulink environments.

discrete action space cart-pole matlab environment

the cart-pole environment is a pole attached to an unactuated joint on a cart, which moves along a frictionless track. the training goal is to make the pendulum stand upright without falling over.

for this environment:

  • the upward balanced pendulum position is 0 radians and the downward hanging position is π radians.

  • the pendulum starts upright with an initial angle that is between –0.05 radians and 0.05 radians.

  • the force action signal from the agent to the environment is either –10 n or 10 n.

  • the observations from the environment are the cart position, cart velocity, pendulum angle, and pendulum angular velocity.

  • the episode terminates if the pole is more than 12 degrees from vertical or the cart moves more than 2.4 m from the original position.

  • a reward of 1 is provided for every time step that the pole remains upright. a penalty of –10 is applied when the pendulum falls.

for more information on this model, see load predefined control system environments.

observation and action specifications

the observations from the environment are the cart position, cart velocity, pendulum angle, and pendulum angle derivative.

obsinfo = rlnumericspec([4 1]);
obsinfo.name = "cartpole states";
obsinfo.description = 'x, dx, theta, dtheta';

the environment has a discrete action space where the agent can apply one of two possible force values to the cart: -10 or 10 n.

actinfo = rlfinitesetspec([-10 10]);
actinfo.name = "cartpole action";

for more information on specifying environment actions and observations, see rlnumericspec and rlfinitesetspec.

define environment reset and step functions

to define a custom environment, first specify the custom step and reset functions. these functions must be in your current working folder or on the matlab path.

the reset function sets the initial state of the environment. this function must have the following signature.

[initialobservation,info] = myresetfunction()

the first output argument is the initial observation. the second output argument can be any useful environment information that you want to pass from one step to the next, such as for example the environment state, or a structure containing state and parameters.

at the beginning of the training (or simulation) episode, train (or sim) calls your reset function and uses its second output argument to initialize the info property of your custom environment. during a training (or simulation) step, train (or sim) supplies the current value of info as the second input argument of stepfcn, and then uses the fourth output argument returned by stepfcn to update the value of info.

for this example, use the second argument to store the initial states of the cart-pole environment: the position and velocity of the cart, the pendulum angle, and the pendulum angle derivative. the reset function sets the cart angle to a random value each time the environment is reset.

for this example, use the custom reset function defined in myresetfunction.m.

type myresetfunction.m
function [initialobservation, initialstate] = myresetfunction()
% reset function to place custom cart-pole environment into a random
% initial state.
% theta (randomize)
t0 = 2 * 0.05 * rand() - 0.05;
% thetadot
td0 = 0;
% x
x0 = 0;
% xdot
xd0 = 0;
% return initial environment state variables as logged signals.
initialstate = [x0;xd0;t0;td0];
initialobservation = initialstate;
end

the step function specifies how the environment advances to the next state based on a given action. this function must have the following signature.

[nextobservation,reward,isdone,updatedinfo] = mystepfunction(action,info)

to calculate the new state, the step function applies the dynamic equation to the current state stored in info. the function then returns the updated state in updatedinfo. at the next training (or simulation) step, train or sim takes the fourth output argument obtained during the previous step, updatedinfo, and supplies it to the step function as the second input argument, info.

for this example, use the custom step function defined in mystepfunction.m. for implementation simplicity, this function redefines physical constants, such as the cart mass, every time step is executed. an alternative is to define the physical constants in the reset function, define info as a structure containing both state and parameters, and therefore use info to store the physical constants as well as the environment states. this alternative implementation lets you easily change some of the parameters during the simulation or training if you need to.

type mystepfunction.m
function [nextobs,reward,isdone,nextstate] = mystepfunction(action,state)
% custom step function to construct cart-pole environment for the function
% name case.
%
% this function applies the given action to the environment and evaluates
% the system dynamics for one simulation step.
% define the environment constants.
% acceleration due to gravity in m/s^2
gravity = 9.8;
% mass of the cart
cartmass = 1.0;
% mass of the pole
polemass = 0.1;
% half the length of the pole
halfpolelength = 0.5;
% max force the input can apply
maxforce = 10;
% sample time
ts = 0.02;
% pole angle at which to fail the episode
anglethreshold = 12 * pi/180;
% cart distance at which to fail the episode
displacementthreshold = 2.4;
% reward each time step the cart-pole is balanced
rewardfornotfalling = 1;
% penalty when the cart-pole fails to balance
penaltyforfalling = -10;
% check if the given action is valid.
if ~ismember(action,[-maxforce maxforce])
    error('action must be %g for going left and %g for going right.',...
        -maxforce,maxforce);
end
force = action;
% unpack the state vector from the logged signals.
xdot = state(2);
theta = state(3);
thetadot = state(4);
% cache to avoid recomputation.
costheta = cos(theta);
sintheta = sin(theta);
systemmass = cartmass   polemass;
temp = (force   polemass*halfpolelength*thetadot*thetadot*sintheta)/systemmass;
% apply motion equations.
thetadotdot = (gravity*sintheta - costheta*temp) / ...
    (halfpolelength*(4.0/3.0 - polemass*costheta*costheta/systemmass));
xdotdot  = temp - polemass*halfpolelength*thetadotdot*costheta/systemmass;
% perform euler integration to calculate next state.
nextstate = state   ts.*[xdot;xdotdot;thetadot;thetadotdot];
% copy next state to next observation.
nextobs = nextstate;
% check terminal condition.
x = nextobs(1);
theta = nextobs(3);
isdone = abs(x) > displacementthreshold || abs(theta) > anglethreshold;
% calculate reward.
if ~isdone
    reward = rewardfornotfalling;
else
    reward = penaltyforfalling;
end
end

construct the custom environment using the observation and action specification, and the names of your step and reset functions.

env = rlfunctionenv(obsinfo,actinfo,"mystepfunction","myresetfunction");

to verify the operation of your environment, rlfunctionenv automatically calls validateenvironment after creating the environment.

pass additional arguments using anonymous functions

while the custom reset and step functions that you must pass to rlfuntionenv must have exactly zero and two arguments, respectively, you can avoid this limitation by using anonymous functions. specifically, you define the reset and step functions to be passed to rlfuntionenv as anonymous functions (with zero and two arguments, respectively). in turn, these anonymous functions, call your custom functions that have additional arguments.

for example, to pass the additional arguments arg1 and arg2 to both the step and reset function, you can write the following functions.

[initialobservation,info] = myresetfunction(arg1,arg2)
[observation,reward,isdone,info] = mystepfunction(action,info,arg1,arg2)

then, with arg1 and arg2 in the matlab workspace, define the following handles to anonymous reset and step functions with zero and two arguments, respectively.

resethandle = @() myresetfunction(arg1,arg2);
stephandle = @(action,info) mystepfunction(action,info,arg1,arg2);

if arg1 and arg2 are available at the time that resethandle and stephandle are created, the workspaces of both anonymous functions include those values. the values persist within the function workspaces even if you clear the variables from the matlab workspace. when resethandle and stephandle are evaluated, they invoke myresetfunction and mystepfunction and pass them a copy of arg1 and arg2. for more information, see .

using additional input arguments can create a more efficient environment implementation. for example, mystepfunction2.m is a custom step function that takes the environment constants as its third input argument (envpars). by doing so, this function avoids redefining the environment constants at each step.

type mystepfunction2.m
function [nextobs,reward,isdone,nextstate] = mystepfunction2(action,state,envpars)
% custom step function to construct cart-pole environment for the function
% handle case.
%
% this function applies the given action to the environment and evaluates
% the system dynamics for one simulation step.
% check if the given action is valid.
if ~ismember(action,[-envpars.maxforce envpars.maxforce])
    error('action must be %g for going left and %g for going right.',...
        -envpars.maxforce,envpars.maxforce);
end
force = action;
% unpack the state vector from the logged signals.
xdot = state(2);
theta = state(3);
thetadot = state(4);
% cache to avoid recomputation.
costheta = cos(theta);
sintheta = sin(theta);
masspole = envpars.masspole;
halflen = envpars.halflength;
systemmass = envpars.masscart   masspole;
temp = (force   masspole*halflen*thetadot*thetadot*sintheta)/systemmass;
% apply motion equations.
thetadotdot = (envpars.gravity*sintheta - costheta*temp)...
    / (halflen*(4.0/3.0 - masspole*costheta*costheta/systemmass));
xdotdot  = temp - masspole*halflen*thetadotdot*costheta/systemmass;
% perform euler integration.
nextstate = state   envpars.ts.*[xdot;xdotdot;thetadot;thetadotdot];
% copy next state to next observation.
nextobs = nextstate;
% check terminal condition.
x = nextobs(1);
theta = nextobs(3);
isdone = abs(x) > envpars.xthreshold || ...
         abs(theta) > envpars.thetathresholdradians;
% calculate reward.
if ~isdone
    reward = envpars.rewardfornotfalling;
else
    reward = envpars.penaltyforfalling;
end
end

create the structure that contains the environment parameters.

% acceleration due to gravity in m/s^2
envpars.gravity = 9.8;
% mass of the cart
envpars.masscart = 1.0;
% mass of the pole
envpars.masspole = 0.1;
% half the length of the pole
envpars.halflength = 0.5;
% max force the input can apply
envpars.maxforce = 10;
% sample time
envpars.ts = 0.02;
% angle at which to fail the episode
envpars.thetathresholdradians = 12 * pi/180;
% distance at which to fail the episode
envpars.xthreshold = 2.4;
% reward each time step the cart-pole is balanced
envpars.rewardfornotfalling = 1;
% penalty when the cart-pole fails to balance
envpars.penaltyforfalling = -5;

create an anonymous function that calls your custom step function, passing envpars as an additional input argument.

stephandle = @(action,info) mystepfunction2(action,info,envpars);

because envpars is available at the time that stephandle is created, the anonymous function workspace includes a copy of envpars. when stephandle is evaluated, it calls mystepfunction2 passing its copy of envpars.

use the same reset function, specifying it as a function handle rather than by using its name.

resethandle = @() myresetfunction;

create the environment using the handles to the anonymous functions.

env2 = rlfunctionenv(obsinfo,actinfo,stephandle,resethandle);

visually inspect outputs of custom functions

while rlfunctionenv automatically calls validateenvironment after creating the environment, it might be useful to visually inspect the output of your functions to further confirm that their behavior conforms to your expectations. to do so, initialize your environment using the reset function and run one simulation step using the step function. for reproducibility, set the random generator seed before validation.

validate the environment created using function names.

rng(0);
initialobs = reset(env)
initialobs = 4×1
         0
         0
    0.0315
         0
[nextobs,reward,isdone,info] = step(env,10);
nextobs
nextobs = 4×1
         0
    0.1947
    0.0315
   -0.2826

validate the environment created using function handles.

rng(0);
initialobs2 = reset(env2)
initialobs2 = 4×1
         0
         0
    0.0315
         0
[nextobs2,reward2,isdone2,info2] = step(env2,10);
nextobs2
nextobs2 = 4×1
         0
    0.1947
    0.0315
   -0.2826

both environments initialize and simulate successfully, producing the same state values in nextobs.

see also

functions

objects

related topics

网站地图