Learning tasks with bimanual robots using motion symmetries
Abstract
The main aim of this work is to present a motion learning framework in order to make a Whole Arm Manipulator (WAM) robot learn a task. In addition, we will improve the motion learning algorithm by reducing the dimensionality of the problem in both general one arm cases, and two arm motions which include symmetries. In the last case, we will use the symmetry feature in order to upgrade the learning process.
Full text
Title: Learning tasks with bimanual robots using motion symmetries Author: Enric Cosp Arqué Advisor: Adrià Colomé and Carme Torras Department: Institut de Robòtica i Informàtica Industrial Academic year: 2016/17 Degree in Mathematics
Universitat Polit`ecnica de Catalunya Facultat de Matem`atiques i Estad´ıstica Degree in Mathematics Bachelor’s Degree Thesis Learning tasks with bimanual robots using motion symmetries Enric Cosp Arqu´e Supervised by Adri`a Colom´e and Carme Torras June, 2017
Firstly, I wish to express my sincere thanks to my tutors, Adri`a Colom´e and Carme Torras. I am extremely thankful and indebted to them for sharing expertise, and sincere and valuable guidance and encouragement extended to me. I take this opportunity to express gratitude to my parents and brother for the incessant encouragement, support and attention. I am also grateful to my partner who supported me throughout this venture. Finally, place on record, my sense of gratitude to one and all, who directly or indirectly, have lent their hand.
Abstract The main aim of this work is to present a motion learning framework in order to make a Whole Arm Manipulator (WAM) robot learn a task. In addition, we will improve the motion learning algorithm by reducing the dimensionality of the problem in both general one arm cases, and two arm motions which include symmetries. In the last case, we will use the symmetry feature in order to upgrade the learning process. Keywords Motion learning, Robotics, Symmetries, Bimanual Robots. 1
Contents 1 Introduction 7 1.1 Motivations and project picture .......................... 7 1.2 Global context .................................... 9 1.2.1 Artificial Intelligence and Machine Learning .............. 9 1.2.2 Robotics .................................... 11 2 Reinforcement learning 13 2.1 Introduction ...................................... 13 2.2 Method ......................................... 13 2.2.1 Markov Decision Problems ......................... 13 2.2.2 Policy Search ................................. 14 3 Required multi-disciplinary knowledge 19 3.1 Robot geometrical structure ............................ 19 3.2 Dynamic Movement Primitives ........................... 20 3.2.1 What are DMPs? .............................. 20 3.2.2 Building DMPs ............................... 20 3.3 Principal Component Analysis ........................... 25 3.3.1 Goal and intuitive view ........................... 25 3.3.2 Method .................................... 26 3.4 Moore-Penrose Pseudo-inverse ........................... 29 4 Implementation 30 4.1 Process and code ................................... 30 5 DOF reduction 37 5.1 General case ...................................... 38 5.2 Symmetric tasks ................................... 41 5.2.1 Method .................................... 41 6 Conclusions 46 6
1 Introduction 1.1 Motivations and project picture Which tasks, problems, concepts and challenges does a researcher face day by day? This question has been boiling in the bowels since the beginning of the last year and the time to take it off the pot has arrived. From the curiosity of the applications of Machine Learning and the chance to collaborate with the Institut de Rob`otica i Inform`atica Industrial, CSIC-UPC, has flourished the idea to solve the latent question in an ideal environment. In greedy fields as they are, nowadays, robotics and machine learning, it was not difficult to find a goal that both satisfied my inquietudes and was useful to the community. The main aim of this work is to present part of the process developed in order to make a Whole Arm Manipulator (WAM) robot learn a task. The subject that we are focusing in is the robot motion learning. Moreover, we want to implement this model in order to make the robot learn movements which involve symmetries, and use this feature to optimize the process. This task jumbles a variety of scientific areas, including kinematics, dynamics, probability, statistics and more. 7
This multi-disciplinary feature is also appealing as, lately, more problems are being approached in this way, and the trend seems to continue this way. In order to carry out the motion learning process, we will characterize trajectories with Dynamic Movement Primitives (DMPs) and afterwards, we will use the latest advances in Reinforcement Learning, more specifically Policy Search, for the learning itself. To reduce the time required to implement this process, we will use a well known algorithm: Principal Component Analysis. Moreover, when applying this framework to bimanual tasks which include symmetries between arms, we will propose a method to use these symmetries to refine the algorithm. In the introduction, we are going to contextualize this work regarding which fields it is placed in. Moreover, we will give light over how this work is placed in a more general and ambitious work inside Artificial Intelligence and Robotics. In the second chapter, we will describe Reinforcement Learning (RL) in terms of which problems it tries to solve. In addition, we will explain the general approach of RL algorithms. Chapter three will go over several algorithms and concepts that we will need in our motion learning process and upgrading. The learning model and its implementation will be described in Chapter four. Different methods will be compared at some stages of the learning process. Being the goal of this work the understanding of a motion learning framework, approach and algorithm, rather that the application itself, we will devote to simple tasks. Chapter five will be devoted to the improvement of the motion learning model, in terms of time and resources needed to achieve our goal. We will approach this challenge by reducing the dimensionality of our problem. Dimensionality reduction is gaining interest within robotics, as for many problems, some stages of the learning process require human interaction. The amount of required human presence is proportional to the number of dimensions. Thus, reducing the dimensionality implies needing less human 8
usually the position or speed in the i-th timestep, and aithe acceleration assignment at timestep i. This yis often called path or rollout. This reward/cost function is a measure of goodness of a trajectory. In order to perform our RL algorithm, we initialize the parameters µand Σ that define the initial policy: π(a|s)∼N(µ, Σ). We use this policy to create Nk(fixed number, usually greater than d·Nf) trajectories, which are perturbations of an initial demonstrated trajectory. Policy Search aims to update the policy taking into account the reward/cost function, i.e. finding good parameters for a given policy parametrization. PS is well suited for robotics as it can cope with high-dimensional state and action spaces, one of the main challenges in robot learning. Model-free policy search is a general approach to learn policies based on sampled trajectories. We classify model-free methods based on their policy evaluation strategy, policy update strategy, and exploration strategy and present a unified view on existing algorithms. Learning a policy is often easier than learning an accurate forward model, and, hence, model-free methods are more frequently used in practice. However, for each sampled trajectory, it is necessary to interact with the robot, which can be time consuming and challenging in practice. Model-based policy search addresses this problem by first learning a simulator of the robots dynamics from data. Subsequently, the simulator generates trajectories that are used for policy learning. We have used two different policy searches: 15
1. Weighted Maximum Likelihood Policy Search (WMLPS) 2. Relative Entropy Policy Search (REPS) These methods use the information given by the MDP in order to find a policy that generates better trajectories according to the reward function. Essentially, they weight the trajectories, giving more importance to the ones with better reward. Weighted Maximum Likelihood Policy Search Let wk,Rk,∀k∈ |Nk|be the samples obtained with the old parameters and the rewards of the trajectories. WLPS uses the following update of the normal distribution parameters: µnew =∑Nk k=1 wkeRk ∑Nk k=1 eRk (1) Σnew =∑Nk k=1(wk−µnew)(wk−µnew)TeRk ∑Nk k=1 eRk (2) In WLPS, the policy parameters are updated by iteratively maximizing the weighted log-likelihood for the obtained sample sequence. WMLE-based policy search methods use the reward Rkto compute a weight lkfor each sample, such that ∑N k=1 lk= 1 and, subsequently, the mean and covariance matrix of the upper-level policy π(θ) is updated by a weighted MLE. In this case, the weights are computed as an exponential transformation of the rewards lk=eRk. The rewards are always negative and the closer the rewards are to zero, the better the trajectories are (if it is a cost function, it is always positive, the closer to zero, the better the trajectories are). 16
Relative Entropy Policy Search This is also a Weighted Maximum Likelihood based policy search. In general, this policies are updated like in the previous method, with the weights computed as lk∝eRk/η, being ηthe so called temperature parameter. In the particular case of REPS, the policy update can be formulated as constrained optimization problem where we want to maximize the expected return of the new policy under the Kullback-Leibler constraint [3]. This problem consists in maximizing the expectation of the reward π=argmaxEθ[R|θ] (3) subject to: ∫π(w)dw = 1 (4) KL(π||q)≤ϵ≈0.5 (5) being πthe new policy, q∼N(µold,Σold) the old one and KL the Kullback- Leibler divergence: KL(π||q) = ∑iπ(i)lnπ(i) q(i)in its discrete form. KL divergence is a measure of how one probability distribution diverges from a second expected probability distribution [6]. The main intuition behind this bound is that we can directly control the exploration-exploitation trade-off with the parameter. On the one hand, for a large ϵ(more greedy), the variance of the new upper level policy will decrease quickly such that, it will give much higher importance to high-reward samples, ignoring lower-performing ones. always choose the sample with highest reward. On the other hand, for a small ϵ(less greedy), the new search policy and the old search policy would be almost identical. This optimization is solved for our samples, due to the fact that it cannot be solved analytically, as the reward of the trajectory generated by W,RW 17
is unknown. As a result, we get a transformation lk∝eRk/η, where the parameter ηis found by minimizing the dual function of the optimization problem g(η) = ηϵ +η log( N ∑ k=1 1 NeRk/η) (6) with η > 0. This dual function comes from solving the optimization problem by means of Lagrange multipliers. 18
3 Required multi-disciplinary knowledge 3.1 Robot geometrical structure The key feature of a robot is its geometrical structure [10] bodies(links) interconnected by articulations (joints). A manipulator is composed by an arm that gifts mobility, a wrist that confers dexterity, and an end-effector that performs the task required of the robot. Another fundamental feature of a manipulator is the kinematic chain. From a geometrical viewpoint, a kinematic chain is termed open when there is only one sequence of links connecting the two ends of the chain. Alternatively, a manipulator contains a closed kinematic chain when a sequence of links forms a loop. We work with WAM robots, inspired in human arms. These have an open chain, born in the base and culminate in the end-effector, which would simulate a hand in a human arm. Mobility is ensured by joints. These are classified in prismatic and revolute joints. In an open kinematic chain, each prismatic or revolute joint provides the structure with a single degree of freedom (DOF). A prismatic joint creates relative translation between the two links, whereas a revolute joint creates a relative rotation between the two links. The degrees of freedom should be properly distributed in the mechanical structure, in order to execute the given task. For the most general task, consisting of positioning and orienting and object in a 3D-space, 6 DOFs are required: 3 for positioning the object and 3 for orienting it. A manipulator is said to be redundant from a kinematic point of view in the number of DOFs available exceeds the number of task variables. On the case of the WAM, there are 7 DOFs: 3 in the first link (shoulder), 1 on the second(elbow) and 3 on the third (wrist), with human-like kinematics. 19
3.2 Dynamic Movement Primitives 3.2.1 What are DMPs? Dynamic movement primitives (DMPs) are a method of trajectory control and planning. The first aim of this work was to find a way to represent complex motor actions that can be flexibly adjusted without manual parameter tuning or having to worry about instability. They where first presented by Auke Ijspeert in 2002 and then updated in 2013 [4]. Complex movements have long been thought to be composed of sets of primitive action. DMPs are a proposed mathematical formalization of these primitives. In robotics, among all Movement Primitives (MPs), they are the most used ones. The basic idea is that given dynamical system with well specified, stable behaviour, one may add another term that makes it follow some interesting trajectory as it goes about its business. There are two kinds of DMPs: discrete and rhythmic. We will only discuss discrete DMPs, as they are the ones that we will use. We may have two systems: an imaginary system where we plan trajectories, and a real system where we carry them out. When we use a DMP what we are doing is planning a trajectory that will be followed by the real system. A DMP has its own set of dynamics, and by setting up your DMP properly we can get the control signal for our actual system to follow. We are not going to talk about the real system, but it is important to keep the perspective that the DMP framework is for generating a trajectory to guide the real system. 3.2.2 Building DMPs In this section we will be using some of the work developed by Ijspeert [9]. Let ybe our system state, gthe goal, τa time constant, and αand β gain terms. The following system describes our trajectory y: ¨y/τ =αy(βy(g−y)−˙y/τ) (7) 20
This is system of second order differential equations. It is well known how to solve this kind of equations both analytically and numerically. Therefore, it is a suitable way to represent our trajectories. We usually choose βz=αz/4 in order to make the system critically damped, so that ymonotonically converges towards g. Now, we add a forcing term fto modify this trajectory: ¨y/τ =αy(βy(g−y)−˙y/τ) + f(8) In order to build the nonlinear function fto get the desired behaviour, we will use an additional nonlinear system, called canonical dynamical system: ˙x=−αxx(9) The use of this system allows us to define fover time, giving the problem giving the problem a well defined structure that can be solved in a straight-forward way and easily generalizes. In order to construct the forcing function, we need to define some more parameters. Let y0be the initial position of the system. Let ϕi=exp (−0.5 (x−ci)2/di),∀i∈[Nf] = {1, . . . Nf}(10) be a set of Gaussians with center at ciand width di.Nfis the chosen number of Gaussians per degree of freedom. Let wibe a set of weightings for the given basis functions ϕi,∀i∈Nf. Now, the forcing function is: fnew(x, g) = ∑Nf i=1 ϕiwi ∑Nf i=1 ϕi x(g−y0) (11) a set of Gaussians that are activated as the canonical system xconverges to its target. Their weighted summation is normalized, and then multiplied by the x(g−y0) term, which acts as both a diminishing and spatial scaling term. In order to compute fnew, we have used ψT t=Id⊗h(xt)T, being hi(x) = ϕi ∑Nf j=1 ϕj x, ∀i∈[Nf], and ⊗the Kronecker product. Then, fnew = ΨT tw. (12) 21
If we assumed that the canonical system starts at x0= 1 and decays to 0 (exponentially, due to the definition of x) as time goes to ∞. On the one hand, the basis functions ψiare activated as a function of x. As the value of xdecreases from 1 to 0, each of the Gaussians are centered around different xvalues. On the other hand, these basis functions are also assigned a weight, wi. Incorporating the xterm into the forcing function guarantees that the contribution of the forcing term goes to zero over time, as the canonical system does. This means that the system will eventually return to its simpler point attractor dynamics and converge to the target. 22
The (g−y0) term of the forcing function handles the spacial scaling. It does so by activating the basis functions ψito be relative to the distance to the goal, causing the system to cover more or less distance. DMPs are key to our work, as they will be used in order to characterize the trajectories of the end-effectors of our WAMs (robot arms) by means of second order dynamical-systems. Finally, to build the trajectories using the fitting of fnew, we solve the ode (8), using the new forcing excitation function: ¨ynew/τ =αy(βy(g−ynew)−˙ynew/τ) + fnew (13) When computing this step numerically, we set ynew 1=y1, ˙ynew 1=y1and ¨ynew 1= ¨y1and we get along ∀i∈[Nt]: ¨ynew i/τ =αy(βy(g−ynew i−1)−˙ynew i−1/τ) + fnew i−1(14) 23
˙ynew i= ˙ynew i−1+dt¨ynew i(15) ynew i=ynew i−1+dt ˙ynew i(16) being dt the timestep. 24
the trajectory matrix notation, this would be: Q(i, :) = Q(i, 2d+ 2 : 3d+ 1)K+Q(i−1,2d+ 2 : 3d+ 1)(1 −K). In order to simplify the formulation, we will assume the following equalities: yi=Q(i, 2, d + 1) (25) ˙yi=Q(i, d + 2,2d+ 1) (26) ¨yi=Q(i, 2d+ 2,3d+ 1) (27) Once we can start working with the data, we choose gain terms αy,βy (usually βy=αy/4, to make the ode critically damped) and the goal g in order to start computing DMPs. Here is a reminder on how we build DMPs, with a more numerical approach. We compute the excitation function: fi= ¨y/τ −αy(βy(g−y)−˙y/τ),∀i∈[Nt] 31
and solve the canonical dynamical system: xi=exp(−αxti),∀i∈[Nt].(28) being tithe time until the i−th timestep. Now, we choose the centers C and widths Dof the Gaussians, so that they are balanced: c= [ τ Nf+ 1, . . . , iτ Nf+ 1, . . . , Nfτ Nf+ 1] (29) C=exp(−αxc τ) (30) D= (diff(C) 0.55 )2,(31) where diff(C) is a vector that stores Ci−Ci−1,∀i= 1 . . . Nfand the parameter 0.55 is found empirically. Then, we calculate the set of Gaussians: ϕi,j =exp((−xi−cj)2 Dj ),∀i∈[Nt],∀j∈[Nf] (32) 32
and the function: hi,j =xiϕi,j ∑Nf j=1 ϕi,j ,∀i∈[Nt],∀j∈[Nf].(33) Let Abe the pseudo-inverse of h. To store the weights, we define w=Af. W(j−1)Nf+i=wi,j ,∀i∈[Nf],∀j∈[d],(34) which means W= w1 . . . wNf .(35) Thus, the fitting of fis: fnew i= ((Id⊗hi,:) W)T,∀i∈[Nf],∀j∈[d] (36) and the fitting of the trajectory, initializing with Qnew(:,1) = Q(:,1), ynew 1= y1,˙y1new = ˙y1,¨y1new = ¨y1and updating ∀i= 2 . . . Nt: •Position: ¨yinew =τ(αz(βz(g−ynew i)−˙yinew/τ) + fnew i−1,:) •Speed: ˙yinew = ˙yinew +dt¨yinew (37) •Acceleration: ynew i=ynew i+dt ˙yinew (38) 33
For our naive example we will be working with the following trajectory: After computing the DMPs, we compare Qnew and fnew with Qand f. We have used αz= 12, βz=αz 4,Nf= 10 and αx= 2.5. Once performed the DMPs, we start running a Policy Search algorithm. To do so, we must specify a reward function, according to the aim. In our example, we want the trajectory to be the closer the better to a point in a certain time-step. Let pQ= 0.4 be the point and pt= 50 the time point where we want pQto be reached. In the example, the reward function is: R=mean(−|y−pQ|−0.000015 ∑¨y2),(39) which takes into account how close the trajectory is to pQat pt. It also considers high accelerations to be high, as it may be dangerous. We set λ= 50 to initialize our covariance matrix Σ = diag(λ). The mean starts being µ=W. Let Nupd be the number of updates of µand σ. Let 34
Nkbe the number of samples created from each update of µand σ. For each update, we create Nksamples Wk, k = 1 . . . Nk. These are created according to a (µ, Σ)−normal distribution, i.e. wk∼N(µ, Σ) and are (Nfd)−weight vectors. Let Wbe a matrix that stores the k−th vector of motion parameters in the k−th column. For each one of these samples, we create a new excitation function fnew(x) = ΨTwk(40) being ΨT=Id⊗h(x) and W= [w1, . . . , wNk]. Expressed in a more coded way: fnew i= ((Id⊗h(+i,:)W:,k )T,∀i∈1. . . Nf,∀j∈1. . . d. (41) and create a new trajectory Qnew, in the same way that we did the first time. We evaluate the function reward, inputing Qnew and store this reward, as well as the excitation function fnew. Having evaluated the reward of the trajectories created with every sample, we update the parameters of the normal distribution: µand Σ. To do so, we have used both Weighted Maximum Likelihood Policy Search (WMLPS) and Relative Entropy Policy Search (REPS). As explained in previous chapters, REPS is usually used to palliate the greediness and instability of Weighted Maximum Likelihood. Once we have updated µnew and Σnew, we use fnew =µnew in order to create a new trajectory Qnew. The policy update involves the reward function and the samples. This is where the algorithm is actually learning, by giving more importance (weight) to the trajectories with less reward (in absolute value). We also evaluate the reward function with this new trajectory. In the following figures, we can observe the evolution of the reward function obtained with both methods, considering only the reward of the trajectory created using µnew updated with the policy search method: As we can see, 35
REPS is performing better at every time-step. As mentioned earlier in this section, it is a more stable method. Therefore, its curve is smoother than the one provided by WMLPS. Focusing on the REPS curve, we can see that it is not monotonous. Instead, it decreases as expected and then grows a little bit. This might be due to numerical errors in the calculus. This process leaves as an output, a trajectory that has learned from every policy update, and every trajectory with its associated reward. 36
5 DOF reduction We have presented a framework for motion learning. This model requires several rollouts in order to find a proper policy update. Moreover, many parameters are needed to achieve a good fitting of the initial trajectory. When applying DMPs in learning models, we must bear in mind several considerations: •Reinforcement learning can be performed through simulation or with a real robot. If we have a good simulator of the robot and its environment, we will go through simulation. Nevertheless, when accurate models are not available, we will have to use a real robot. In this case, reducing the number of parameters and iterations (rollouts) is vital. •Moreover, certain tasks might not depend on all the Degrees of Freedom (DoFs) of the robot. In this case, the algorithm may be exploring motions that are meaningless to the task. Also some exploration values could generate strong oscillations, rapid accelerations and other dangerous motions. •In addition, complex robots usually require many parameters for a proper trajectory representation. The number of parameters is strongly dependent on the trajectory length. In a 7-DoF robot like the WAM that we are using, we use over 20 Gaussian kernels per joint for a 20-second trajectory, meaning that we might have more than 140 parameters in total. The more parameters we use, the better the fitting of the initial trajectory will be, generally speaking. However, this a large number of parameters may result in a slower learning. In this sense, there is a tradeoff between better exploitation (many parameters) and efficient exploration (fewer parameters). For these reasons, performing Dimensionality Reduction (DR) on the DMPs DoF is an effective way of dealing with the setoff between exploration and exploitation in order to help the algorithm converge faster to a likely better solution. 37
5.1 General case In this section, we will describe how to reduce the dimensionality of the problem with a coordination framework for DMPs [3]. To achieve our goal, we will perform a different fitting of the excitation function: f(xi) = ΩΨT iW , ∀i∈ |Nt|(42) being Ω a (d×r) matrix (r < d is the dimension that we want to reduce to), ΨT i=Ir⊗h(i, :) (Iris the identity matrix of dimension r×r) and Wthe matrix of samples of motion parameters, as in the previous chapter. This representation is equivalent to having rmovement primitives codifying the d-dimensional vector fnew(x). Intuitively, the columns of Ω represent the couplings between the robots DoF. In order to learn the coordination matrix Ω, we need an initialization, an updating method and an algorithm to eliminate needless DoFs from the DMP, according to the reward. We can assume that the probability of having certain excitation function values fi=f(xi) at a timestep, given the sample of weights W, is p(fi|W)∼N(ΩΨT iW, Σf), with Σfbeing the system covariance (noise). Thus, if W∼N(µW,ΣW), the probability of fi is: P(fi) = N(ΩΨt iµW,Σf+ ΩΨT iΣWΨiΩT) (43) the coordination matrix Ω can be initialized with a Principal Component Analysis(PCA) [3]. Particularly, we will perform it over the values of f= ΨTW, with Ψ calculated with the identity matrix of d×ddimensions (this is the first fitting of the excitation function). To do so, we build the (d×Nt) matrix: 38
¯ F= f(1) de (x0)−¯ f(1) de . . . f(1) de (xNt)−¯ f(1) de . . . . . . f(d) de (x0)−¯ f(d) de . . . f(d) de (xNt)−¯ f(d) de (44) being ¯ fde the joint average of the DMP excitation function, for the demonstrated motion (fde). Note that ¯ Fis the matrix of all the Nttimesteps f(j) i and djoins. Afterwards, we Perform Singular Value Decomposition (SVD) of ¯ F, so we have ¯ F=UpcaΣpcaVT pca. The next step in this method is to take the reigenvectors with the highest singular values as the initialization of coordination matrix Ω. These eigenvectors are the first rcolumns of Upca, thus Ω = [u1, . . . , ur] and their associated singular values σ1> . . . > σr, being Upca = [u1, . . . , ur, . . . ud] and Σpca =diag(σ1, . . . , σr, . . . , σd). This way, we minimize the error in the reprojection e=∥¯ F−Ω¯ ΣVT∥2 Frob (with ¯ Σ = diag(σ1, . . . , σr)), while reducing the set of DoF of dimension r, which activate the robot joints (dimension d). Now, we are going to describe how to update the coordination matrix in every rollout. We assume that we have performed Nkreproductions of the motion, namely rollouts. Thus, we obtain the excitation function f(j),k i, for every time-step i= 1 . . . Nt, rollout k= 1 . . . Nkand DoF j= 1 . . . d. Now, we evaluate the trajectories attached to every excitation function with the reward function. Then, we can associate a relative weight Pk ito each rollout and timestep, regarding the reward values. These weights are given by the policy search algorithms that we are using (WMLPS and REPS). Thus, we obtain a new matrix Fnew co = ∑Nk k=1 f(1),k 1Pk 1. . . ∑Nk k=1 f(1),k NtPk Nt . . . . . . ∑Nk k=1 f(d),k 1Pk 1. . . ∑Nk k=1 f(d),k NtPk Nt (45) This d×Ntmatrix contains the excitation functions weighted by their importance according to the rollout result. Then, the coordination matrix 39
can be updated by PCA. Nevertheless, we have to refit the parameters µW,ΣWto make the trajectory representation fit the same trajectory. Let ˆµand ˆ Σ be the old distribution parameters. We want to minimize the loss of information. To do so, we will minimize the Kulbach-Leibler divergence between ˆp∼N(ˆµW,ˆ ΣW) and p∼ N(MµW, MΣWMT), being M= (ˆ Ωˆ ΨT i)+ΩΨT i(+ is the Moore-Penrose pseudo-inverse operator). Derivating KL(ˆp||p) with respect to µWand ΣWand equating the derivative to zero, we obtain the following updates of the policy parameters: µW=M+ˆµW(46) ΣW=M+(ˆ ΣW+ (MµW−ˆµW)(MµW−ˆµW)T)MT,+(47) Being this the parameter update that minimizes the KL divergence, it results in the update with the least loss of information, in terms of probability distribution on the excitation function, i.e. we minimize the loss of inertia of the excitation functions created with these parameters with respect to the old parameters. Currently, in reinforcement learning, not all the DoF affect the task the the robot tries to learn. However, these DoF are still considered through all the learning process, causing a slowdown in the learning process or result in motions in which a part of the trajectory may not be necessary. Hence, the use of the coordination matrix build as we described outfits the framework, removing unnecessary DoF. With the described framework we achieve to reduce the dimensionality from dto r. 40
References [1] Deisenroth, M. P., Neumann, G., & Peters, J. (2013). Introduction(pp. 4). A survey on policy search for robotics. Foundations and Trends in Robotics, 2(12), 1-142. [2] Colom´e, Adri`a and Torras, Carme. Dimensionality Reduction for Dynamic Movement Primitives and Application to Bimanual Manipulation of Clothes, submitted 2016. [3] A. Colom´e and C. Torras. Dimensionality reduction and motion coordination in learning trajectories with dynamic movement primitives, 2014 IEEE/RSJ International Conference on Intelligent Robots and Systems, 2014, Chicago, pp. 1414-1420 [4] DeWolf, Travis. Dynamic Movement Primitives Part 1: the basics <https://studywolf.wordpress.com/2013/11/16/dynamic-movement- primitives-part-1-the-basics/>, 2013 [5] Siciliano, B. et al (2007). Part A. AI Reasoning Methods for Robotics (pp. 336). Handbook of robotics. [6] Kullback, S. and Leibler, On information and sufficiency (pp. 79-80), Annals of Mathematical Statistics, 1951. [7] Gradient Descent. <https://en.wikipedia.org/wiki/Gradient descent>. [8] Gerig G. Least Squares, Pseudo-Inverses, PCA & SVD.<http://www.sci.utah.edu/∼gerig/CS6640- F2012/Materials/pseudoinverse-cis61009sl10.pdf>. University of Utah. [9] Ijspeert, A. J., Nakanishi, J., Hoffmann, H., Pastor, P., & Schaal, S. (2013). Dynamical movement primitives: learning attractor models for motor behaviors. Neural computation, 25(2), 328-373. [10] Siciliano, B. (2009) Chapters 1-3 (pp. 1-159) Robotics modelling, planning and control. 47
Appendix: Code % main min_jerk close all clear variables % generem t r a j e c t r i a d=7; min_jerk_trajectory; % N o t a c i i guardar p a r m e t r e s donats aux =size(T); Q=zeros (aux (1) ,3*d+1) ; Q(: ,1) = T; Q(:,2:d+1) = y; Q(:,d+2:2*d+1) = yd; Q(:,2*d+2:3* d+1) = ydd; plot(Q(: ,2)) Nt =length(Q(: ,1)); Nf = 10; alphaz = 12; alphax = 2.5; betaz =alphaz/4; %tau = 20.1; K= 0.8; g=Q(Nt , 2:d+1) ; dt =Q(2 ,1) -Q(1 ,1); % carreguem les dades de la trajectoria , trobem els p a r m e t r e s i la f i % filtrem l ’ a c c e l e r a c i [ddy_filt,f,x,Q,Nt ,g] = ini_filt_param(Q,tau ,d,Nf ,alphax ,alphaz ,betaz,K,g); % calculem les gaussianes i fem el plot % per on volem que passi Q1 = [0.4 , 0.7 , 0.5 , 0.45 , 0.3 , 0.6 , 0.55]; t1 = 50; lambda = 1; Nk =Nf*d+ 5; % calculem gaussianes i la matriu P [Ct ,C,D,W,p,P] = gaussianes (Q,Nf ,tau,alphax ,x,d); % troba els pesos , calcula la nova f i fa plots [new_f,w,A,new_Q,Id ,w_aux] = pesos (P,Nf ,d,x,f,Q,Nt ,alphaz ,betaz,g,dt ,tau,lambda) ; % guardem alguns p a r m e t r e s per a poguer fer policy ( actualitzant mu i sigma amb Maximum Likelihood ) %i policyREPS ( acutalitzant amb REPS ) per separat lambda = 5000; 49
Q1ini =Q1; t1ini =t1; lambdaini =lambda; Qini =Q; new_Qini =new_Q; wini =w; % f_newini = f_new ; new_fini =new_f; Pini =P; Nupdates=100; % genera mostres a partir de la normal i actualitza la mu i la sigma usant % Maximum Likelyhood [R,Rmean,new_mu ,new_S,W,fs ,new_f ] = policy (Q1 ,t1 ,lambda ,Nk ,Q,new_Q ,dt ,Id ,alphax , alphaz ,betaz,Nf ,d,w,new_f ,g,Nt ,P,tau ,Nupdates ,t1); % policy search amb REPS r= 1; [RREPS,RmeanREPS ,new_mu ,new_S,W,fs ,dws,new_f,M,S] = policyREPS (Q1ini,t1ini, lambdaini ,Nk ,Qini,new_Qini,dt ,Id ,alphax ,alphaz ,betaz,Nf ,d,wini,new_fini ,g,Nt ,Pini ,tau,Nupdates ,r,t1 ); figure; plot(Rmean(2: end, 1)) hold on; plot(RmeanREPS(2: end , 1)) title(’Rmean vs RmeanREPS ’) legend(’Rmean ’,’ RmeanREPS ’) % main min_jerk close all clear all addpath(’/ Users / acolome / Desktop / MATLAB / robot ’) % read data Qtot =load (’ FullData . txt ’); Q1 =Qtot(:,[1:8,16:22,30:36]); Q2 =Qtot(:,[1,9:15,23:29,37:43]); time =Q1(end ,1); d= 7; % for i = 2:( d +1) % figure % plot ( Q1(:,i)) % end % no movement in the firt 15 -20 timesteps Q1 =Q1 (15: end , :); Q2 =Q2 (15: end , :); %subsampling ss =3; Q1 =Q1 (1: ss:end, :); %Q2 = Q2 (1:3: end , :); 50
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%555 % for i = 2:( d +1) % x = 1: length ( Q1 (: ,1) ); % y = Q1(x,i); % xx = 0:.25: length ( Q1 (: ,1) ); % yy = spline (x ,y, xx ); % figure % plot (x,y,’o’,xx ,yy) % hold on % plot ( Q1 (: ,i ), ’ LineWidth ’ ,2); % end dt1 =Q1 (2 ,1) -Q1 (1 ,1); %=0.0597 timelapse =Q1(end ,1) -Q1 (1 ,1); %=8.9545 dt1 = 1/ length(Q1 (: ,1) ); T1 = 0: dt1 :1 - dt1; Q1 (: ,1) = T1; dt2 = 1/ length(Q2 (: ,1) ); T2 = 0: dt2 :1 - dt2; Q2 (: ,1) = T2; tau = 1; dt =dt2*time ; T=T2; yy =zeros(size (Q2) ); yy (1 ,:) = Q1 (1 ,:) ; yy (: ,1) = Q2 (: ,1) ; x= 1: length (Q1 (: ,1) ); xx = 1:(1/ ss): length(Q1 (: ,1)); for i= 2:(d+1) y=Q1(x,i); yy(:,i) = spline(x,y,xx); for j= 2: length(yy (: ,1) ) yy (2: end,d+i) = diff (yy(:,i)) / dt; yy (2: end ,2*d+i) = diff(yy (:,d+i)) / dt; % yy(: ,d+i) = gradient (yy(:,i)); % yy (: ,2* d+i) = gradient (yy (:, d+i)); end % figure % plot (x,y,’o’,xx ,yy); % hold on % plot ( Q1 (: ,i ), ’ LineWidth ’ ,2); end %for i = (2* d+2) :(3*d+1) for i= 1:22 figure plot (yy (: ,1) , yy(:,i)); hold on plot (Q1 (: ,1) , Q1(:,i), ’ LineWidth ’ ,2); 51
end Q1 =yy; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %dt = Q1 (2 ,1) -Q1 (1 ,1) ; %=0.0597 timelapse =Q1(end ,1) -Q1 (1 ,1); %=8.9545 %dt = 1/ length ( Q1 (: ,1)); T= 0: dt2 :1- dt2 ; Q1 (: ,1) = T; Q2 (: ,1) = T2; tau = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Nf = 10; alphaz = 10; alphax = 3.5; betaz =alphaz/4; tau = 1; K= 0.8; Nt =length(Q1 (: ,1) ); g=Q1(Nt , 2:d+1); % translation coordinates l1 = 0.985; l2 = 0; l3 = 0; % rotation angle theta = 0; WAM; [Qc1 ,Qc2] = change_ref (Q1 ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % carreguem les dades de la trajectoria , trobem els p a r m e t r e s i la f i % filtrem l ’ a c c e l e r a c i [ddy_filt,f,x,Q1 ,Nt ,g] = ini_filt_param(Q1 ,tau,d,Nf ,alphax ,alphaz ,betaz,K,g); Qg = [1, -0.22 , -0.25; 1.2 , -0.3, -0.2; 1.05 , -0.22 , 0.5]; tg = [10 , 25, 40] ’; %tgv = Q1(tg ,1) ; lambda_reg = 0.1; Nk =Nf*d+ 2; % Nk = 10; % compute Gaussians and weights , and make the fitting of f and Q [Ct ,C,D,W,p,P] = gaussianes (Q1 ,Nf ,tau,alphax ,x,d); [new_f,w,A,new_Q1 ,Id ,w_aux] = pesos(P,Nf ,d,x,f,Q1 ,Nt ,alphaz ,betaz,g,dt ,tau , lambda_reg ); 52
% safe parameters to compare WMLPS and REPS lambda = 5000; Qgini =Qg; tgini =tg; lambdaini =lambda; Q1ini =Q1; new_Q1ini =new_Q1; wini =w; new_fini =new_f; Pini =P; Nupdates = 10; % WMLPS new_Q =new_Q1; [R,Rmean,new_mu ,new_S,W,fs ,new_f ] = policy2(Qg ,tg ,lambda ,Nk ,Q1 ,Q2 ,new_Q1 ,dt ,Id , alphax ,alphaz ,betaz,Nf ,d,w,new_f ,g,Nt ,P,tau,Nupdates,Qc2 ,l1 ,l2 ,l3 ,theta) % REPS with coordination matrix DoF reduction r= 4; [RREPS,RmeanREPS ,new_mu ,new_S,W,fs ,dws,new_f,M,S] = policyREPS2(Qgini ,tgini, lambdaini ,Nk ,Q1ini,new_Q1ini ,Q2 ,dt ,Id ,alphax ,alphaz ,betaz,Nf ,d,wini,new_fini ,g,Nt ,Pini ,tau,Nupdates,r,Qc2,l1 ,l2 ,l3 ,theta ); figure; plot(Rmean(2: end ,1)) hold on; plot(RmeanREPS(2: end ,1)) title(’Rmean vs RmeanREPS ’) legend(’Rmean ’,’ RmeanREPS ’) figure; hold on; plot(RREPS) hold on; title(’R vs RREPS ’) legend(’R ’,’RREPS ’,’Rnormal’) % initial variety dist_min =Inf; eix_min = [1 0 0 0]; % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end figure plot(Qc2 (: ,2)) hold on plot(Qc1 (: ,2)) 53
hold on plot(Qm (: ,2)) hold on plot(Qpm (: ,2)) legend(’Q2 ’,’Q1 ’,’Qm ’,’Qpm ’) figure plot3(Qc1 (: ,2) ,Qc1 (: ,3) ,Qc1 (: ,4) ,’m’,’ LineWidth ’ ,2) hold on plot3(Qc2 (: ,2) ,Qc2 (: ,3) ,Qc2 (: ,4) ,’k’,’ LineWidth ’ ,2) plot3(Qm (: ,2) ,Qm (: ,3) ,Qm (: ,4) ,’g’,’LineWidth ’ ,2) grid on % axis equal legend(’q1 ’,’q2 ’,’qm ’) x=-2:.1:2; [X,Y] = meshgrid(x); aa=eix_min(1); bb=eix_min(2); cc=eix_min(3) ; dd=eix_min(4); Z=(dd -aa *X-bb *Y)/cc; h=surf (X,Y,Z) shading flat h.EdgeColor =’none ’ h.FaceColor =’b’ % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end function [x,xd ,xdd ] = min_jerk_step (x,xd ,xdd ,goal ,tau ,dt) % function [x,xd ,xdd] = min_jerk_step (x,xd ,xdd ,goal ,tau , dt) computes % the update of x,xd , xdd for the next time step dt given that we are % currently at x,xd ,xdd , and that we have tau until we want to reach % the goal if tau<dt , return; end; dist =goal -x; a1 = 0; a0 =xdd *tau ^2; v1 = 0; v0 =xd *tau ; t1=dt; t2=dt ^2; 54
t3=dt ^3; t4=dt ^4; t5=dt ^5; c1 = (6.*dist + (a1 -a0)/2. - 3.*( v0 +v1))/tau ^5; c2 = ( -15.* dist + (3.*a0 - 2.* a1) /2. + 8.* v0 + 7.* v1)/tau ^4; c3 = (10.* dist+ (a1 - 3.* a0) /2. - 6.* v0 - 4.* v1)/ tau ^3; c4 =xdd /2.; c5 =xd; c6 =x; x=c1*t5 +c2*t4 +c3*t3 +c4*t2 +c5*t1 +c6; xd = 5.* c1*t4 + 4* c2*t3 + 3* c3 *t2 + 2* c4*t1 +c5; xdd = 20.*c1*t3 + 12.*c2*t2 + 6.* c3*t1 + 2.* c4; % min_jerk d joints tau = 1; %temps final dt = 0.01; %discretization step % d = 7; % dimensio es diu al main y=zeros (tau/dt ,d); yd =zeros(tau/dt ,d); ydd =zeros(tau/dt ,d); dof =size(y,2); y(1 ,:) = zeros (1,d); %starting position g=ones (1,d) ’; %Goal for i=1: tau/dt -1 for j=1:d [y(i+1,j) ,yd(i+1,j),ydd(i+1 ,j)] = min_jerk_step (y(i,j),yd(i,j),ydd(i,j), g(j), tau -i*dt ,dt); % function [x ,xd ,xdd ] = min_jerk_step (x,xd ,xdd , goal ,tau , dt) computes % the update of x,xd , xdd for the next time step dt given that we are % currently at x,xd ,xdd , and that we have tau until we want to reach % the goal end end T=(0: dt:tau-dt) ’; tau = 1; %temps final dt = 0.01; %discretization step %d = 1; % dimensio y=zeros (tau/dt ,d); yd =zeros(tau/dt ,d); ydd =zeros(tau/dt ,d); dof =size(y,2); y(1 ,:) = zeros (1,d)+ randn(1,d); %starting position g=ones (1,d) ’+ randn(1,d) ’; % Goal for i=1: tau/dt -1 for j=1: dof 55
[y(i+1,j) ,yd(i+1,j),ydd(i+1 ,j)] = min_jerk_step (y(i,j),yd(i,j),ydd(i,j), g(j), tau -i*dt ,dt); % function [x ,xd ,xdd ] = min_jerk_step (x,xd ,xdd , goal ,tau , dt) computes % the update of x,xd , xdd for the next time step dt given that we are % currently at x,xd ,xdd , and that we have tau until we want to reach % the goal end end T=(0: dt:tau-dt) ’; function [Qc1,Qc2 ] = change_ref (Q1 ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam ) % WAM; % change of reference transformation T= [cos(theta ) -sin (theta) 0 l1; sin(theta )cos(theta ) 0 l2; 0 0 1 l3; 0 0 0 1]; Qc1 =Q1 (: ,1) ; Qc2 =Q2 (: ,1) ; for t= 1: Nt % Q2 is the trajectory of WAM2 in the Joint Space 2 q= (Q2(t,2:d+1)) ’; T2 =fkine (wam,q); Qc2(t,2:4) = T2 (1:3 ,4); % Qc2 is Q2 in the Cartesian Space 2 aux = (T*[ Qc2(t,2:4) ’ ; 1]) ’; Qc2(t,2: end) = aux (1 ,1:3); % transform from Cartesian Space 2 to 1 % Q1 is the trajectory of WAM1 in the Joint Space 1 q= (Q1(t,2:d+1)) ’; T1 =fkine (wam,q); Qc1(t,2:4) = T1 (1:3 ,4); % Qc1 is Q1 in the Cartesian Space 1 end end clear L L{1} = link ([-pi /2 0 0 0 0],’standard ’); L{2} = link ([ pi /2 0 0 0 0], ’standard ’); L{3} = link ([-pi /2 0.045 0 0.55 0], ’standard ’); L{4} = link ([ pi /2 -0.045 0 0 0], ’ standard ’); L{5} = link ([-pi /2 0 0 0.3 0], ’ standard ’); L{6} = link ([ pi /2 0 0 0 0], ’standard ’); L{7}=link([0 0 0 0.06 0], ’ standard ’); L{1}.m= 8.3936; L{2}.m= 4.8487; L{3}.m= 1.7251; L{4}.m= 1.0912; 56
% inicialize mu and Sigma f_aux =new_f ’; z=zeros (r*Nt ,1) ; for t= 1: Nt z( (t-1)*r+1 : t*r,1) = pinv(Om_old)* f_aux (:,t); end Psi_aux =zeros(r*Nt ,Nf*r); for t= 1: Nt Psi_aux(((t-1)*r+ 1) :((t-1)*r+r) , :) = Psi( : , ((t-1)*r+ 1) :((t-1)*r+ r))’ ; end old_mu =pinv (Psi_aux) * z; old_S = 1000* eye(r*Nf); % inicialize de new_mu i new_S new_mu =old_mu; new_S =old_S ; % % nova t r a j e c t r i a % new_Q (: ,1) = Q (: ,1) ; % new_Q (: ,2:5) = Q (: ,2:5) ; % new_Q (: ,6:9) = Q (: ,9:12); % new_Q (: ,10:13) = Q (: ,16:19); RmeanREPS=zeros(Nupdates+1 ,2) ; for iter = 1: Nupdates % while ( abs ( Rmean ( iter )) > 0.05) [iter RmeanREPS (iter)] RREPS =zeros (1, Nk); % mu and Sigma for k= 1: Nk W(:,k) = mvnrnd(new_mu ,new_S )’ ; % Sample clear new_f ; clear new_Q ; % new trajectory new_Q (: ,1) = Q(: ,1); new_Q (:,2:d+1) = Q(:,2:d+1); new_Q (:,d+2:2* d+1) = Q(:,d+2:2* d+1) ; % fitting f for t= 1: Nt new_f (t,:) = ( Om_old *( kron(eye(r), P(t,:))* W(: ,k))) ’; end % trajectory for i= 2: Nt new_Q (i,2*d+2:3* d+1) = tau*alphaz* ( betaz *(g-new_Q (i-1,2:d+1) ) - new_Q(i-1,d+2:2* d+1) / tau) + new_f(i,:) ; new_Q (i,d+2:2*d+1) = new_Q (i-1 ,d+2:2* d+1) + dt*new_Q (i,2*d+2:3*d+1); new_Q (i,2:d+1) = new_Q(i-1,2:d+1) + dt*new_Q (i,d+2:2*d+1) ; end 63
ALLQ {k}= new_Q(:,2:d+1); if plot_flag ==1 plot (new_Q (: ,2) ,’b’) hold on end NEW_F {k} = new_f ’; RREPS (k)= mean (- abs (new_Q (tg ,2:d+1) - Q1) - 0.000015* sum ( ( new_Q (:,2*d +2:3* d+1)).^2 )); end % figure % plot (- abs ( new_Q (50 ,2:8) - Q1)) % title ( iter ) % figure % plot (0.000015* sum ( new_Q (: ,16:22) ) .^2 ) % title ( iter ) REPS ;% -> new_mu and new_S Fweighted =zeros (d,Nt); for i= 1: Nk Fweighted =Fweighted+dw(i)* NEW_F{i}/ sum(dw); end % build coordination matrix if iter ~= 1 Om_old =Om ; end % [U,S,V] = svd (Fweighted ); % if iter ==1 Om =U(: ,1: r); % end O_old =kron (eye(Nt), Om_old); O=kron (eye (Nt),Om); M=pinv (O_old *Psi’)*O*Psi ’; if iter ~= 1 old_mu =new_mu; old_S =new_S; end % update policy new_mu =pinv (M)* old_mu ; new_S =pinv (M)*(old_S + (M*new_mu -old_mu) * (M*new_mu -old_mu )’ ) * pinv (M) ’; % new trajectory clear new_f; clear new_Q; new_Q (: ,1) = Q(: ,1); new_Q (1 ,2:d+1) =Q(1 ,2:d+1); new_Q (1,d+2:2* d+1)=Q(1,d+2:2* d+1); Id =eye(r); 64
for t= 1: Nt new_f (t,:) = ( Om *( kron (eye(r), P(t,:))* new_mu ) ) ’; end for i= 2: Nt new_Q (i,2*d+2:3* d+1) = tau*alphaz* ( betaz *(g-new_Q(i-1,2:d+1) ) - new_Q (i-1,d+2:2* d+1) / tau) + new_f (i-1 ,:); new_Q (i,d+2:2* d+1) = new_Q (i-1,d+2:2*d+1) + dt*new_Q(i,2*d+2:3*d+1); new_Q (i,2:d+1) = new_Q(i-1,2:d+1) + dt*new_Q (i,d+2:2* d+1) ; end % Reward REPS_output(iter+1)= mean(-abs(new_Q(tg ,2:d+1) - Q1) - 0.000015* sum( ( new_Q (:,2*d+2:3* d+1)) .^2 )); RmeanREPS (iter +1 ,:) = [ mean(REPS_output) ,2* std(REPS_output)]; MU =[ MU;new_mu ’]; SS =[ SS;svd(new_S) ’]; % plot ( new_Q (: ,2:8) ,’ Color ’, Colorset (1 ,:) ) ; % title (’ QREPS vs newQREPS ’) ; if plot_flag ==1 close all plot (new_Q (: ,2) ,’k’,’ LineWidth ’ ,2) hold on end end figure plot(RmeanREPS(2: end ,1) ,’b ’,’ LineWidth ’ ,2) hold on plot(RmeanREPS(2: end ,1) + RmeanREPS (2: end ,2) ,’b ’,’ LineWidth ’ ,1) plot(RmeanREPS(2: end ,1) - RmeanREPS (2: end ,2) ,’b’,’ LineWidth ’ ,1) title(’ RmeanREPS ’) % figure % plot ( RREPS ) % hold on % plot ( RmeanREPS ) % title (’ Reward ’) % legend (’ RREPS ’, ’ RmeanREPS ’) % end % function [R,Rmean,new_mu ,new_S,W,fs ,new_f] = policy2(Qg ,tg ,lambda ,Nk ,Q1 ,Q2 ,new_Q ,dt ,Id ,alphax ,alphaz ,betaz,Nf ,d,w,new_f,g,Nt ,P,tau ,Nupdates ,Qc2,l1 ,l2 ,l3 , theta ) % per on volem que passi % Q1 = [0.4 , 0.7 , 0.15 , 1.5 , -0.1, -0.25 , 0.1]; % t1 = Q (50 ,1); fs =zeros (Nt ,d,Nk); 65
new_mu =w; new_S =lambda*eye (d*Nf); R=zeros (1, Nk); WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end R(1) = mean(mean(- abs(Qpm(tg ,2:4) - Qg)) ); W=zeros (d*Nf ,Nk); hold on iter = 1; Rmean =zeros(Nupdates ,1) ; for iter =1: Nupdates [iter Rmean (iter)] % perform Nk rollouts for k= 1: Nk W(:,k) = mvnrnd (new_mu ,new_S)’ ; % samples clear new_f ; clear new_Q ; % new trajectory new_Q (: ,1) = Q1 (: ,1); new_Q (1,2:d+1) = Q1 (1,2:d+1); new_Q (1,d+2:2*d+1) = Q1(1,d+2:2* d+1); for i= 2: Nt new_f(i,:) = (kron(Id ,P(i,:))*W(:,k)) ’; new_Q(i,2* d+2:3* d+1) = tau *alphaz* ( betaz *(g-new_Q (i-1 ,2:d+1) ) - new_Q (i-1,d+2:2*d+1) / tau) + new_f (i,:) ; new_Q(i,d+2:2*d+1) = new_Q (i-1,d+2:2* d+1) + dt*new_Q (i,2*d+2:22) ; new_Q(i,2: d+1) = new_Q (i-1,2:d+1) + dt*new_Q(i,d+2:2*d+1) ; end % plot ( new_Q (: ,2:8) ,’ Color ’, Colorset (1 ,:) ); WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end n= 3; m= 1; % break indx into 3 parts because n-m+1 = 3 ( points definig the variety) 66
indx1 =randi([1 floor (Nt /3)], 1, 500) ; indx2 =randi([ floor (Nt /3) floor (2* Nt /3)], 1, 500); indx3 =randi([ floor (2* Nt /3) floor(Nt)], 1, 500); [DIST,Qm ] = mirr_traj(m,n,indx1,indx2,indx3,Nt ,d,Qc1 ,Qc2 ,Qpm ); % Evaluate Reward R(k)= mean (mean (- abs (Qpm (tg ,2:4) - Qg)) ); R(k) fs(: ,:,k) = new_f ; end % plot ( new_Q (: ,2:8) ,’ Color ’, Colorset (1 ,:) ) ; % title (’Q vs newQ ’) % % legend (’Q ’) new_mu=zeros(Nf*d,1); for i= 1: Nk new_mu =new_mu +W(:,i)* exp (R(i)) / sum(exp(R) ); end new_S =zeros (Nf*d,Nf*d); for i=1: Nk new_S =new_S + (W(:,i) - new_mu)*(W(:,i) - new_mu ) ’*exp (R(i))/sum ( exp(R)); end % new mean trajectory clear new_f ; clear new_Q ; new_Q (: ,1) = Q1 (: ,1); new_Q (1,2:d+1)=Q1 (1 ,2: d+1); new_Q (1,d+2:2* d+1)=Q1(1,d+2:2* d+1); % new_f = f_new ; for i= 2: Nt new_f (i,:) = ( kron(Id ,P(i,:) )* new_mu) ’; new_Q (i,2*d+2:3* d+1) = tau*alphaz* ( betaz *(g-new_Q (i-1,2:d+1) ) - new_Q(i-1,d+2:2* d+1) / tau) + new_f(i-1 ,:); new_Q (i,d+2:2*d+1) = new_Q (i-1 ,d+2:2* d+1) + dt*new_Q (i,2*d+2:3*d+1); new_Q (i,2:d+1) = new_Q(i-1,2:d+1) + dt*new_Q (i,d+2:2*d+1) ; end WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end % Reward of the mean trajectory Rmean (iter +1) = mean(mean (- abs (Qpm (tg ,2:4) - Qg)) ); end % figure 67
% plot (R) % hold on % plot ( Rmean ) % title (’ Reward ’) % legend (’R ’, ’Rmean ’) % end function [REPS_output ,RmeanREPS ,new_mu ,new_S,W,fs ,dws,new_f,MU ,SS] = policyREPS2 (Qg ,tg ,lambda ,Nk ,Q,new_Q ,Q2 ,dt ,Id ,alphax ,alphaz ,betaz ,Nf ,d,w,new_f ,g,Nt ,P, tau,Nupdates ,r,Qc2,l1 ,l2 ,l3 ,theta ) plot_flag=0; dws =1; % store parameters SS =[]; MU =[]; % Compute Psi Psi =zeros(r*Nf ,Nt*r); for t= 1: Nt Psi( : , ((t-1)*r+ 1) :((t-1)*r+r)) = ( kron(eye(r), P(t,:) ))’ ; end fs =zeros(Nt ,d,Nk); new_mu =w; new_S =lambda*eye (d*Nf); RREPS =zeros (1, Nk); WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end RREPS(1) = mean(mean(- abs (Qpm(tg ,2:4) - Qg)) ); REPS_output=RREPS (1) ; W=zeros (r*Nf ,Nk); % % figure % Colorset = varycolor (50) ; % plot (Q (: ,2:8) ,’b’, ’ LineWidth ’ ,2) % hold on iter = 1; % inicialize Omega [U,S,V] = svd (new_f ’); Om_old =U(: ,1:r); % inicialize mu and Sigma f_aux =new_f ’; z=zeros (r*Nt ,1) ; 68
for t= 1: Nt z( (t-1)*r+1 : t*r,1) = pinv(Om_old)* f_aux (:,t); end Psi_aux =zeros(r*Nt ,Nf*r); for t= 1: Nt Psi_aux(((t-1)*r+ 1) :((t-1)*r+r) , :) = Psi( : , ((t-1)*r+ 1) :((t-1)*r+ r))’ ; end old_mu =pinv (Psi_aux) * z; old_S = 1000* eye(r*Nf); % inicialize de new_mu i new_S new_mu =old_mu; new_S =old_S ; % % nova t r a j e c t r i a % new_Q (: ,1) = Q (: ,1) ; % new_Q (: ,2:5) = Q (: ,2:5) ; % new_Q (: ,6:9) = Q (: ,9:12); % new_Q (: ,10:13) = Q (: ,16:19); RmeanREPS=zeros(Nupdates+1 ,2) ; for iter = 1: Nupdates % while ( abs ( Rmean ( iter )) > 0.05) [iter RmeanREPS (iter)] RREPS =zeros (1, Nk); % mu and Sigma for k= 1: Nk W(:,k) = mvnrnd(new_mu ,new_S )’ ; % Sample clear new_f ; clear new_Q ; % new trajectory new_Q (: ,1) = Q(: ,1); new_Q (:,2:d+1) = Q(:,2:d+1); new_Q (:,d+2:2* d+1) = Q(:,d+2:2* d+1) ; % fitting f for t= 1: Nt new_f (t,:) = ( Om_old *( kron(eye(r), P(t,:))* W(: ,k))) ’; end % trajectory for i= 2: Nt new_Q (i,2*d+2:3* d+1) = tau*alphaz* ( betaz *(g-new_Q (i-1,2:d+1) ) - new_Q(i-1,d+2:2* d+1) / tau) + new_f(i,:) ; new_Q (i,d+2:2*d+1) = new_Q (i-1 ,d+2:2* d+1) + dt*new_Q (i,2*d+2:3*d+1); new_Q (i,2:d+1) = new_Q(i-1,2:d+1) + dt*new_Q (i,d+2:2*d+1) ; end ALLQ {k}= new_Q(:,2:d+1); if plot_flag ==1 69
plot (new_Q (: ,2) ,’b’) hold on end NEW_F {k} = new_f ’; WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end n= 3; m= 1; % break indx into 3 parts because n-m+1 = 3 ( points definig the variety ) indx1 =randi([1 floor(Nt /3)], 1, 500) ; indx2 =randi([ floor (Nt /3) floor(2* Nt /3)], 1, 500); indx3 =randi([ floor (2* Nt /3) Nt], 1, 500) ; [DIST,Qm ] = mirr_traj (m,n,indx1 ,indx2 ,indx3,Nt ,d,Qc1,Qc2 ,Qpm); RREPS (k)= mean (mean (- abs (Qpm(tg ,2:4) - Qg)) ); end % figure % plot (- abs ( new_Q (50 ,2:8) - Q1)) % title ( iter ) % figure % plot (0.000015* sum ( new_Q (: ,16:22) ) .^2 ) % title ( iter ) REPS ;% -> new_mu and new_S Fweighted =zeros (d,Nt); for i= 1: Nk Fweighted =Fweighted+dw(i)* NEW_F{i}/ sum(dw); end % build coordination matrix if iter ~= 1 Om_old =Om ; end % [U,S,V] = svd (Fweighted ); % if iter ==1 Om =U(: ,1: r); % end O_old =kron (eye(Nt), Om_old); O=kron (eye (Nt),Om); M=pinv (O_old *Psi’)*O*Psi ’; if iter ~= 1 old_mu =new_mu; old_S =new_S; 70
end % update policy new_mu =pinv (M)* old_mu ; new_S =pinv (M)*(old_S + (M*new_mu -old_mu) * (M*new_mu -old_mu )’ ) * pinv (M) ’; % new trajectory clear new_f; clear new_Q; new_Q (: ,1) = Q(: ,1); new_Q (1 ,2:d+1) =Q(1 ,2:d+1); new_Q (1,d+2:2* d+1)=Q(1,d+2:2* d+1); Id =eye(r); for t= 1: Nt new_f (t,:) = ( Om *( kron (eye(r), P(t,:))* new_mu ) ) ’; end for i= 2: Nt new_Q (i,2*d+2:3* d+1) = tau*alphaz* ( betaz *(g-new_Q(i-1,2:d+1) ) - new_Q (i-1,d+2:2* d+1) / tau) + new_f (i-1 ,:); new_Q (i,d+2:2* d+1) = new_Q (i-1,d+2:2*d+1) + dt*new_Q(i,2*d+2:3*d+1); new_Q (i,2:d+1) = new_Q(i-1,2:d+1) + dt*new_Q (i,d+2:2* d+1) ; end WAM; [Qc1,Qc2 ] = change_ref (new_Q ,Q2 ,l1 ,l2 ,l3 ,theta,Nt ,d,wam); % middle point curve Qpm (: ,1) = Qc1 (: ,1) ; for i= 1: Nt Qpm(i,2:4) = ( Qc1 (i,2:4) + Qc2(i,2:4) ) / 2; end % Reward REPS_output(iter+1)= mean(mean(- abs (Qpm (tg ,2:4) - Qg)) ); RmeanREPS (iter +1 ,:) = [ mean(REPS_output) ,2* std(REPS_output)]; MU =[ MU;new_mu ’]; SS =[ SS;svd(new_S) ’]; % plot ( new_Q (: ,2:8) ,’ Color ’, Colorset (1 ,:) ) ; % title (’ QREPS vs newQREPS ’) ; if plot_flag ==1 close all plot (new_Q (: ,2) ,’k’,’ LineWidth ’ ,2) hold on end end figure plot(RmeanREPS(2: end ,1) ,’b ’,’ LineWidth ’ ,2) hold on plot(RmeanREPS(2: end ,1) + RmeanREPS (2: end ,2) ,’b ’,’ LineWidth ’ ,1) plot(RmeanREPS(2: end ,1) - RmeanREPS (2: end ,2) ,’b’,’ LineWidth ’ ,1) title(’ RmeanREPS ’) % figure 71
% plot ( RREPS ) % hold on % plot ( RmeanREPS ) % title (’ Reward ’) % legend (’ RREPS ’, ’ RmeanREPS ’) % end %% REPS % input : Ekl =0.5 % REWARDS : Vector fila amb els rewards de les trajectories % regularization : valor per regularitzar el rang de Sw , prendre % 0.001 , per exemple . % SAMPLES : matriu on cada columna s un vector w de pesos d ’una % mostra . s a dir , cada columna s w -N(mw ,Sw ) % output : % new_mu : mitja ponderada % new_S : nova c o v a r i a n a %fmincon options %dw : pesos Ekl =0.5; REWARDS= (RREPS-min(RREPS)) /( max (RREPS ) -min(RREPS )); SAMPLES=W; regularization=1; options =optimset( fmincon);options.Display=’off’;options.Algorithm=’active-set’;ndatause=size(REWARDS,2);dualFunctionActual = (eta_)dualfunction(eta_ ,REWARDS,Ekl); eta2 =fmincon(dualFunctionActual ,0.01 ,[] , [], [], [], 0.0005 , 100 ,[] , options); if or (eta2==100 , eta2==0.0005) warning(’Eta in its boundary ’) eta2 end dw=exp (( REWARDS-max(REWARDS)* ones(size (REWARDS)))/ eta2 ) ’; Z=( sum(dw)*sum(dw) - sum (dw .^ 2) )/ sum (dw); % parameter distribution update new_mu=sum(bsxfun(times, SAMPLES’, dw)’,2)./sum(dw);summ=0;for ak=1:ndatausesumm=summ+dw(ak)*((SAMPLES(:,ak)-new_mu)*(SAMPLES(:,ak)-new_mu)’);endnew_S=summ./(Z+0.000000001);new_S=new_S+eye(size(new_S))*regularization; function [Sc ,Sjerk ]= rolloutcost(Ye ,Ydde ,npi,Ppi,Rpi) r4=WAMarm4; for i=1: size (Ye ,1) Taa=fkine (r4 ,Ye(i,1:4) ’) *[0;0;0.3;1]; Qaa=Taa (1:3 ,1); % Xex =[ Xex ;Qaa ’]; if i<size(Ye ,1) Ct(i)= circlecost (Qaa,Ppi’,npi,Rpi); 72