create custom environment from class template
you can define a custom reinforcement learning environment by creating and modifying a template environment class. you can use a custom template environment to:
implement more complex environment dynamics.
add custom visualizations to your environment.
create an interface to third-party libraries defined in languages such as c , java®, or python®. for more information, see external language interfaces.
for more information about creating matlab® classes, see .
you can create less complex custom reinforcement learning environments using custom functions, as described in create custom environment using step and reset functions.
create template class
to define your custom environment, first create the template class file, specifying the
name of the class. for this example, name the class myenvironment
.
rlcreateenvtemplate("myenvironment")
the function rlcreateenvtemplate
creates and opens the template class file. the template class is a subclass of the
rl.env.matlabenvironment
abstract class, as shown in the class
definition at the start of the template file. this abstract class is the same one used by
the other matlab reinforcement learning environment objects.
classdef myenvironment < rl.env.matlabenvironment
by default, the template class implements a simple cart-pole balancing model similar to the cart-pole predefined environments described in load predefined control system environments.
to define your environment dynamics, save the file as
myenvironment.m
. then modify the template class by specifying the
following:
environment properties
required environment methods
optional environment methods
environment properties
in the properties
section of the template, specify any parameters
necessary for creating and simulating the environment. these parameters can include:
physical constants — the sample environment defines the acceleration due to gravity (
gravity
).environment geometry — the sample environment defines the cart and pole masses (
cartmass
andpolemass
) and the half-length of the pole (halfpolelength
).environment constraints — the sample environment defines the pole angle and cart distance thresholds (
anglethreshold
anddisplacementthreshold
). the environment uses these values to detect when a training episode is finished.variables required for evaluating the environment — the sample environment defines the state vector (
state
) and a flag for indicating when an episode is finished (isdone
).constants for defining the actions or observation spaces — the sample environment defines the maximum force for the action space (
maxforce
).constants for calculating the reward signal — the sample environment defines the constants
rewardfornotfalling
andpenaltyforfalling
.
properties % specify and initialize the necessary properties of the environment % 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 % angle at which to fail the episode (radians) anglethreshold = 12 * pi/180 % 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 end properties % initialize system state [x,dx,theta,dtheta]' state = zeros(4,1) end properties(access = protected) % initialize internal flag to indicate episode termination isdone = false end
required functions
a reinforcement learning environment requires the following functions to be defined. the
getobservationinfo
, getactioninfo
,
sim
, and validateenvironment
functions are already
defined in the base abstract class. to create your environment, you must define the
constructor, reset
, and step
functions.
function | description |
---|---|
getobservationinfo | return information about the environment observations |
getactioninfo | return information about the environment actions |
sim | simulate the environment with an agent |
validateenvironment | validate the environment by calling the reset function and
simulating the environment for one time step using step |
reset | initialize the environment state and clean up any visualization |
step | apply an action, simulate the environment for one step, and output the observations and rewards; also, set a flag indicating whether the episode is complete |
constructor function | a function with the same name as the class that creates an instance of the class |
sample constructor function
the sample cart-pole constructor function creates the environment by:
defining the action and observation specifications. for more information about creating these specifications, see
rlnumericspec
andrlfinitesetspec
.calling the constructor of the base abstract class.
function this = myenvironment() % initialize observation settings observationinfo = rlnumericspec([4 1]); observationinfo.name = 'cartpole states'; observationinfo.description = 'x, dx, theta, dtheta'; % initialize action settings actioninfo = rlfinitesetspec([-1 1]); actioninfo.name = 'cartpole action'; % the following line implements built-in functions of the rl environment this = this@rl.env.matlabenvironment(observationinfo,actioninfo); % initialize property values and precompute necessary values updateactioninfo(this); end
this sample constructor function does not include any input arguments. however, you can add input arguments for your custom constructor.
sample reset
function
the sample cart-pole reset function sets the initial condition of the model and
returns the initial values of the observations. it also generates a notification that the
environment has been updated by calling the envupdatedcallback
function, which is useful for updating the environment visualization.
% reset environment to initial state and return initial observation function initialobservation = reset(this) % theta ( - .05 rad) t0 = 2 * 0.05 * rand - 0.05; % thetadot td0 = 0; % x x0 = 0; % xdot xd0 = 0; initialobservation = [x0;xd0;t0;td0]; this.state = initialobservation; % (optional) use notifyenvupdated to signal that the % environment is updated (for example, to update the visualization) notifyenvupdated(this); end
sample step
function
the sample cart-pole step
function:
processes the input action.
evaluates the environment dynamic equations for one time step.
computes and returns the updated observations.
computes and returns the reward signal.
checks if the episode is complete and returns the
isdone
signal as appropriate.generates a notification that the environment has been updated.
function [observation,reward,isdone,info] = step(this,action) info = []; % get action force = getforce(this,action); % unpack state vector xdot = this.state(2); theta = this.state(3); thetadot = this.state(4); % cache to avoid recomputation costheta = cos(theta); sintheta = sin(theta); systemmass = this.cartmass this.polemass; temp = (force this.polemass*this.halfpolelength*thetadot^2*sintheta)... /systemmass; % apply motion equations thetadotdot = (this.gravity*sintheta - costheta*temp)... / (this.halfpolelength*(4.0/3.0 - this.polemass*costheta*costheta/systemmass)); xdotdot = temp - this.polemass*this.halfpolelength*thetadotdot*costheta/systemmass; % euler integration observation = this.state this.ts.*[xdot;xdotdot;thetadot;thetadotdot]; % update system states this.state = observation; % check terminal condition x = observation(1); theta = observation(3); isdone = abs(x) > this.displacementthreshold || abs(theta) > this.anglethreshold; this.isdone = isdone; % get reward reward = getreward(this); % (optional) use notifyenvupdated to signal that the % environment has been updated (for example, to update the visualization) notifyenvupdated(this); end
optional functions
you can define any other functions in your template class as required. for example, you
can create helper functions that are called by either step
or
reset
.
the cart-pole template model implements a getreward
function for
computing the reward at each time step.
function reward = getreward(this) if ~this.isdone reward = this.rewardfornotfalling; else reward = this.penaltyforfalling; end end
environment visualization
you can add a visualization to your custom environment by implementing the
plot
function. in the plot
function:
create a figure or an instance of a visualizer class of your own implementation. for this example, you create a figure and store a handle to the figure within the environment object.
call the
envupdatedcallback
function.
function plot(this) % initiate the visualization this.figure = figure('visible','on','handlevisibility','off'); ha = gca(this.figure); ha.xlimmode = 'manual'; ha.ylimmode = 'manual'; ha.xlim = [-3 3]; ha.ylim = [-1 2]; hold(ha,'on'); % update the visualization envupdatedcallback(this) end
for this example, store the handle to the figure as a protected property of the environment object.
properties(access = protected) % initialize internal flag to indicate episode termination isdone = false % handle to figure figure end
in the envupdatedcallback
, plot the visualization to the figure or
use your custom visualizer object. for example, check if the figure handle has been set. if
it has, then plot the visualization.
function envupdatedcallback(this) if ~isempty(this.figure) && isvalid(this.figure) % set visualization figure as the current figure ha = gca(this.figure); % extract the cart position and pole angle x = this.state(1); theta = this.state(3); cartplot = findobj(ha,'tag','cartplot'); poleplot = findobj(ha,'tag','poleplot'); if isempty(cartplot) || ~isvalid(cartplot) ... || isempty(poleplot) || ~isvalid(poleplot) % initialize the cart plot cartpoly = polyshape([-0.25 -0.25 0.25 0.25],[-0.125 0.125 0.125 -0.125]); cartpoly = translate(cartpoly,[x 0]); cartplot = plot(ha,cartpoly,'facecolor',[0.8500 0.3250 0.0980]); cartplot.tag = 'cartplot'; % initialize the pole plot l = this.halfpolelength*2; polepoly = polyshape([-0.1 -0.1 0.1 0.1],[0 l l 0]); polepoly = translate(polepoly,[x,0]); polepoly = rotate(polepoly,rad2deg(theta),[x,0]); poleplot = plot(ha,polepoly,'facecolor',[0 0.4470 0.7410]); poleplot.tag = 'poleplot'; else cartpoly = cartplot.shape; polepoly = poleplot.shape; end % compute the new cart and pole position [cartposx,~] = centroid(cartpoly); [poleposx,poleposy] = centroid(polepoly); dx = x - cartposx; dtheta = theta - atan2(cartposx-poleposx,poleposy-0.25/2); cartpoly = translate(cartpoly,[dx,0]); polepoly = translate(polepoly,[dx,0]); polepoly = rotate(polepoly,rad2deg(dtheta),[x,0.25/2]); % update the cart and pole positions on the plot cartplot.shape = cartpoly; poleplot.shape = polepoly; % refresh rendering in the figure window drawnow(); end end
the environment calls the envupdatedcallback
function, and
therefore updates the visualization, whenever the environment is updated.
instantiate custom environment
after you define your custom environment class, create an instance of it in the matlab workspace. at the command line, type the following.
env = myenvironment;
if your constructor has input arguments, specify them after the class name. for example,
myenvironment(arg1,arg2)
.
after you create your environment, the best practice is to validate the environment
dynamics. to do so, use the validateenvironment
function, which prints
an error to the command window if your environment implementation has any issues.
validateenvironment(env)
after validating the environment object, you can use it to train a reinforcement learning agent. for more information on training agents, see train reinforcement learning agents.