plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
RobinAmsters/GT_mobile_robotics-master
|
doesblockexist.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/doesblockexist.m
| 1,690 |
utf_8
|
8c3d04d595b2f2e7d26bdb692a63c7b6
|
%DOESBLOCKEXIST Check existence of block in Simulink model
%
% RES = doesblockexist(MDLNAME, BLOCKADDRESS) is a logical result that
% indicates whether or not the block BLOCKADDRESS exists within the
% Simulink model MDLNAME.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also symexpr2slblock, distributeblocks.
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [res] = doesblockexist(mdlName, blockAddress)
wasntLoaded = 0;
if ~bdIsLoaded(mdlName)
load_system(mdlName)
wasntLoaded = 1;
end
blockList = find_system(mdlName);
blockList = strfind(blockList,blockAddress);
emptyList = cellfun(@isempty,blockList);
res = any(~emptyList);
if wasntLoaded
close_system(mdlName)
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plotbotopt.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/plotbotopt.m
| 1,024 |
utf_8
|
d73b36da5fc6f18299eceba1ff5438a9
|
%PLOTBOTOPT Define default options for robot plotting
%
% A user provided function that returns a cell array of default
% plot options for the SerialLink.plot method.
%
% See also SerialLink.plot.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function options = plotbotopt
options = {'base'};
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
jtraj.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/jtraj.m
| 3,099 |
utf_8
|
d2a0b895ed85f50c11229499ed78b964
|
%JTRAJ Compute a joint space trajectory
%
% [Q,QD,QDD] = JTRAJ(Q0, QF, M) is a joint space trajectory Q (MxN) where the joint
% coordinates vary from Q0 (1xN) to QF (1xN). A quintic (5th order) polynomial is used
% with default zero boundary conditions for velocity and acceleration.
% Time is assumed to vary from 0 to 1 in M steps. Joint velocity and
% acceleration can be optionally returned as QD (MxN) and QDD (MxN) respectively.
% The trajectory Q, QD and QDD are MxN matrices, with one row per time step,
% and one column per joint.
%
% [Q,QD,QDD] = JTRAJ(Q0, QF, M, QD0, QDF) as above but also specifies
% initial QD0 (1xN) and final QDF (1xN) joint velocity for the trajectory.
%
% [Q,QD,QDD] = JTRAJ(Q0, QF, T) as above but the number of steps in the
% trajectory is defined by the length of the time vector T (Mx1).
%
% [Q,QD,QDD] = JTRAJ(Q0, QF, T, QD0, QDF) as above but specifies initial and
% final joint velocity for the trajectory and a time vector.
%
% Notes::
% - When a time vector is provided the velocity and acceleration outputs
% are scaled assumign that the time vector starts at zero and increases
% linearly.
%
% See also QPLOT, CTRAJ, SerialLink.jtraj.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [qt,qdt,qddt] = jtraj(q0, q1, tv, qd0, qd1)
if length(tv) > 1
tscal = max(tv);
t = tv(:)/tscal;
else
tscal = 1;
t = (0:(tv-1))'/(tv-1); % normalized time from 0 -> 1
end
q0 = q0(:);
q1 = q1(:);
if nargin == 3
qd0 = zeros(size(q0));
qd1 = qd0;
elseif nargin == 5
qd0 = qd0(:);
qd1 = qd1(:);
else
error('incorrect number of arguments')
end
% compute the polynomial coefficients
A = 6*(q1 - q0) - 3*(qd1+qd0)*tscal;
B = -15*(q1 - q0) + (8*qd0 + 7*qd1)*tscal;
C = 10*(q1 - q0) - (6*qd0 + 4*qd1)*tscal;
E = qd0*tscal; % as the t vector has been normalized
F = q0;
tt = [t.^5 t.^4 t.^3 t.^2 t ones(size(t))];
c = [A B C zeros(size(A)) E F]';
qt = tt*c;
% compute optional velocity
if nargout >= 2
c = [ zeros(size(A)) 5*A 4*B 3*C zeros(size(A)) E ]';
qdt = tt*c/tscal;
end
% compute optional acceleration
if nargout == 3
c = [ zeros(size(A)) zeros(size(A)) 20*A 12*B 6*C zeros(size(A))]';
qddt = tt*c/tscal^2;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
simulinkext.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/simulinkext.m
| 1,609 |
utf_8
|
3c852724210e0c51e67283a9079f2a28
|
%SIMULINKEXT Return file extension of Simulink block diagrams.
%
% str = simulinkext() is either
% - '.mdl' if Simulink version number is less than 8
% - '.slx' if Simulink version numberis larger or equal to 8
%
% Notes::
% The file extension for Simulink block diagrams has changed from Matlab 2011b to Matlab 2012a.
% This function is used for backwards compatibility.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also symexpr2slblock, doesblockexist, distributeblocks.
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function str = simulinkext()
if verLessThan('simulink','8')
str = '.mdl';
else
str = '.slx';
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
Dubbins.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/Dubbins.m
| 11,339 |
utf_8
|
0b0b1d5e711aa199849ecc7bc3f33e5a
|
% Dubbins path planner sample code
%
% P = Dubbins(q0, qf, maxc, dl) finds the shortest path between configurations
% q0 and qf where each is a vector [x y theta]. maxc is the maximum curvature
%
% The robot can only move forwards and the path consists of 3 segments
% which have zero or maximum curvature maxc. There are discontinuities in
% velocity and steering commands (cusps) at the transitions between the
% segments.
%
% Example::
% q0 = [1 1 pi/4]'; qf = [1 1 pi]';
% p = Dubbins(q0, qf, 1, 0.05)
% p.plot('circles', 'k--', 'join', {'Marker', 'o', 'MarkerFaceColor', 'k'});
%
% or alternatively
%
% Dubbins.test
%
% References::
% - Dubins, L.E.
% On Curves of Minimal Length with a Constraint on Average Curvature, and with Prescribed Initial and Terminal Positions and Tangents
% American Journal of Mathematics. 79(3), July 1957, pp497?516.
% doi:10.2307/2372560.
%
% Acknowledgement::
% - Based on python code from Python Robotics by Atsushi Sakai
% https://github.com/AtsushiSakai/PythonRobotics
%
% See also Navigation, ReedsShepp
% each path is described by a 3-letter word.
% the algorithm finds a bunch of possible paths, then chooses the shortest
% one. Each word is represented by a structure with fields:
% - word a 3-letter sequence drawn from the letters LRLS
% - L total path length
% - lengths a 3-vector of lengths, signed to indicate the direction of
% curvature
% - traj a cell array of 3xN matrices giving the path for each segment
classdef Dubbins < handle
properties
best % the best path
words
maxc
end
methods
function obj = Dubbins(q0, qf, maxcurv, dl)
obj.maxc = maxcurv;
% return the word describing the shortest path
obj.words = generate_path(q0, qf, maxcurv);
if isempty(obj.words)
error('no path');
end
% find shortest path
[~,k] = min( [obj.words.L] );
obj.best = obj.words(k);
% add the trajectory
obj.best = generate_trajectories(obj.best, maxcurv, dl, q0);
end
function p = path(obj)
p = [obj.best.traj{:}]';
end
function show(obj)
for w=obj.words
fprintf('%s (%g): [%g %g %g]\n', w.word, w.L, w.lengths);
end
end
function n = length(obj)
n = length(obj.words);
end
function plot(obj, varargin)
%DUBBINS.PLOT Plot Dubbins path
%
% DP.plot(OPTIONS) plots the optimal Dubbins path.
%
% Options::
% 'circle',LS Plot the full circle corresponding to each curved segment
% 'join',LS Plot a marker at the intermediate segment boundaries
%
% Notes::
% - LS can be a simple LineSpec string or a cell array of Name,Value pairs.
opt.circles = [];
opt.join = [];
opt = tb_optparse(opt, varargin);
if ~ishold
clf
end
hold on
word = obj.best;
for i=1:3
color = 'b';
if i == 1
x = word.traj{i}(1,:);
y = word.traj{i}(2,:);
else
% ensure we join up the lines in the plot
x = [x(end) word.traj{i}(1,:)];
y = [y(end) word.traj{i}(2,:)];
end
if ~isempty(opt.join) && i<3
plot(x(end), y(end), opt.join{:});
end
if ~isempty(opt.circles)
T = SE2(word.traj{i}(:,1));
R = 1/obj.maxc;
switch word.word(i)
case 'L'
c = T*[0; R];
case 'R'
c = T*[0; -R];
case 'S'
continue
end
plot_circle(c, R, opt.circles)
plot_point(c, 'k+')
end
plot(x, y, color, 'LineWidth', 2);
end
grid on; xlabel('X'); ylabel('Y')
hold off
axis equal
title('Dubbins path')
end
function s = char(obj)
s = '';
s = strvcat(s, sprintf('Dubbins path: %s, length %f', obj.best.word, obj.best.L));
s = strvcat(s, sprintf(' segment lengths: %f %f %f', obj.best.lengths));
end
function display(obj)
disp( char(obj) );
end
end
methods(Static)
function test()
maxcurv = 1;
dl = 0.05;
q0 = [1 1 pi/4]'; qf = [1 1 pi]';
p = Dubbins(q0, qf, maxcurv, dl)
p.plot('circles', 'k--', 'join', {'Marker', 'o', 'MarkerFaceColor', 'k'});
hold on
plot_vehicle(q0, 'r');
plot_vehicle(qf, 'b');
hold off
end
end
end
function out = generate_trajectories(word, maxc, d, q0)
% initialize the configuration
p0 = q0;
% output struct is same as input struct, but we will add:
% - a cell array of trajectories
% - a vector of directions -1 or +1
out = word;
for i=1:3
m = word.word(i);
l = word.lengths(i);
x = 0:d:abs(l);
if x(end) ~= abs(l)
x = [x abs(l)];
end
p = pathseg(x, m, maxc, p0);
% add new fields to the struct
if i == 1
out.traj{i} = p;
else
% for subsequent segments skip the first point, same as last
% point of previous segment
out.traj{i} = p(:,2:end);
end
out.dir(i) = sign(l);
% initial state for next segment is last state of this segment
p0 = p(:,end);
end
end
function q = pathseg(l, m, maxc, p0)
q0 = p0(:);
switch m
case 'S'
f = @(t,q) [cos(q(3)), sin(q(3)), 0]';
case 'L'
f = @(t,q) [cos(q(3)), sin(q(3)), maxc]';
case 'R'
f = @(t,q) [cos(q(3)), sin(q(3)), -maxc]';
end
[t,q] = ode45(f, l, q0);
q = q'; % points are column vectors
end
function words = generate_path(q0, q1, maxc)
% return a list of all possible words
q0 = q0(:); q1 = q1(:);
dq = q1 - q0;
dth = dq(3);
xy = rot2(q0(3))' * dq(1:2);
x = xy(1); y = xy(2);
d = norm([x y]) * maxc;
% [x y d]
theta = mod2pi(atan2(y, x));
alpha = mod2pi(-theta);
beta = mod2pi(dth - theta);
words = [];
words = LSL(alpha, beta, d, 'LSL', words);
words = RSR(alpha, beta, d, 'RSR', words);
words = LSR(alpha, beta, d, 'LSR', words);
words = RSL(alpha, beta, d, 'RSL', words);
words = RLR(alpha, beta, d, 'RLR', words);
words = LRL(alpha, beta, d, 'LRL', words);
% account for non-unit curvature
for i=1:numel(words)
words(i).lengths = words(i).lengths / maxc;
words(i).L = words(i).L / maxc;
end
end % class Dubbins
%%
function owords = LSL(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
tmp0 = d + sa - sb;
p_squared = 2 + (d * d) - (2 * c_ab) + (2 * d * (sa - sb));
if p_squared < 0
t = NaN; p = NaN; q = NaN;
else
tmp1 = atan2((cb - ca), tmp0);
t = mod2pi(-alpha + tmp1);
p = sqrt(p_squared);
q = mod2pi(beta - tmp1);
end
owords = addpath(words, [t, p, q], word);
end
function owords = RSR(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
tmp0 = d - sa + sb;
p_squared = 2 + (d * d) - (2 * c_ab) + (2 * d * (sb - sa));
if p_squared < 0
t = NaN; p = NaN; q = NaN;
else
tmp1 = atan2((ca - cb), tmp0);
t = mod2pi(alpha - tmp1);
p = sqrt(p_squared);
q = mod2pi(-beta + tmp1);
end
owords = addpath(words, [t, p, q], word);
end
function owords = LSR(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
p_squared = -2 + (d * d) + (2 * c_ab) + (2 * d * (sa + sb));
if p_squared < 0
t = NaN; p = NaN; q = NaN;
else
p = sqrt(p_squared);
tmp2 = atan2((-ca - cb), (d + sa + sb)) - atan2(-2.0, p);
t = mod2pi(-alpha + tmp2);
q = mod2pi(-mod2pi(beta) + tmp2);
end
owords = addpath(words, [t, p, q], word);
end
function owords = RSL(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
p_squared = (d * d) - 2 + (2 * c_ab) - (2 * d * (sa + sb));
if p_squared < 0
t = NaN; p = NaN; q = NaN;
else
p = sqrt(p_squared);
tmp2 = atan2((ca + cb), (d - sa - sb)) - atan2(2.0, p);
t = mod2pi(alpha - tmp2);
q = mod2pi(beta - tmp2);
end
owords = addpath(words, [t, p, q], word);
end
function owords = RLR(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
tmp_rlr = (6.0 - d * d + 2.0 * c_ab + 2.0 * d * (sa - sb)) / 8.0;
if abs(tmp_rlr) > 1
t = NaN; p = NaN; q = NaN;
else
p = mod2pi(2 * pi - acos(tmp_rlr));
t = mod2pi(alpha - atan2(ca - cb, d - sa + sb) + mod2pi(p / 2.0));
q = mod2pi(alpha - beta - t + mod2pi(p));
owords = addpath(words, [t, p, q], word);
end
end
function owords = LRL(alpha, beta, d, word, words)
sa = sin(alpha);
sb = sin(beta);
ca = cos(alpha);
cb = cos(beta);
c_ab = cos(alpha - beta);
tmp_lrl = (6.0 - d * d + 2.0 * c_ab + 2.0 * d * (- sa + sb)) / 8.0;
if abs(tmp_lrl) > 1
t = NaN; p = NaN; q = NaN;
else
p = mod2pi(2 * pi - acos(tmp_lrl));
t = mod2pi(-alpha - atan2(ca - cb, d + sa - sb) + p / 2.0);
q = mod2pi(mod2pi(beta) - alpha - t + mod2pi(p));
end
owords = addpath(words, [t, p, q], word);
end
function owords = addpath(words, lengths, ctypes)
owords = words;
% create a struct to represent this segment
word.word = ctypes;
word.lengths = lengths;
if any(isnan(lengths))
return;
end
word.L = sum(abs(lengths));
owords = [owords word];
end
function v = mod2pi(theta)
%v = theta - 2.0 * pi * floor(theta / 2.0 / pi)
v = mod(theta, 2*pi);
end
function v = pi_2_pi(angle)
%v = (angle + pi) % (2 * math.pi) - math.pi
v = mod(angle + pi, 2*pi) - pi;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
eulplot.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/eulplot.m
| 1,112 |
utf_8
|
fd8e283f35c793926d0d5ecba2c99a7d
|
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function eulplot(a,b,c)
R = eye(3,3);
trplot( R, 'unit', 'frame', '0', 'color', 'k');
hold on
R = R * rotz(a);
trplot( R, 'unit', 'frame', '1', 'color', 'r');
R = R * roty(b);
trplot( R, 'unit', 'frame', '2', 'color', 'g');
R = R * rotz(c);
trplot( R, 'unit', 'frame', '3', 'color', 'b');
hold off
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
tpoly.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/tpoly.m
| 4,753 |
utf_8
|
f20c5d817480deea50f0e188c4f9ad87
|
%TPOLY Generate scalar polynomial trajectory
%
% [S,SD,SDD] = TPOLY(S0, SF, M) is a scalar trajectory (Mx1) that varies
% smoothly from S0 to SF in M steps using a quintic (5th order) polynomial.
% Velocity and acceleration can be optionally returned as SD (Mx1) and SDD
% (Mx1) respectively.
%
% TPOLY(S0, SF, M) as above but plots S, SD and SDD versus time in a single
% figure.
%
% [S,SD,SDD] = TPOLY(S0, SF, T) as above but the trajectory is computed at
% each point in the time vector T (Mx1).
%
% [S,SD,SDD] = TPOLY(S0, SF, T, QD0, QD1) as above but also specifies the
% initial and final velocity of the trajectory.
%
% Notes::
% - If M is given
% - Velocity is in units of distance per trajectory step, not per second.
% - Acceleration is in units of distance per trajectory step squared, not
% per second squared.
% - If T is given then results are scaled to units of time.
% - The time vector T is assumed to be monotonically increasing, and time
% scaling is based on the first and last element.
%
% Reference:
% Robotics, Vision & Control
% Chap 3
% Springer 2011
%
% See also LSPB, JTRAJ.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% [S,SD,SDD] = TPOLY(S0, SF, N, SD0, SDF) as above but specifies initial
% and final joint velocity for the trajectory.
%
% [S,SD,SDD] = TPOLY(S0, SF, T, SD0, SDF) as above but specifies initial
% and final joint velocity for the trajectory and time vector T.
%
% Notes::
% - In all cases if no output arguments are specified S, SD, and SDD are plotted
% against time.
%
% See also LSPB, JTRAJ.
function [s,sd,sdd] = tpoly(q0, qf, t, qd0, qdf)
t0 = t;
if isscalar(t)
t = (0:t-1)';
else
t = t(:);
end
if nargin < 4
qd0 = 0;
end
if nargin < 5
qdf = 0;
end
plotsargs = {'.-', 'Markersize', 16};
tf = max(t);
% solve for the polynomial coefficients using least squares
X = [
0 0 0 0 0 1
tf^5 tf^4 tf^3 tf^2 tf 1
0 0 0 0 1 0
5*tf^4 4*tf^3 3*tf^2 2*tf 1 0
0 0 0 2 0 0
20*tf^3 12*tf^2 6*tf 2 0 0
];
coeffs = (X \ [q0 qf qd0 qdf 0 0]')';
% coefficients of derivatives
coeffs_d = coeffs(1:5) .* (5:-1:1);
coeffs_dd = coeffs_d(1:4) .* (4:-1:1);
% evaluate the polynomials
p = polyval(coeffs, t);
pd = polyval(coeffs_d, t);
pdd = polyval(coeffs_dd, t);
switch nargout
case 0
if isscalar(t0)
% for scalar time steps, axis is labeled 1 .. M
xt = t+1;
else
% for vector time steps, axis is labeled by vector M
xt = t;
end
clf
subplot(311)
plot(xt, p, plotsargs{:}); grid; ylabel('$s$', 'FontSize', 16, 'Interpreter','latex');
subplot(312)
plot(xt, pd, plotsargs{:}); grid;
if isscalar(t0)
ylabel('$ds/dk$', 'FontSize', 16, 'Interpreter','latex');
else
ylabel('$ds/dt$', 'FontSize', 16, 'Interpreter','latex');
end
subplot(313)
plot(xt, pdd, plotsargs{:}); grid;
if isscalar(t0)
ylabel('$ds^2/dk^2$', 'FontSize', 16, 'Interpreter','latex');
else
ylabel('$ds^2/dt^2$', 'FontSize', 16, 'Interpreter','latex');
end
if ~isscalar(t0)
xlabel('t (seconds)')
else
xlabel('k (step)');
for c=findobj(gcf, 'Type', 'axes')
set(c, 'XLim', [1 t0]);
end
end
shg
case 1
s = p;
case 2
s = p;
sd = pd;
case 3
s = p;
sd = pd;
sdd = pdd;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
models.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/models.m
| 3,393 |
utf_8
|
29eb9c620a850baf86f3c248256a91cf
|
%MODELS Summarise and search available robot models
%
% MODELS() lists keywords associated with each of the models in Robotics Toolbox.
%
% MODELS(QUERY) lists those models that match the keyword QUERY. Case is
% ignored in the comparison.
%
% M = MODELS(QUERY) as above but returns a cell array (Nx1) of the names of the
% M-files that define the models.
%
% Examples::
% models
% models('modified_DH') % all models using modified DH notation
% models('kinova') % all Kinova robot models
% models('6dof') % all 6dof robot models
% models('redundant') % all redundant robot models, >6 DOF
% models('prismatic') % all robots with a prismatic joint
%
% Notes::
% - A model is a file mdl_*.m in the models folder of the RTB directory.
% - The keywords are indicated by a line '% MODEL: ' after the main comment
% block.
%
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function name_ = models(query)
% first find the path to the models
pth = mfilename('fullpath');
pth = fileparts(pth);
pth = fullfile(pth, 'models');
assert(exist(pth, 'dir') > 0, 'RTB:models:nomodel', 'models folder not found');
models = dir(fullfile(pth, 'mdl_*.m'));
info = {};
name = {};
for model=models'
fid = fopen( fullfile(pth, model.name), 'r');
while true
line = fgetl(fid);
if line == -1
break;
end
if (length(line) > 11) && (strcmp(line(1:11), '% Copyright:') == 1)
% an empty line, done with the header block
break;
end
[p,n,e] = fileparts(model.name);
if (length(line) > 8) && (strcmp(line(1:8), '% MODEL:') == 1)
% we have a model description line
line = line(10:end); % trim off the tag
if nargin > 0
% we have a query
if strfind(lower(line), lower(query))
info = [info; [line ' (' n ')' ]];
name = [name; n];
end
else
% no query, report all
info = [info; [line ' (' n ')' ]];
name = [name n];
end
break
end
end
fclose(fid);
end
% optionally return a list of model names
if nargout == 1
name_ = name';
else
% now sort and print the matching models
for i = sort(info)'
fprintf('%s\n', i{1});
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mstraj.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/mstraj.m
| 8,016 |
utf_8
|
8469f3b14161a23681a08daf1b228f37
|
%MSTRAJ Multi-segment multi-axis trajectory
%
% TRAJ = MSTRAJ(WP, QDMAX, TSEG, Q0, DT, TACC, OPTIONS) is a trajectory
% (KxN) for N axes moving simultaneously through M segment. Each segment
% is linear motion and polynomial blends connect the segments. The axes
% start at Q0 (1xN) and pass through M-1 via points defined by the rows of
% the matrix WP (MxN), and finish at the point defined by the last row of WP.
% The trajectory matrix has one row per time step, and one column per
% axis. The number of steps in the trajectory K is a function of the
% number of via points and the time or velocity limits that apply.
%
% - WP (MxN) is a matrix of via points, 1 row per via point, one column
% per axis. The last via point is the destination.
% - QDMAX (1xN) are axis speed limits which cannot be exceeded,
% - TSEG (1xM) are the durations for each of the K segments
% - Q0 (1xN) are the initial axis coordinates
% - DT is the time step
% - TACC (1x1) is the acceleration time used for all segment transitions
% - TACC (1xM) is the acceleration time per segment, TACC(i) is the acceleration
% time for the transition from segment i to segment i+1. TACC(1) is also
% the acceleration time at the start of segment 1.
%
% TRAJ = MSTRAJ(WP, QDMAX, TSEG, [], DT, TACC, OPTIONS) as above but the
% initial coordinates are taken from the first row of WP.
%
% TRAJ = MSTRAJ(WP, QDMAX, Q0, DT, TACC, QD0, QDF, OPTIONS) as above
% but additionally specifies the initial and final axis velocities (1xN).
%
% Options::
% 'verbose' Show details.
%
% Notes::
% - Only one of QDMAX or TSEG can be specified, the other is set to [].
% - If no output arguments are specified the trajectory is plotted.
% - The path length K is a function of the number of via points, Q0, DT
% and TACC.
% - The final via point P(end,:) is the destination.
% - The motion has M segments from Q0 to P(1,:) to P(2,:) ... to P(end,:).
% - All axes reach their via points at the same time.
% - Can be used to create joint space trajectories where each axis is a joint
% coordinate.
% - Can be used to create Cartesian trajectories where the "axes"
% correspond to translation and orientation in RPY or Euler angle form.
% - If qdmax is a scalar then all axes are assumed to have the same
% maximum speed.
%
% See also MTRAJ, LSPB, CTRAJ.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [TG, t, info] = mstraj(segments, qdmax, tsegment, q0, dt, Tacc, varargin)
if isempty(q0)
q0 = segments(1,:);
segments = segments(2:end,:);
end
assert(size(segments,2) == size(q0,2), 'RTB:mstraj:badarg', 'WP and Q0 must have same number of columns');
assert(xor(~isempty(qdmax), ~isempty(tsegment)), 'RTB:mstraj:badarg', 'Must specify either qdmax or tsegment, but not both');
if isempty(qdmax)
assert(length(tsegment) == size(segments,1), 'RTB:mstraj:badarg', 'Length of TSEG does not match number of segments');
end
if isempty(tsegment)
if length(qdmax) == 1
% if qdmax is a scalar assume all axes have the same speed
qdmax = repmat(qdmax, 1, numcols(segments));
end
assert(length(qdmax) == size(segments,2), 'RTB:mstraj:badarg', 'Length of QDMAX does not match number of axes');
end
ns = numrows(segments);
nj = numcols(segments);
[opt,args] = tb_optparse([], varargin);
if length(args) > 0
qd0 = args{1};
else
qd0 = zeros(1, nj);
end
if length(args) > 1
qdf = args{2};
else
qdf = zeros(1, nj);
end
% set the initial conditions
q_prev = q0;
qd_prev = qd0;
clock = 0; % keep track of time
arrive = []; % record planned time of arrival at via points
tg = [];
taxis = [];
for seg=1:ns
if opt.verbose
fprintf('------------------- segment %d\n', seg);
end
% set the blend time, just half an interval for the first segment
if length(Tacc) > 1
tacc = Tacc(seg);
else
tacc = Tacc;
end
tacc = ceil(tacc/dt)*dt;
tacc2 = ceil(tacc/2/dt) * dt;
if seg == 1
taccx = tacc2;
else
taccx = tacc;
end
% estimate travel time
% could better estimate distance travelled during the blend
q_next = segments(seg,:); % current target
dq = q_next - q_prev; % total distance to move this segment
%% probably should iterate over the next section to get qb right...
% while 1
% qd_next = (qnextnext - qnext)
% tb = abs(qd_next - qd) ./ qddmax;
% qb = f(tb, max acceleration)
% dq = q_next - q_prev - qb
% tl = abs(dq) ./ qdmax;
if ~isempty(qdmax)
% qdmax is specified, compute slowest axis
qb = taccx * qdmax / 2; % distance moved during blend
tb = taccx;
% convert to time
tl = abs(dq) ./ qdmax;
%tl = abs(dq - qb) ./ qdmax;
tl = ceil(tl/dt) * dt;
% find the total time and slowest axis
tt = tb + tl;
[tseg,slowest] = max(tt);
info(seg).slowest = slowest;
info(seg).segtime = tseg;
info(seg).axtime = tt;
info(seg).clock = clock;
% best if there is some linear motion component
if tseg <= 2*tacc
tseg = 2 * tacc;
end
elseif ~isempty(tsegment)
% segment time specified, use that
tseg = tsegment(seg);
slowest = NaN;
end
% log the planned arrival time
arrive(seg) = clock + tseg;
if seg > 1
arrive(seg) = arrive(seg) + tacc2;
end
if opt.verbose
fprintf('seg %d, slowest axis %d, time required %.4g\n', ...
seg, slowest, tseg);
end
%% create the trajectories for this segment
% linear velocity from qprev to qnext
qd = dq / tseg;
% add the blend polynomial
qb = jtraj(q0, q_prev+tacc2*qd, 0:dt:taccx, qd_prev, qd);
tg = [tg; qb(2:end,:)];
clock = clock + taccx; % update the clock
% add the linear part, from tacc/2+dt to tseg-tacc/2
for t=tacc2+dt:dt:tseg-tacc2
s = t/tseg;
q0 = (1-s) * q_prev + s * q_next; % linear step
tg = [tg; q0];
clock = clock + dt;
end
q_prev = q_next; % next target becomes previous target
qd_prev = qd;
end
% add the final blend
qb = jtraj(q0, q_next, 0:dt:tacc2, qd_prev, qdf);
tg = [tg; qb(2:end,:)];
info(seg+1).segtime = tacc2;
info(seg+1).clock = clock;
% plot a graph if no output argument
if nargout == 0
t = (0:numrows(tg)-1)'*dt;
clf
plot(t, tg, '-o');
hold on
plot(arrive, segments, 'bo', 'MarkerFaceColor', 'k');
hold off
grid
xlabel('time');
xaxis(t(1), t(end))
return
end
if nargout > 0
TG = tg;
end
if nargout > 1
t = (0:numrows(tg)-1)'*dt;
end
if nargout > 2
infout = info;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
getprofilefunctionstats.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/getprofilefunctionstats.m
| 1,652 |
utf_8
|
cae43e948e7e87341a4a673e3632306d
|
%GETPROFILEFUNCTIONSTATS Summary of this function goes here
% Detailed explanation goes here
%
% Author::
% Joern Malzahn, ([email protected])
% Copyright (C) 2012-2018, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [ funstats] = getprofilefunctionstats( pstats , desfun, varargin)
nEl = numel(pstats.FunctionTable);
desfname = which(desfun);
funstats = [];
if isempty(desfname)
error(['Function ', desfun, ' not found!']);
end
funtype = '';
if nargin == 3
switch lower(varargin{1})
case 'm-function'
case 'mex-function'
otherwise
error('funtype must be either ''M-function'' or ''MEX-function''!');
end
else
desfun = [desfun '.m'];
end
for iEl = 1:nEl
curstats = pstats.FunctionTable(iEl);
if string(curstats.FileName).endsWith(desfun)
funstats = curstats;
return
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
distancexform.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/distancexform.m
| 10,892 |
utf_8
|
56921fa7d195c8b78a6abcb4c4a16ddc
|
%DISTANCEXFORM Distance transform
%
% D = DISTANCEXFORM(IM, OPTIONS) is the distance transform of the binary
% image IM. The elements of D have a value equal to the shortest distance
% from that element to a non-zero pixel in the input image IM.
%
% D = DISTANCEXFORM(OCCGRID, GOAL, OPTIONS) is the distance transform of
% the occupancy grid OCCGRID with respect to the specified goal point GOAL
% = [X,Y]. The cells of the grid have values of 0 for free space and 1 for
% obstacle. The resulting matrix D has cells whose value is the shortest
% distance to the goal from that cell, or NaN if the cell corresponds to an
% obstacle (set to 1 in OCCGRID).
%
% Options:
% 'euclidean' Use Euclidean (L2) distance metric (default)
% 'cityblock' Use cityblock or Manhattan (L1) distance metric
%
% 'animate' Show the iterations of the computation
% 'delay',D Delay of D seconds between animation frames (default 0.2s)
% 'movie',M Save animation to a movie file or folder
%
% 'noipt' Don't use Image Processing Toolbox, even if available
% 'novlfeat' Don't use VLFeat, even if available
% 'nofast' Don't use IPT, VLFeat or imorph, even if available.
%
% 'delay'
%
% Notes::
% - For the first case Image Processing Toolbox (IPT) or VLFeat will be used if
% available, searched for in that order. They use a 2-pass rather than
% iterative algorithm and are much faster.
% - Options can be used to disable use of IPT or VLFeat.
% - If IPT or VLFeat are not available, or disabled, then imorph is used.
% - If IPT, VLFeat or imorph are not available a slower M-function is used.
% - If the 'animate' option is given then the MATLAB implementation is used.
% - Using imorph requires iteration and is slow.
% - For the second case the Machine Vision Toolbox function imorph is required.
% - imorph is a mex file and must be compiled.
% - The goal is given as [X,Y] not MATLAB [row,col] format.
%
% See also IMORPH, DXform, Animate.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function dx = distancexform(occgrid, varargin)
opt.delay = 0.2;
opt.ipt = true;
opt.vlfeat = true;
opt.fast = true;
opt.metric = {'euclidean', 'cityblock'};
opt.animate = false;
opt.movie = [];
[opt,args] = tb_optparse(opt, varargin);
if opt.movie
opt.animate = true;
end
if opt.animate
opt.fast = false;
opt.ipt = false;
opt.vlfeat = false;
clf
end
count = [];
switch opt.metric
case 'cityblock'
ipt_metric = opt.metric; % if we use bwdistgeodesic
m = [ inf 1 inf
1 0 1
inf 1 inf ];
case 'euclidean'
ipt_metric = 'quasi-euclidean'; % if we use bwdistgeodesic
r2 = sqrt(2);
m = [ r2 1 r2
1 0 1
r2 1 r2 ];
end
if ~isempty(args) && isvec(args{1}, 2)
%% path planning interpretation
% distancexform(world, goal, metric, show)
goal = args{1};
occgrid = double(occgrid);
% check the goal point is sane
assert(occgrid(goal(2), goal(1)) == 0, 'RTB:distancexform:badarg', 'goal inside obstacle')
if exist('imorph', 'file') && opt.fast
if opt.verbose
fprintf('using MVTB:imorph\n');
end
% setup to use imorph
% - set obstacles to NaN
% - set free space to Inf
% - set goal to 0
occgrid(occgrid>0) = NaN;
occgrid(occgrid==0) = Inf;
occgrid(goal(2), goal(1)) = 0;
count = 0;
ninf = Inf; % number of infinities in the map
while 1
occgrid = imorph(occgrid, m, 'plusmin');
count = count+1;
if opt.animate
cmap = [1 0 0; gray(count)];
colormap(cmap)
image(occgrid+1, 'CDataMapping', 'direct');
set(gca, 'Ydir', 'normal');
xlabel('x');
ylabel('y');
pause(opt.delay);
end
ninfnow = sum( isinf(occgrid(:)) ); % current number of Infs
if ninfnow == ninf
% stop if the number of Infs left in the map had stopped reducing
% it may never get to zero if there are unreachable cells in the map
break;
end
ninf = ninfnow;
end
dx = occgrid;
elseif exist('bwdistgeodesic', 'file') && opt.ipt
if opt.verbose
fprintf('using IPT:bwdistgeodesic\n');
end
% solve using IPT
dx = double( bwdistgeodesic(occgrid==0, goal(1), goal(2), ipt_metric) );
else
if opt.verbose
fprintf('using MATLAB code, faster if you install MVTB\n');
end
% setup to use M-function
occgrid(occgrid>0) = NaN;
nans = isnan(occgrid);
occgrid(occgrid==0) = Inf;
occgrid(goal(2), goal(1)) = 0;
count = 0;
ninf = Inf; % number of infinities in the map
anim = Animate(opt.movie);
while 1
occgrid = dxstep(occgrid, m);
occgrid(nans) = NaN;
count = count+1;
if opt.animate
cmap = [1 0 0; gray(count)];
colormap(cmap)
image(occgrid+1, 'CDataMapping', 'direct');
set(gca, 'Ydir', 'normal');
xlabel('x');
ylabel('y');
if opt.animate
anim.add();
else
pause(opt.delay);
end
end
ninfnow = sum( isinf(occgrid(:)) ); % current number of Infs
if ninfnow == ninf
% stop if the number of Infs left in the map had stopped reducing
% it may never get to zero if there are unreachable cells in the map
break;
end
ninf = ninfnow;
end
anim.close();
dx = occgrid;
end
if opt.animate && ~isempty(count)
fprintf('%d iterations, %d unreachable cells\n', count, ninf);
end
else
%% image processing interpretation
% distancexform(world, [metric])
if exist('imorph', 'file') && opt.fast
if opt.verbose
fprintf('using MVTB:imorph\n');
end
% setup to use imorph
% - set free space to Inf
% - set goal to 0
occgrid = double(occgrid);
occgrid(occgrid==0) = Inf;
occgrid(isfinite(occgrid)) = 0;
count = 0;
anim = Animate(opt.movie);
while 1
occgrid = imorph(occgrid, m, 'plusmin');
count = count+1;
if opt.show
cmap = [1 0 0; gray(count)];
colormap(cmap)
image(occgrid+1, 'CDataMapping', 'direct');
set(gca, 'Ydir', 'normal');
xlabel('x');
ylabel('y');
if opt.animate
anim.add();
else
pause(opt.delay);
end
end
ninfnow = sum( isinf(occgrid(:)) ); % current number of Infs
if ninfnow == 0
% stop if no Infs left in the image
break;
end
end
anim.close();
dx = occgrid;
elseif exist('bwdist') && opt.ipt
if opt.verbose
fprintf('using IPT:bwdist\n');
end
% use IPT
dx = bwdist(occgrid, ipt_metric);
elseif exist('vl_imdisttf') && opt.vlfeat
if opt.verbose
fprintf('using VLFEAT:vl_imsdisttf\n');
end
im = double(occgrid);
im(im==0) = inf;
im(im==1) = 0;
d2 = vl_imdisttf(im);
dx = sqrt(d2);
else
if opt.verbose
fprintf('using MATLAB code, faster if you install MVTB\n');
end
occgrid = double(occgrid);
occgrid(occgrid==0) = Inf;
occgrid(isfinite(occgrid)) = 0;
count = 0;
while 1
occgrid = dxstep(occgrid, m);
count = count+1;
if opt.show
cmap = [1 0 0; gray(count)];
colormap(cmap)
image(occgrid+1, 'CDataMapping', 'direct');
set(gca, 'Ydir', 'normal');
xlabel('x');
ylabel('y');
pause(opt.show);
end
ninfnow = sum( isinf(occgrid(:)) ); % current number of Infs
if ninfnow == 0
% stop if no Infs left in the image
break;
end
end
dx = occgrid;
end
end
end
% MATLAB implementation of computational kernel
function out = dxstep(G, m)
[h,w] = size(G); % get size of occ grid
% pad with inf
G = [ones(1,w)*Inf; G; ones(1,w)*Inf];
G = [ones(h+2,1)*Inf G ones(h+2,1)*Inf];
w = w+2; h = h+2;
for r=2:h-1
for c=2:w-1
W = G(r-1:r+1,c-1:c+1); % get 3x3 window
out(r-1,c-1) = min(min(W+m)); % add distances and find the minimum
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
makemap.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/makemap.m
| 5,470 |
utf_8
|
8fab1c7703f28487379400116dfa57bf
|
%MAKEMAP Make an occupancy map
%
% map = makemap(N) is an occupancy grid map (NxN) created by a simple
% interactive editor. The map is initially unoccupied and obstacles can
% be added using geometric primitives.
%
% map = makemap() as above but N=128.
%
% map = makemap(map0) as above but the map is initialized from the
% occupancy grid map0, allowing obstacles to be added.
%
% With focus in the displayed figure window the following commands can
% be entered:
% left button click and drag to create a rectangle
% p draw polygon
% c draw circle
% u undo last action
% e erase map
% q leave editing mode and return map
%
% See also DXForm, PRM, RRT.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function world = makemap(Nw)
if nargin < 1
Nw = 128;
end
if isscalar(Nw)
% initialize a new map
world = zeros(Nw, Nw);
else
% we were passed a map
world = Nw;
end
himg = imagesc(world);
set(gca, 'Ydir', 'normal');
grid on
binary_cmap = [1 1 1; 1 0 0];
colormap(binary_cmap);
caxis([0 1]);
figure(gcf)
set(gcf, 'Name', 'makemap');
fprintf('makemap:\n');
fprintf(' left button, click and drag to create a rectangle\n');
fprintf(' or type the following letters in the figure window:\n');
fprintf(' p - draw polygon\n');
fprintf(' c - draw circle\n');
fprintf(' e - erase map\n');
fprintf(' u - undo last action\n');
fprintf(' q - leave editing mode\n');
while 1
drawnow
k = waitforbuttonpress;
if k == 1
% key pressed
c = get(gcf, 'CurrentCharacter');
switch c
case 'p'
fprintf('click a sequence of points, <enter> when done')
title('click a sequence of points, <enter> when done')
xy = ginput;
fprintf('\r \r')
title('')
xy = round(xy);
world_prev = world;
[X,Y] = meshgrid(1:Nw, 1:Nw);
world = world + inpolygon(X, Y, xy(:,1), xy(:,2));
case 'c'
fprintf('click a centre point')
title('click a centre point')
waitforbuttonpress;
point1 = get(gca,'CurrentPoint'); % button down detected
point1 = round(point1(1,1:2)); % extract x and y
hold on
h = plot(point1(1), point1(2), '+');
drawnow
fprintf('\rclick a circumference point')
title('click a circumference point')
waitforbuttonpress;
point2 = get(gca,'CurrentPoint'); % button up detected
point2 = round(point2(1,1:2));
fprintf('\r \r')
title('')
delete(h);
drawnow
hold off
r = round(colnorm(point1-point2));
c = kcircle(r);
world_prev = world;
% add the circle to the world
world(point1(2)-r:point1(2)+r,point1(1)-r:point1(1)+r) = ...
world(point1(2)-r:point1(2)+r,point1(1)-r:point1(1)+r) + c;
% ensure maximum value of occ.grid is 1
world = min(world, 1);
case 'e'
world_prev = world;
world = zeros(Nw, Nw);
case 'u'
if ~isempty(world_prev)
world = world_prev;
end
otherwise
break; % key pressed
end
else
% button pressed
[point1, point2] = pickregion('pressed')
point1 = round(point1); % extract x and y
point2 = round(point2);
x1 = max(1, point1(1));
x2 = min(Nw, point2(1));
y1 = max(1, point1(2));
y2 = min(Nw, point2(2));
if x1 > x2
t = x1; x1 = x2; x2 = t;
end
if y1 > y2
t = y1; y1 = y2; y2 = t;
end
world_prev = world;
world(y1:y2, x1:x2) = 1;
end
% ensure maximum value of occ.grid is 1
world = min(world, 1);
% update the world display
set(himg, 'CData', world);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
EKF.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/EKF.m
| 38,292 |
utf_8
|
efc593dc23cb6c974db0aca7305b3924
|
%EKF Extended Kalman Filter for navigation
%
% Extended Kalman filter for optimal estimation of state from noisy
% measurments given a non-linear dynamic model. This class is specific to
% the problem of state estimation for a vehicle moving in SE(2).
%
% This class can be used for:
% - dead reckoning localization
% - map-based localization
% - map making
% - simultaneous localization and mapping (SLAM)
%
% It is used in conjunction with:
% - a kinematic vehicle model that provides odometry output, represented
% by a Vehicle sbuclass object.
% - The vehicle must be driven within the area of the map and this is
% achieved by connecting the Vehicle subclass object to a Driver object.
% - a map containing the position of a number of landmark points and is
% represented by a LandmarkMap object.
% - a sensor that returns measurements about landmarks relative to the
% vehicle's pose and is represented by a Sensor object subclass.
%
% The EKF object updates its state at each time step, and invokes the
% state update methods of the vehicle object. The complete history of estimated
% state and covariance is stored within the EKF object.
%
% Methods::
% run run the filter
% plot_xy plot the actual path of the vehicle
% plot_P plot the estimated covariance norm along the path
% plot_map plot estimated landmark points and confidence limits
% plot_vehicle plot estimated vehicle covariance ellipses
% plot_error plot estimation error with standard deviation bounds
% display print the filter state in human readable form
% char convert the filter state to human readable string
%
% Properties::
% x_est estimated state
% P estimated covariance
% V_est estimated odometry covariance
% W_est estimated sensor covariance
% landmarks maps sensor landmark id to filter state element
% robot reference to the Vehicle object
% sensor reference to the Sensor subclass object
% history vector of structs that hold the detailed filter state from
% each time step
% verbose show lots of detail (default false)
% joseph use Joseph form to represent covariance (default true)
%
% Vehicle position estimation (localization)::
%
% Create a vehicle with odometry covariance V, add a driver to it,
% create a Kalman filter with estimated covariance V_est and initial
% state covariance P0
% veh = Vehicle(V);
% veh.add_driver( RandomPath(20, 2) );
% ekf = EKF(veh, V_est, P0);
% We run the simulation for 1000 time steps
% ekf.run(1000);
% then plot true vehicle path
% veh.plot_xy('b');
% and overlay the estimated path
% ekf.plot_xy('r');
% and overlay uncertainty ellipses
% ekf.plot_ellipse('g');
% We can plot the covariance against time as
% clf
% ekf.plot_P();
%
% Map-based vehicle localization::
%
% Create a vehicle with odometry covariance V, add a driver to it,
% create a map with 20 point landmarks, create a sensor that uses the map
% and vehicle state to estimate landmark range and bearing with covariance
% W, the Kalman filter with estimated covariances V_est and W_est and initial
% vehicle state covariance P0
% veh = Bicycle(V);
% veh.add_driver( RandomPath(20, 2) );
% map = LandmarkMap(20);
% sensor = RangeBearingSensor(veh, map, W);
% ekf = EKF(veh, V_est, P0, sensor, W_est, map);
% We run the simulation for 1000 time steps
% ekf.run(1000);
% then plot the map and the true vehicle path
% map.plot();
% veh.plot_xy('b');
% and overlay the estimatd path
% ekf.plot_xy('r');
% and overlay uncertainty ellipses
% ekf.plot_ellipse('g');
% We can plot the covariance against time as
% clf
% ekf.plot_P();
%
% Vehicle-based map making::
%
% Create a vehicle with odometry covariance V, add a driver to it,
% create a sensor that uses the map and vehicle state to estimate landmark range
% and bearing with covariance W, the Kalman filter with estimated sensor
% covariance W_est and a "perfect" vehicle (no covariance),
% then run the filter for N time steps.
%
% veh = Vehicle(V);
% veh.add_driver( RandomPath(20, 2) );
% map = LandmarkMap(20);
% sensor = RangeBearingSensor(veh, map, W);
% ekf = EKF(veh, [], [], sensor, W_est, []);
% We run the simulation for 1000 time steps
% ekf.run(1000);
% Then plot the true map
% map.plot();
% and overlay the estimated map with 97% confidence ellipses
% ekf.plot_map('g', 'confidence', 0.97);
%
% Simultaneous localization and mapping (SLAM)::
%
% Create a vehicle with odometry covariance V, add a driver to it,
% create a map with 20 point landmarks, create a sensor that uses the map
% and vehicle state to estimate landmark range and bearing with covariance
% W, the Kalman filter with estimated covariances V_est and W_est and initial
% state covariance P0, then run the filter to estimate the vehicle state at
% each time step and the map.
%
% veh = Vehicle(V);
% veh.add_driver( RandomPath(20, 2) );
% map = PointMap(20);
% sensor = RangeBearingSensor(veh, map, W);
% ekf = EKF(veh, V_est, P0, sensor, W, []);
% We run the simulation for 1000 time steps
% ekf.run(1000);
% then plot the map and the true vehicle path
% map.plot();
% veh.plot_xy('b');
% and overlay the estimated path
% ekf.plot_xy('r');
% and overlay uncertainty ellipses
% ekf.plot_ellipse('g');
% We can plot the covariance against time as
% clf
% ekf.plot_P();
% Then plot the true map
% map.plot();
% and overlay the estimated map with 3 sigma ellipses
% ekf.plot_map(3, 'g');
%
% References::
%
% Robotics, Vision & Control, Chap 6,
% Peter Corke,
% Springer 2011
%
% Stochastic processes and filtering theory,
% AH Jazwinski
% Academic Press 1970
%
% Acknowledgement::
%
% Inspired by code of Paul Newman, Oxford University,
% http://www.robots.ox.ac.uk/~pnewman
%
% See also Vehicle, RandomPath, RangeBearingSensor, PointMap, ParticleFilter.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
classdef EKF < handle
%TODO
% add a hook for data association
% show landmark covar as ellipse or pole
% show vehicle covar as ellipse
% show track
% landmarks property should be an array of structs
properties
% STATE:
% the state vector is [x_vehicle x_map] where
% x_vehicle is 1x3 and
% x_map is 1x(2N) where N is the number of map landmarks
x_est % estimated state
P_est % estimated covariance
% landmarks keeps track of landmarks we've seen before.
% Each column represents a landmark. This is a fixed size
% array, indexed by landmark id.
% row 1: the start of this landmark's state in the state vector, initially NaN
% row 2: the number of times we've sighted the landmark
landmarks % map state
V_est % estimate of covariance V
W_est % estimate of covariance W
robot % reference to the robot vehicle
sensor % reference to the sensor
% FLAGS:
% estVehicle estMap
% 0 0
% 0 1 make map
% 1 0 dead reckoning
% 1 1 SLAM
estVehicle % flag: estimating vehicle location
estMap % flag: estimating map
joseph % flag: use Joseph form to compute p
verbose
keepHistory % keep history
P0 % passed initial covariance
map % passed map
% HISTORY:
% vector of structs to hold EKF history
% .x_est estimated state
% .odo vehicle odometry
% .P estimated covariance matrix
% .innov innovation
% .S
% .K Kalman gain matrix
history
dim % robot workspace dimensions
end
methods
% constructor
function ekf = EKF(robot, V_est, P0, varargin)
%EKF.EKF EKF object constructor
%
% E = EKF(VEHICLE, V_EST, P0, OPTIONS) is an EKF that estimates the state
% of the VEHICLE (subclass of Vehicle) with estimated odometry covariance V_EST (2x2) and
% initial covariance (3x3).
%
% E = EKF(VEHICLE, V_EST, P0, SENSOR, W_EST, MAP, OPTIONS) as above but
% uses information from a VEHICLE mounted sensor, estimated
% sensor covariance W_EST and a MAP (LandmarkMap class).
%
% Options::
% 'verbose' Be verbose.
% 'nohistory' Don't keep history.
% 'joseph' Use Joseph form for covariance
% 'dim',D Dimension of the robot's workspace.
% - D scalar; X: -D to +D, Y: -D to +D
% - D (1x2); X: -D(1) to +D(1), Y: -D(2) to +D(2)
% - D (1x4); X: D(1) to D(2), Y: D(3) to D(4)
%
% Notes::
% - If MAP is [] then it will be estimated.
% - If V_EST and P0 are [] the vehicle is assumed error free and
% the filter will only estimate the landmark positions (map).
% - If V_EST and P0 are finite the filter will estimate the
% vehicle pose and the landmark positions (map).
% - EKF subclasses Handle, so it is a reference object.
% - Dimensions of workspace are normally taken from the map if given.
%
% See also Vehicle, Bicycle, Unicycle, Sensor, RangeBearingSensor, LandmarkMap.
opt.history = true;
opt.joseph = true;
opt.dim = [];
[opt,args] = tb_optparse(opt, varargin);
% copy options to class properties
ekf.verbose = opt.verbose;
ekf.keepHistory = opt.history;
ekf.joseph = opt.joseph;
ekf.P0 = P0;
ekf.dim = opt.dim;
% figure what we need to estimate
ekf.estVehicle = false;
ekf.estMap = false;
switch length(args)
case 0
% Deadreckoning:
% E = EKF(VEHICLE, V_EST, P0, OPTIONS)
sensor = []; W_est = []; map = [];
ekf.estVehicle = true;
case 3
% Using a map:
% E = EKF(VEHICLE, V_EST, P0, SENSOR, W_EST, MAP, OPTIONS)
% Estimating a map:
% E = EKF(VEHICLE,[], [], SENSOR, W_EST, [], OPTIONS)
% Full SLAM:
% E = EKF(VEHICLE, V_EST, P0, SENSOR, W_EST, [], OPTIONS)
[sensor, W_est, map] = deal(args{:});
if isempty(map)
ekf.estMap = true;
end
if ~isempty(V_est)
ekf.estVehicle = true;
end
otherwise
error('RTB:EKF:badarg', 'incorrect number of non-option arguments');
end
% check types for passed objects
if ~isempty(map) && ~isa(map, 'LandmarkMap')
error('RTB:EKF:badarg', 'expecting LandmarkMap object');
end
if ~isempty(sensor) && ~isa(sensor, 'Sensor')
error('RTB:EKF:badarg', 'expecting Sensor object');
end
if ~isa(robot, 'Vehicle')
error('RTB:EKF:badarg', 'expecting Vehicle object');
end
% copy arguments to class properties
ekf.robot = robot;
ekf.V_est = V_est;
ekf.sensor = sensor;
ekf.map = map;
ekf.W_est = W_est;
ekf.init();
end
function init(ekf)
%EKF.init Reset the filter
%
% E.init() resets the filter state and clears landmarks and history.
ekf.robot.init();
% clear the history
ekf.history = [];
if isempty(ekf.V_est)
% perfect vehicle case
ekf.estVehicle = false;
ekf.x_est = [];
ekf.P_est = [];
else
% noisy odometry case
ekf.x_est = ekf.robot.x(:); % column vector
ekf.P_est = ekf.P0;
ekf.estVehicle = true;
end
if ~isempty(ekf.sensor)
ekf.landmarks = NaN*zeros(2, ekf.sensor.map.nlandmarks);
end
end
function run(ekf, n, varargin)
%EKF.run Run the filter
%
% E.run(N, OPTIONS) runs the filter for N time steps and shows an animation
% of the vehicle moving.
%
% Options::
% 'plot' Plot an animation of the vehicle moving
%
% Notes::
% - All previously estimated states and estimation history are initially
% cleared.
opt.plot = true;
opt.movie = [];
opt = tb_optparse(opt, varargin);
ekf.init();
if opt.plot
if ~isempty(ekf.sensor)
ekf.sensor.map.plot();
elseif ~isempty(ekf.dim)
switch length(ekf.dim)
case 1
d = ekf.dim;
axis([-d d -d d]);
case 2
w = ekf.dim(1), h = ekf.dim(2);
axis([-w w -h h]);
case 4
axis(ekf.dim);
end
set(gca, 'ALimMode', 'manual');
else
opt.plot = false;
end
axis manual
xlabel('X'); ylabel('Y')
end
% simulation loop
anim = Animate(opt.movie);
for k=1:n
if opt.plot
ekf.robot.plot();
drawnow
end
ekf.step(opt);
anim.add();
end
anim.close();
end
function xyt = get_xy(ekf)
%EKF.plot_xy Get vehicle position
%
% P = E.get_xy() is the estimated vehicle pose trajectory
% as a matrix (Nx3) where each row is x, y, theta.
%
% See also EKF.plot_xy, EKF.plot_error, EKF.plot_ellipse, EKF.plot_P.
if ekf.estVehicle
xyt = zeros(length(ekf.history), 3);
for i=1:length(ekf.history)
h = ekf.history(i);
xyt(i,:) = h.x_est(1:3)';
end
else
xyt = [];
end
end
function out = plot_xy(ekf, varargin)
%EKF.plot_xy Plot vehicle position
%
% E.plot_xy() overlay the current plot with the estimated vehicle path in
% the xy-plane.
%
% E.plot_xy(LS) as above but the optional line style arguments
% LS are passed to plot.
%
% See also EKF.get_xy, EKF.plot_error, EKF.plot_ellipse, EKF.plot_P.
xyt=ekf.get_xy();
plot(xyt(:,1), xyt(:,2), varargin{:});
plot(xyt(1,1), xyt(1,2), 'ko', 'MarkerSize', 8, 'LineWidth', 2);
end
function out = plot_error(ekf, varargin)
%EKF.plot_error Plot vehicle position
%
% E.plot_error(OPTIONS) plot the error between actual and estimated vehicle
% path (x, y, theta) versus time. Heading error is wrapped into the range [-pi,pi)
%
% Options::
% 'bound',S Display the confidence bounds (default 0.95).
% 'color',C Display the bounds using color C
% LS Use MATLAB linestyle LS for the plots
%
% Notes::
% - The bounds show the instantaneous standard deviation associated
% with the state. Observations tend to decrease the uncertainty
% while periods of dead-reckoning increase it.
% - Set bound to zero to not draw confidence bounds.
% - Ideally the error should lie "mostly" within the +/-3sigma
% bounds.
%
% See also EKF.plot_xy, EKF.plot_ellipse, EKF.plot_P.
opt.color = 'r';
opt.confidence = 0.95;
opt.nplots = 3;
[opt,args] = tb_optparse(opt, varargin);
clf
if ekf.estVehicle
err = zeros(length(ekf.history), 3);
for i=1:length(ekf.history)
h = ekf.history(i);
% error is true - estimated
err(i,:) = ekf.robot.x_hist(i,:) - h.x_est(1:3)';
err(i,3) = angdiff(err(i,3));
P = diag(h.P);
pxy(i,:) = sqrt( chi2inv_rtb(opt.confidence, 2)*P(1:3) );
end
if nargout == 0
clf
t = 1:numrows(pxy);
t = [t t(end:-1:1)]';
subplot(opt.nplots*100+11)
if opt.confidence
edge = [pxy(:,1); -pxy(end:-1:1,1)];
h = patch(t, edge ,opt.color);
set(h, 'EdgeColor', 'none', 'FaceAlpha', 0.3);
end
hold on
plot(err(:,1), args{:});
hold off
grid
ylabel('x error')
subplot(opt.nplots*100+12)
if opt.confidence
edge = [pxy(:,2); -pxy(end:-1:1,2)];
h = patch(t, edge, opt.color);
set(h, 'EdgeColor', 'none', 'FaceAlpha', 0.3);
end
hold on
plot(err(:,2), args{:});
hold off
grid
ylabel('y error')
subplot(opt.nplots*100+13)
if opt.confidence
edge = [pxy(:,3); -pxy(end:-1:1,3)];
h = patch(t, edge, opt.color);
set(h, 'EdgeColor', 'none', 'FaceAlpha', 0.3);
end
hold on
plot(err(:,3), args{:});
hold off
grid
xlabel('Time step')
ylabel('\theta error')
if opt.nplots > 3
subplot(opt.nplots*100+14);
end
else
out = pxy;
end
end
end
function xy = get_map(ekf, varargin)
%EKF.get_map Get landmarks
%
% P = E.get_map() is the estimated landmark coordinates (2xN) one per
% column. If the landmark was not estimated the corresponding column
% contains NaNs.
%
% See also EKF.plot_map, EKF.plot_ellipse.
xy = [];
for i=1:numcols(ekf.landmarks)
n = ekf.landmarks(1,i);
if isnan(n)
% this landmark never observed
xy = [xy [NaN; NaN]];
continue;
end
% n is an index into the *landmark* part of the state
% vector, we need to offset it to account for the vehicle
% state if we are estimating vehicle as well
if ekf.estVehicle
n = n + 3;
end
xf = ekf.x_est(n:n+1);
xy = [xy xf];
end
end
function plot_map(ekf, varargin)
%EKF.plot_map Plot landmarks
%
% E.plot_map(OPTIONS) overlay the current plot with the estimated landmark
% position (a +-marker) and a covariance ellipses.
%
% E.plot_map(LS, OPTIONS) as above but pass line style arguments
% LS to plot_ellipse.
%
% Options::
% 'confidence',C Draw ellipse for confidence value C (default 0.95)
%
% See also EKF.get_map, EKF.plot_ellipse.
% TODO: some option to plot map evolution, layered ellipses
opt.confidence = 0.95;
[opt,args] = tb_optparse(opt, varargin);
xy = [];
for i=1:numcols(ekf.landmarks)
n = ekf.landmarks(1,i);
if isnan(n)
% this landmark never observed
xy = [xy [NaN; NaN]];
continue;
end
% n is an index into the *landmark* part of the state
% vector, we need to offset it to account for the vehicle
% state if we are estimating vehicle as well
if ekf.estVehicle
n = n + 3;
end
xf = ekf.x_est(n:n+1);
P = ekf.P_est(n:n+1,n:n+1);
% TODO reinstate the interval landmark
%plot_ellipse(xf, P, interval, 0, [], varargin{:});
plot_ellipse( P * chi2inv_rtb(opt.confidence, 2), xf, args{:});
plot(xf(1), xf(2), 'k.', 'MarkerSize', 10)
end
end
function P = get_P(ekf, k)
%EKF.get_P Get covariance magnitude
%
% E.get_P() is a vector of estimated covariance magnitude at each time step.
P = zeros(length(ekf.history),1);
for i=1:length(ekf.history)
P(i) = sqrt(det(ekf.history(i).P));
end
end
function plot_P(ekf, varargin)
%EKF.plot_P Plot covariance magnitude
%
% E.plot_P() plots the estimated covariance magnitude against
% time step.
%
% E.plot_P(LS) as above but the optional line style arguments
% LS are passed to plot.
p = ekf.get_P();
plot(p, varargin{:});
xlabel('Time step');
ylabel('(det P)^{0.5}')
end
function show_P(ekf, k)
clf
if nargin < 2
k = length(ekf.history);
end
z = log10(abs(ekf.history(k).P));
mn = min(z(~isinf(z)))
z(isinf(z)) = mn;
cmap = flip( gray(256), 1);
%colormap(parula);
colormap(flipud(bone))
c = gray;
c = [ones(numrows(c),1) 1-c(:,1:2)];
colormap(c)
% imshow(z, ...
% 'DisplayRange', [min(z(:)) max(z(:))], ...
% 'ColorMap', cmap, ...
% 'InitialMagnification', 'fit' )
image(z, 'CDataMapping', 'scaled')
xlabel('state'); ylabel('state');
c = colorbar();
c.Label.String = 'log covariance';
end
function plot_ellipse(ekf, varargin)
%EKF.plot_ellipse Plot vehicle covariance as an ellipse
%
% E.plot_ellipse() overlay the current plot with the estimated
% vehicle position covariance ellipses for 20 points along the
% path.
%
% E.plot_ellipse(LS) as above but pass line style arguments
% LS to plot_ellipse.
%
% Options::
% 'interval',I Plot an ellipse every I steps (default 20)
% 'confidence',C Confidence interval (default 0.95)
%
% See also plot_ellipse.
opt.interval = round(length(ekf.history)/20);
opt.confidence = 0.95;
[opt,args] = tb_optparse(opt, varargin);
holdon = ishold;
hold on
for i=1:opt.interval:length(ekf.history)
h = ekf.history(i);
%plot_ellipse(h.x_est(1:2), h.P(1:2,1:2), 1, 0, [], varargin{:});
plot_ellipse(h.P(1:2,1:2) * chi2inv_rtb(opt.confidence, 2), h.x_est(1:2), args{:});
end
if ~holdon
hold off
end
end
function display(ekf)
%EKF.display Display status of EKF object
%
% E.display() displays the state of the EKF object in
% human-readable form.
%
% Notes::
% - This method is invoked implicitly at the command line when the result
% of an expression is a EKF object and the command has no trailing
% semicolon.
%
% See also EKF.char.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
disp( char(ekf) );
end % display()
function s = char(ekf)
%EKF.char Convert to string
%
% E.char() is a string representing the state of the EKF
% object in human-readable form.
%
% See also EKF.display.
s = sprintf('EKF object: %d states', length(ekf.x_est));
e = '';
if ekf.estVehicle
e = [e 'Vehicle '];
end
if ekf.estMap
e = [e 'Map '];
end
s = char(s, [' estimating: ' e]);
if ~isempty(ekf.robot)
s = char(s, char(ekf.robot));
end
if ~isempty(ekf.sensor)
s = char(s, char(ekf.sensor));
end
s = char(s, ['W_est: ' mat2str(ekf.W_est, 3)] );
s = char(s, ['V_est: ' mat2str(ekf.V_est, 3)] );
end
end % method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% P R I V A T E M E T H O D S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Access=protected)
function x_est = step(ekf, opt)
%fprintf('-------step\n');
% move the robot along its path and get odometry
odo = ekf.robot.step();
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% do the prediction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ekf.estVehicle
% split the state vector and covariance into chunks for
% vehicle and map
xv_est = ekf.x_est(1:3);
xm_est = ekf.x_est(4:end);
Pvv_est = ekf.P_est(1:3,1:3);
Pmm_est = ekf.P_est(4:end,4:end);
Pvm_est = ekf.P_est(1:3,4:end);
else
xm_est = ekf.x_est;
%Pvv_est = ekf.P_est;
Pmm_est = ekf.P_est;
end
if ekf.estVehicle
% evaluate the state update function and the Jacobians
% if vehicle has uncertainty, predict its covariance
xv_pred = ekf.robot.f(xv_est', odo)';
Fx = ekf.robot.Fx(xv_est, odo);
Fv = ekf.robot.Fv(xv_est, odo);
Pvv_pred = Fx*Pvv_est*Fx' + Fv*ekf.V_est*Fv';
else
% otherwise we just take the true robot state
xv_pred = ekf.robot.x;
end
if ekf.estMap
if ekf.estVehicle
% SLAM case, compute the correlations
Pvm_pred = Fx*Pvm_est;
end
Pmm_pred = Pmm_est;
xm_pred = xm_est;
end
% put the chunks back together again
if ekf.estVehicle && ~ekf.estMap
% vehicle only
x_pred = xv_pred;
P_pred = Pvv_pred;
elseif ~ekf.estVehicle && ekf.estMap
% map only
x_pred = xm_pred;
P_pred = Pmm_pred;
elseif ekf.estVehicle && ekf.estMap
% vehicle and map
x_pred = [xv_pred; xm_pred];
P_pred = [ Pvv_pred Pvm_pred; Pvm_pred' Pmm_pred];
end
% at this point we have:
% xv_pred the state of the vehicle to use to
% predict observations
% xm_pred the state of the map
% x_pred the full predicted state vector
% P_pred the full predicted covariance matrix
% initialize the variables that might be computed during
% the update phase
doUpdatePhase = false;
%fprintf('x_pred:'); x_pred'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% process observations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sensorReading = false;
if ~isempty(ekf.sensor)
% read the sensor
[z,js] = ekf.sensor.reading();
% test if the sensor has returned a reading at this time interval
sensorReading = js > 0;
end
if sensorReading
% here for MBL, MM, SLAM
% compute the innovation
z_pred = ekf.sensor.h(xv_pred', js)';
innov(1) = z(1) - z_pred(1);
innov(2) = angdiff(z(2), z_pred(2));
if ekf.estMap
% the map is estimated MM or SLAM case
if ekf.seenBefore(js)
% get previous estimate of its state
jx = ekf.landmarks(1,js);
xf = xm_pred(jx:jx+1);
% compute Jacobian for this particular landmark
Hx_k = ekf.sensor.Hp(xv_pred', xf);
% create the Jacobian for all landmarks
Hx = zeros(2, length(xm_pred));
Hx(:,jx:jx+1) = Hx_k;
Hw = ekf.sensor.Hw(xv_pred, xf);
if ekf.estVehicle
% concatenate Hx for for vehicle and map
Hxv = ekf.sensor.Hx(xv_pred', xf);
Hx = [Hxv Hx];
end
doUpdatePhase = true;
% if mod(i, 40) == 0
% plot_ellipse(x_est(jx:jx+1), P_est(jx:jx+1,jx:jx+1), 5);
% end
else
% get the extended state
[x_pred, P_pred] = ekf.extendMap(P_pred, xv_pred, xm_pred, z, js);
doUpdatePhase = false;
end
else
% the map is given, MBL case
Hx = ekf.sensor.Hx(xv_pred', js);
Hw = ekf.sensor.Hw(xv_pred', js);
doUpdatePhase = true;
end
end
% doUpdatePhase flag indicates whether or not to do
% the update phase of the filter
%
% DR always false
% map-based localization if sensor reading
% map creation if sensor reading & not first
% sighting
% SLAM if sighting of a previously
% seen landmark
if doUpdatePhase
%fprintf('do update\n');
%% we have innovation, update state and covariance
% compute x_est and P_est
% compute innovation covariance
S = Hx*P_pred*Hx' + Hw*ekf.W_est*Hw';
% compute the Kalman gain
K = P_pred*Hx' / S;
% update the state vector
x_est = x_pred + K*innov';
if ekf.estVehicle
% wrap heading state for a vehicle
x_est(3) = angdiff(x_est(3));
end
% update the covariance
if ekf.joseph
% we use the Joseph form
I = eye(size(P_pred));
P_est = (I-K*Hx)*P_pred*(I-K*Hx)' + K*ekf.W_est*K';
else
P_est = P_pred - K*S*K';
end
% enforce P to be symmetric
P_est = 0.5*(P_est+P_est');
else
% no update phase, estimate is same as prediction
x_est = x_pred;
P_est = P_pred;
innov = [];
S = [];
K = [];
end
%fprintf('X:'); x_est'
% update the state and covariance for next time
ekf.x_est = x_est;
ekf.P_est = P_est;
% record time history
if ekf.keepHistory
hist = [];
hist.x_est = x_est;
hist.odo = odo;
hist.P = P_est;
hist.innov = innov;
hist.S = S;
hist.K = K;
ekf.history = [ekf.history hist];
end
end
function s = seenBefore(ekf, jf)
if ~isnan(ekf.landmarks(1,jf))
%% we have seen this landmark before, update number of sightings
if ekf.verbose
fprintf('landmark %d seen %d times before, state_idx=%d\n', ...
jf, ekf.landmarks(2,jf), ekf.landmarks(1,jf));
end
ekf.landmarks(2,jf) = ekf.landmarks(2,jf)+1;
s = true;
else
s = false;
end
end
function [x_ext, P_ext] = extendMap(ekf, P, xv, xm, z, jf)
%% this is a new landmark, we haven't seen it before
% estimate position of landmark in the world based on
% noisy sensor reading and current vehicle pose
if ekf.verbose
fprintf('landmark %d first sighted\n', jf);
end
% estimate its position based on observation and vehicle state
xf = ekf.sensor.g(xv, z);
% append this estimate to the state vector
if ekf.estVehicle
x_ext = [xv; xm; xf];
else
x_ext = [xm; xf];
end
% get the Jacobian for the new landmark
Gz = ekf.sensor.Gz(xv, z);
% extend the covariance matrix
if ekf.estVehicle
Gx = ekf.sensor.Gx(xv, z);
n = length(ekf.x_est);
M = [eye(n) zeros(n,2); Gx zeros(2,n-3) Gz];
P_ext = M*blkdiag(P, ekf.W_est)*M';
else
P_ext = blkdiag(P, Gz*ekf.W_est*Gz');
end
% record the position in the state vector where this
% landmark's state starts
ekf.landmarks(1,jf) = length(xm)+1;
%ekf.landmarks(1,jf) = length(ekf.x_est)-1;
ekf.landmarks(2,jf) = 1; % seen it once
if ekf.verbose
fprintf('extended state vector\n');
end
% plot an ellipse at this time
% jx = landmarks(1,jf);
% plot_ellipse(x_est(jx:jx+1), P_est(jx:jx+1,jx:jx+1), 5);
end
end % private methods
end % classdef
function f = chi2inv_rtb(confidence, n)
assert(n == 2, 'chi2inv_rtb: only valid for 2DOF');
c = linspace(0,1,101);
% build a lookup table:
%x = chi2inv(c,2)
%fprintf('%f ');
x = [0.000000 0.020101 0.040405 0.060918 0.081644 0.102587 0.123751 0.145141 0.166763 0.188621 0.210721 0.233068 0.255667 0.278524 0.301646 0.325038 0.348707 0.372659 0.396902 0.421442 0.446287 0.471445 0.496923 0.522730 0.548874 0.575364 0.602210 0.629421 0.657008 0.684981 0.713350 0.742127 0.771325 0.800955 0.831031 0.861566 0.892574 0.924071 0.956072 0.988593 1.021651 1.055265 1.089454 1.124238 1.159637 1.195674 1.232372 1.269757 1.307853 1.346689 1.386294 1.426700 1.467938 1.510045 1.553058 1.597015 1.641961 1.687940 1.735001 1.783196 1.832581 1.883217 1.935168 1.988505 2.043302 2.099644 2.157619 2.217325 2.278869 2.342366 2.407946 2.475749 2.545931 2.618667 2.694147 2.772589 2.854233 2.939352 3.028255 3.121295 3.218876 3.321462 3.429597 3.543914 3.665163 3.794240 3.932226 4.080442 4.240527 4.414550 4.605170 4.815891 5.051457 5.318520 5.626821 5.991465 6.437752 7.013116 7.824046 9.210340 Inf];
f = interp1(c, x, confidence);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
startup_rtb.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/startup_rtb.m
| 2,933 |
utf_8
|
6686fddd89b8991e00972cc00b0f85aa
|
%STARTUP_RTB Initialize MATLAB paths for Robotics Toolbox
%
% Adds demos, data, contributed code and examples to the MATLAB path, and adds also to
% Java class path.
%
% Notes::
% - This sets the paths for the current session only.
% - To make the settings persistent across sessions you can:
% - Add this script to your MATLAB startup.m script.
% - After running this script run PATHTOOL and save the path.
%
% See also PATH, ADDPATH, PATHTOOL, JAVAADDPATH.
% Copyright (C) 1993-2019, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function startup_rtb(tbpath)
fp = fopen('RELEASE', 'r');
release = fgetl(fp);
fclose(fp);
fprintf('- Robotics Toolbox for MATLAB (release %s)\n', release)
if nargin == 0
tbpath = fileparts( mfilename('fullpath') );
end
addpath( fullfile(tbpath, 'demos') );
addpath( fullfile(tbpath, 'examples') );
addpath( fullfile(tbpath, 'Apps') );
addpath( fullfile(tbpath, 'mex') );
addpath( fullfile(tbpath, 'models') );
addpath( fullfile(tbpath, 'data') );
javaaddpath( fullfile(tbpath, 'java', 'DHFactor.jar') );
p = fullfile(tbpath, 'simulink');
if exist(p, 'dir')
addpath( p );
end
addpath( fullfile(tbpath, 'interfaces', 'VREP') );
% add the contrib code to the path
rvcpath = fileparts(tbpath); % strip one folder off path
p = fullfile(rvcpath, 'contrib');
if exist(p, 'dir')
addpath(p)
end
p = fullfile(tbpath, 'data', 'meshes');
disp([' - ARTE contributed code: 3D models for robot manipulators (' p ')']);
p = fullfile(rvcpath, 'contrib', 'pHRIWARE', 'next');
if exist(p, 'dir')
addpath( p );
disp([' - pHRIWARE (release ',pHRIWARE('ver'),'): ',pHRIWARE('c')]);
end
p = fullfile(rvcpath, 'contrib/paretofront');
% if exist(p)
% addpath( p );
% disp([' - paretofront contributed code (' p ')']);
% end
% [currentversion,status] = urlread('http://www.petercorke.com/RTB/currentversion.php', 'Timeout', 2.0);
% if status == 1
% if ~strcmp(release, currentversion)
% fprintf('** Release %s now available\n\n', ...
% currentversion);
% end
% end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
delta2tr.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/delta2tr.m
| 1,233 |
utf_8
|
fd7fb8d433dcdff76ec180253a34ec45
|
%DELTA2TR Convert differential motion to a homogeneous transform
%
% T = DELTA2TR(D) is a homogeneous transform (4x4) representing differential
% translation and rotation. The vector D=(dx, dy, dz, dRx, dRy, dRz)
% represents an infinitessimal motion, and is an approximation to the spatial
% velocity multiplied by time.
%
% See also tr2delta, SE3.delta.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function delta = delta2tr(d)
d = d(:);
delta = eye(4,4) + [skew(d(4:6)) d(1:3); 0 0 0 0];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ctraj.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/ctraj.m
| 2,109 |
utf_8
|
cb005b9fbd6614032f309fd2dfe28eea
|
%CTRAJ Cartesian trajectory between two poses
%
% TC = CTRAJ(T0, T1, N) is a Cartesian trajectory (4x4xN) from pose T0 to T1
% with N points that follow a trapezoidal velocity profile along the path.
% The Cartesian trajectory is a homogeneous transform sequence and the last
% subscript being the point index, that is, T(:,:,i) is the i'th point along
% the path.
%
% TC = CTRAJ(T0, T1, S) as above but the elements of S (Nx1) specify the
% fractional distance along the path, and these values are in the range [0 1].
% The i'th point corresponds to a distance S(i) along the path.
%
% Notes::
% - If T0 or T1 is equal to [] it is taken to be the identity matrix.
% - In the second case S could be generated by a scalar trajectory generator
% such as TPOLY or LSPB (default).
% - Orientation interpolation is performed using quaternion interpolation.
%
% Reference::
% Robotics, Vision & Control, Sec 3.1.5,
% Peter Corke, Springer 2011
%
% See also LSPB, MSTRAJ, TRINTERP, UnitQuaternion.interp, SE3.ctraj.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function traj = ctraj(T0, T1, t)
% T0 = SE3.check(T0);
% T1 = SE3.check(T1);
% distance along path is a smooth function of time
if isscalar(t)
s = lspb(0, 1, t);
else
s = t(:);
end
for i=1:length(s)
traj(:,:,i) = trinterp(T0, T1, s(i));
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
rtbdemo.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/rtbdemo.m
| 7,904 |
utf_8
|
6cd0b596b9ecb4058ec2c46f2ea79c23
|
%RTBDEMO Robot toolbox demonstrations
%
% rtbdemo displays a menu of toolbox demonstration scripts that illustrate:
% - fundamental datatypes
% - rotation and homogeneous transformation matrices
% - quaternions
% - trajectories
% - serial link manipulator arms
% - forward and inverse kinematics
% - robot animation
% - forward and inverse dynamics
% - mobile robots
% - kinematic models and control
% - path planning (D*, PRM, Lattice, RRT)
% - localization (EKF, particle filter)
% - SLAM (EKF, pose graph)
% - quadrotor control
%
% rtbdemo(T) as above but waits for T seconds after every statement, no
% need to push the enter key periodically.
%
% Notes::
% - By default the scripts require the user to periodically hit <Enter> in
% order to move through the explanation.
% - Some demos require Simulink
% - To quit, close the rtbdemo window
% TODO: triple angle, pose graph slam example, lattice planner
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function rtbdemo(timeout)
echo off
close all
% find the path to the demos
if exist('rtbdemo', 'file') == 2
tbpath = fileparts(which('rtbdemo'));
demopath = fullfile(tbpath, 'demos');
end
% create the options to pass through to runscript
opts = {'begin', 'path', demopath};
% display a help message in the consolde
msg = {
'------------------------------------------------------------'
'Many of these demos print tutorial text and MATLAB commmands'
'in the console window. Read the text and press <enter> to move'
'on to the next command. At the end of the tutorial you can'
'choose the next one from the graphical menu, or close the menu'
'window.'
'------------------------------------------------------------'
};
for i=1:numel(msg)
fprintf('%s\n', msg{i});
end
% Map the button names (must be exact match) to the scripts to invoke
demos = {
'Rotations', 'rotation';
'Transformations', 'trans';
'Joystick demo', 'joytest';
'Trajectory', 'traj';
'V-REP simulator', 'vrepdemo';
'Create a model', 'robot';
'Animation', 'graphics';
'Rendered animation', 'puma_path';
'3-point turn', 'car_anim_rs';
'Forward kinematics', 'fkine';
'Inverse kinematics', 'ikine';
'Jacobians', 'jacob';
'Inverse dynamics', 'idyn';
'Forward dynamics', 'fdyn';
'Symbolic', 'symbolic';
'Driving to a pose', 'drivepose';
'Quadrotor flying', 'quadrotor';
'Braitenberg vehicle', 'braitnav';
'Bug navigation', 'bugnav';
'D* navigation', 'dstarnav';
'PRM navigation', 'prmnav';
'SLAM demo', 'slam';
'Particle filter localization', 'particlefilt';
'Pose graph SLAM', 'pgslam';
};
% display the GUI panel
% some of this taken from the GUIDE generated file
gui_Singleton = 1;
gui_State = struct('gui_Name', 'rtbdemo_gui', ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @rtbdemo_gui_OpeningFcn, ...
'gui_OutputFcn', @rtbdemo_gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
h = gui_mainfcn(gui_State);
% now set the callback for every button, can't seem to make this work using
% GUIDE.
cb = findobj(h, 'Tag', 'checkbox1');
for hh=h.Children'
switch hh.Type
case 'uicontrol'
if strcmp( hh.Style, 'pushbutton')
set(hh, 'Callback', @demo_pushbutton_callback);
end
case 'uipanel'
for hhh=hh.Children'
if strcmp( hhh.Style, 'pushbutton')
set(hhh, 'Callback', @demo_pushbutton_callback);
end
continue;
end
end
end
% TODO:
% build the buttons dynamically, eliminate the need for GUIDE
set(h, 'Name', 'rtbdemo');
while true
set(h, 'Visible', 'on');
% wait for a button press
% buttons set the UserData property of the GUI to the button string name
waitfor(h, 'UserData');
% check if the GUI window has been dismissed
if ~ishandle(h)
break
end
% get the user's selection, it was stashed in GUI UserData
selection = get(h, 'UserData');
set(h, 'UserData', []); % reset user data so we notice next change
% now look for it in the list of demos
for i=1:size(demos, 1)
if strcmp(selection, demos{i,1})
% then run the appropriate script
script = demos{i,2};
set(h, 'Visible', 'off');
if cb.Value > 0
% pause after each command
opts1 = opts;
else
% no pause
delay = 0;
% if delay given on command use that
if nargin > 0
delay = timeout;
end
opts1 = [opts, 'delay', delay];
end
try
runscript(script, opts1{:})
catch me
disp('error in executing demo script');
me.getReport()
end
end
end
end
end
% --- Executes just before rtbdemo_gui is made visible.
function rtbdemo_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to rtbdemo_gui (see VARARGIN)
% Choose default command line output for rtbdemo_gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
initialize_gui(hObject, handles, false);
end
% --- Outputs from this function are returned to the command line.
function varargout = rtbdemo_gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
end
function initialize_gui(fig_handle, handles, isreset)
% Update handles structure
guidata(handles.figure1, handles);
end
% --- Executes on button press .
function demo_pushbutton_callback(hObject, eventdata, handles)
% hObject handle to pushbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(gcf, 'Userdata', get(hObject, 'String'));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
symexpr2slblock.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/symexpr2slblock.m
| 3,224 |
utf_8
|
4f0f8a64a5284a0570329322a4f24417
|
%SYMEXPR2SLBLOCK Create symbolic embedded MATLAB Function block
%
% symexpr2slblock(VARARGIN) creates an Embedded MATLAB Function block
% from a symbolic expression. The input arguments are just as used with
% the functions emlBlock or matlabFunctionBlock.
%
% Notes::
% - In Symbolic Toolbox versions prior to V5.7 (2011b) the function to
% create Embedded Matlab Function blocks from symbolic expressions is
% 'emlBlock'.
% - Since V5.7 (2011b) there is another function named
% 'matlabFunctionBlock' which replaces the old function.
% - symexpr2slblock is a wrapper around both functions, which
% checks for the installed Symbolic Toolbox version and calls the
% required function accordingly.
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also emlBlock, matlabFunctionBlock.
% Copyright (C) 1993-2014, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = symexpr2slblock(varargin)
% V5.8 (R2012a)
if verLessThan('symbolic','5.7')
emlBlock(varargin{:});
elseif verLessThan('symbolic','5.11')
matlabFunctionBlock(varargin{:});
else
% Work around a bug in matlabFunctionBlock.m
%% Read orignal file
fid = fopen(which('matlabFunctionBlock.m'),'r');
funStr = fscanf(fid, '%c',inf);
fclose(fid);
%% Create Temporary Workaround File
tmpFName = fullfile(pwd,'tmp_workaround_matlabFunctionBlock.m');
% perform necessary modifications
funStr = strrep(funStr,...
'if isa(b,''Stateflow.EMChart'')',... Buggy expression to be replaced
'if ~strcmp(class(b),''Stateflow.EMChart'')'); % Working expression from previous version.
funStr = strrep(funStr,...
'matlabFunctionBlock',... Buggy expression to be replaced
'tmp_workaround_matlabFunctionBlock'); % Working expression from previous version.
% write modified function to temporary file
fid = fopen(tmpFName, 'w');
fprintf(fid,'%s\n','% This is a temporary file used as workaround for a bug in matlabFunctionBlock.m (R2013b).');
fprintf(fid,'%s\n','% It should have been deleted automatically by the Robotics Toolbox. If not, feel free to do it manually.');
fprintf(fid,'%s',funStr);
fclose(fid);
% update function database
rehash
% perform the actual block generation
tmp_workaround_matlabFunctionBlock(varargin{:});
% clean up
delete(tmpFName);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plot_vehicle.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/plot_vehicle.m
| 7,750 |
utf_8
|
22444c9c63225df884542619910283e2
|
%plot_vehicle Draw mobile robot pose
%
% PLOT_VEHICLE(X,OPTIONS) draws an oriented triangle to represent the pose
% of a mobile robot moving in a planar world. The pose X (1x3) = [x,y,theta].
% If X is a matrix (Nx3) then an animation of the robot motion is shown and
% animated at the specified frame rate.
%
% Image mode::
%
% Create a structure with the following elements and pass it with the
% 'model' option.
%
% image an RGB image (HxWx3)
% alpha an alpha plane (HxW) with pixels 0 if transparent
% rotation image rotation in degrees required for front to pointing to the right
% centre image coordinate (U,V) of the centre of the back axle
% length length of the car in real-world units
%
% Animation mode::
%
% H = PLOT_VEHICLE(X,OPTIONS) as above draws the robot and returns a handle.
%
% PLOT_VEHICLE(X, 'handle', H) updates the pose X (1x3) of the previously drawn
% robot.
%
% Options::
% 'scale',S draw vehicle with length S x maximum axis dimension (default
% 1/60)
% 'size',S draw vehicle with length S
% 'fillcolor',F the color of the circle's interior, MATLAB color spec
% 'alpha',A transparency of the filled circle: 0=transparent, 1=solid
% 'box' draw a box shape (default is triangle)
% 'fps',F animate at F frames per second (default 10)
% 'image',I use an image to represent the robot pose
% 'retain' when X (Nx3) then retain the robots, leaving a trail
% 'model',M animate an image of the vehicle. M is a structure with
% elements: image, alpha, rotation (deg), centre (pix), length (m).
% 'axis',h handle of axis or UIAxis to draw into (default is current axis)
% 'movie',M create a movie file in file M
%
% Example::
% [car.image,~,car.alpha] = imread('car2.png'); % image and alpha layer
% car.rotation = 180; % image rotation to align front with world x-axis
% car.centre = [648; 173]; % image coordinates of centre of the back wheels
% car.length = 4.2; % real world length for scaling (guess)
% h = plot_vehicle(x, 'model', car) % draw car at configuration x
% plot_vehicle(x, 'handle', h) % animate car to configuration x
%
% Notes::
% - The vehicle is drawn relative to the size of the axes, so set them
% first using axis().
% - For backward compatibility, 'fill', is a synonym for 'fillcolor'
% - For the 'model' option, you provide a monochrome or color image of the
% vehicle. Optionally you can provide an alpha mask (0=transparent).
% Specify the reference point on the vehicle as the (x,y) pixel
% coordinate within the image. Specify the rotation, in degrees, so that
% the car's front points to the right. Finally specify a length of the
% car, the image is scaled to be that length in the plot.
% - Set 'fps' to Inf to have zero pause
%
% See also Vehicle.plot, Animate, plot_poly, demos/car_animation
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% TODO needs to work for 3D point
function h_ = plot_vehicle(x, varargin)
opt.scale = 1/60;
opt.size = [];
opt.shape = {'triangle', 'box'};
opt.fps = 20;
opt.handle = [];
opt.image = [];
opt.model = [];
opt.retain = false;
opt.axis = [];
opt.trail = '';
opt.movie = [];
if numel(x) == 3
x = x(:)'; % enforce row vector
end
[opt,args] = tb_optparse(opt, varargin);
if isempty(opt.handle)
% create a new robot
% compute some default dimensions based on axis scaling
if isempty(opt.axis)
opt.axis = gca;
end
ax = opt.axis;
a = [ax.XLim ax.YLim];
d = (a(2)+a(4) - a(1)-a(3)) * opt.scale;
% create the robot
h.vehicle = draw_robot(d, opt, args);
if ~isempty(opt.trail)
hold on
h.trail = plot(0,0, opt.trail);
hold off
end
h.opt = opt;
plot_vehicle(x, 'handle', h, varargin{:});
else
% we are animating
h = opt.handle;
anim = Animate(opt.movie);
for i=1:numrows(x)
h.vehicle.Matrix = SE2(x(i,:)).SE3.T; % convert (x,y,th) to SE(3)
% check if retain is on
if h.opt.retain
plot_vehicle(x(i,:));
end
% extend the line if required
if ~isempty(h.opt.trail)
l = h.trail;
l.XData = [l.XData x(i,1)];
l.YData = [l.YData x(i,2)];
end
% pause a while
anim.add();
if ~isinf(h.opt.fps)
pause(1/h.opt.fps)
end
end
anim.close();
end
if nargout > 0
h_ = h;
end
end
function h = draw_robot(d, opt, args)
if ~isempty(opt.model)
% display an image of a vehicle, pass in a struct
if isstruct(opt.model)
img = opt.model.image;
rotation = opt.model.rotation;
centre = opt.model.centre;
scale = opt.model.length / max(numcols(img), numrows(img)) ;
else
img = opt.image;
centre = [numcols(img)/2 numrows(img)/2];
end
h = hgtransform('Tag', 'image');
h2 = hgtransform('Matrix', trotz(rotation, 'deg')*trscale(scale)*transl(-centre(1), -centre(2),0), 'Parent', h );
if isfield(opt.model, 'alpha')
% use alpha data if provided
alpha = opt.model.alpha;
else
% otherwise black pixels (0,0,0) are set to transparent
alpha = any(img>0,3);
end
image(img, 'AlphaData', alpha, 'Parent', h2);
%axis equal
else
% display a simple polygon
switch opt.shape
case 'triangle'
if ~isempty(opt.size)
d = opt.size;
end
L = d; W = 0.6*d;
corners = [
L 0
-L -W
-L W]';
case 'box'
if ~isempty(opt.size)
switch length(opt.size)
case 1
W = opt.size/2; L1 = opt.size/2; L2 = opt.size/2;
case 2
W = opt.size(1)/2; L1 = opt.size(2)/2; L2 = opt.size(2)/2;
case 3
W = opt.size(1)/2; L1 = opt.size(2); L2 = opt.size(3);
end
else
L1 = d; L2 = d; W = 0.6*d;
end
corners = [
-L1 W
0.6*L2 W
L2 0.5*W
L2 -0.5*W
0.6*L2 -W
-L1 -W ]';
end
h = plot_poly(corners, 'animate', 'axis', opt.axis, args{:});
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
multidfprintf.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/multidfprintf.m
| 2,127 |
utf_8
|
269527702c93cdc5c3b7ffcc62415799
|
%MULTIDFPRINTF Print formatted text to multiple streams
%
% COUNT = MULTIDFPRINTF(IDVEC, FORMAT, A, ...) performs formatted output
% to multiple streams such as console and files. FORMAT is the format string
% as used by sprintf and fprintf. A is the array of elements, to which the
% format will be applied similar to sprintf and fprint.
%
% IDVEC is a vector (1xN) of file descriptors and COUNT is a vector (1xN) of
% the number of bytes written to each file.
%
% Notes::
% - To write to the consolde use the file identifier 1.
%
% Example::
% % Create and open a new example file:
% fid = fopen('exampleFile.txt','w+');
% % Write something to the file and the console simultaneously:
% multidfprintf([1 FID],'% s % d % d % d!\n','This is a test!',1,2,3);
% % Close the file:
% fclose(FID);
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also fprintf,sprintf.
% Copyright (C) 1993-2014, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [count] = multidfprintf(idVec,varargin)
if isempty(idVec)
warning('multIDFprintf','Target ID is empty. Nothing is written.')
count = [];
else
count = zeros(size(idVec));
for iID = 1:numel(idVec)
if idVec(iID) < 1
count(iID) = 0;
else
count(iID) = fprintf(idVec(iID),varargin{:});
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
Link.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/Link.m
| 40,102 |
utf_8
|
4a5eaa697b66710d52413e6460dbbac2
|
%LinkRobot manipulator Link class
%
% A Link object holds all information related to a robot joint and link such as
% kinematics parameters, rigid-body inertial parameters, motor and
% transmission parameters.
%
% Constructors::
% Link general constructor
% Prismatic construct a prismatic joint+link using standard DH
% PrismaticMDH construct a prismatic joint+link using modified DH
% Revolute construct a revolute joint+link using standard DH
% RevoluteMDH construct a revolute joint+link using modified DH
%
% Information/display methods::
% display print the link parameters in human readable form
% dyn display link dynamic parameters
% type joint type: 'R' or 'P'
%
% Conversion methods::
% char convert to string
%
% Operation methods::
% A link transform matrix
% friction friction force
% nofriction Link object with friction parameters set to zero%
%
% Testing methods::
% islimit test if joint exceeds soft limit
% isrevolute test if joint is revolute
% isprismatic test if joint is prismatic
% issym test if joint+link has symbolic parameters
%
% Overloaded operators::
% + concatenate links, result is a SerialLink object
%
% Properties (read/write)::
%
% theta kinematic: joint angle
% d kinematic: link offset
% a kinematic: link length
% alpha kinematic: link twist
% jointtype kinematic: 'R' if revolute, 'P' if prismatic
% mdh kinematic: 0 if standard D&H, else 1
% offset kinematic: joint variable offset
% qlim kinematic: joint variable limits [min max]
%-
% m dynamic: link mass
% r dynamic: link COG wrt link coordinate frame 3x1
% I dynamic: link inertia matrix, symmetric 3x3, about link COG.
% B dynamic: link viscous friction (motor referred)
% Tc dynamic: link Coulomb friction
%-
% G actuator: gear ratio
% Jm actuator: motor inertia (motor referred)
%
% Examples::
%
% L = Link([0 1.2 0.3 pi/2]);
% L = Link('revolute', 'd', 1.2, 'a', 0.3, 'alpha', pi/2);
% L = Revolute('d', 1.2, 'a', 0.3, 'alpha', pi/2);
%
% Notes::
% - This is a reference class object.
% - Link objects can be used in vectors and arrays.
% - Convenience subclasses are Revolute, Prismatic, RevoluteMDH and
% PrismaticMDH.
%
% References::
% - Robotics, Vision & Control, P. Corke, Springer 2011, Chap 7.
%
% See also Link, Revolute, Prismatic, SerialLink, RevoluteMDH, PrismaticMDH.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
classdef Link < matlab.mixin.Copyable
properties
% kinematic parameters
theta % kinematic: link angle
d % kinematic: link offset
alpha % kinematic: link twist
a % kinematic: link length
jointtype % revolute='R', prismatic='P' -- should be an enum
mdh % standard DH=0, MDH=1
offset % joint coordinate offset
name % joint coordinate name
flip % joint moves in opposite direction
% dynamic parameters
m % dynamic: link mass
r % dynamic: position of COM with respect to link frame (3x1)
I % dynamic: inertia of link with respect to COM (3x3)
Jm % dynamic: motor inertia
B % dynamic: motor viscous friction (1x1 or 2x1)
Tc % dynamic: motor Coulomb friction (1x2 or 2x1)
G % dynamic: gear ratio
qlim % joint coordinate limits (2x1)
end
methods
function l = Link(varargin)
%Link Create robot link object
%
% This the class constructor which has several call signatures.
%
% L = Link() is a Link object with default parameters.
%
% L = Link(LNK) is a Link object that is a deep copy of the link
% object LNK and has type Link, even if LNK is a subclass.
%
% L = Link(OPTIONS) is a link object with the kinematic and dynamic
% parameters specified by the key/value pairs.
%
% Options::
% 'theta',TH joint angle, if not specified joint is revolute
% 'd',D joint extension, if not specified joint is prismatic
% 'a',A joint offset (default 0)
% 'alpha',A joint twist (default 0)
% 'standard' defined using standard D&H parameters (default).
% 'modified' defined using modified D&H parameters.
% 'offset',O joint variable offset (default 0)
% 'qlim',L joint limit (default [])
% 'I',I link inertia matrix (3x1, 6x1 or 3x3)
% 'r',R link centre of gravity (3x1)
% 'm',M link mass (1x1)
% 'G',G motor gear ratio (default 1)
% 'B',B joint friction, motor referenced (default 0)
% 'Jm',J motor inertia, motor referenced (default 0)
% 'Tc',T Coulomb friction, motor referenced (1x1 or 2x1), (default [0 0])
% 'revolute' for a revolute joint (default)
% 'prismatic' for a prismatic joint 'p'
% 'standard' for standard D&H parameters (default).
% 'modified' for modified D&H parameters.
% 'sym' consider all parameter values as symbolic not numeric
%
% Notes::
% - It is an error to specify both 'theta' and 'd'
% - The joint variable, either theta or d, is provided as an argument to
% the A() method.
% - The link inertia matrix (3x3) is symmetric and can be specified by giving
% a 3x3 matrix, the diagonal elements [Ixx Iyy Izz], or the moments and products
% of inertia [Ixx Iyy Izz Ixy Iyz Ixz].
% - All friction quantities are referenced to the motor not the load.
% - Gear ratio is used only to convert motor referenced quantities such as
% friction and interia to the link frame.
%
% Old syntax::
% L = Link(DH, OPTIONS) is a link object using the specified kinematic
% convention and with parameters:
% - DH = [THETA D A ALPHA SIGMA OFFSET] where SIGMA=0 for a revolute and 1
% for a prismatic joint; and OFFSET is a constant displacement between the
% user joint variable and the value used by the kinematic model.
% - DH = [THETA D A ALPHA SIGMA] where OFFSET is zero.
% - DH = [THETA D A ALPHA], joint is assumed revolute and OFFSET is zero.
%
% Options::
%
% 'standard' for standard D&H parameters (default).
% 'modified' for modified D&H parameters.
% 'revolute' for a revolute joint, can be abbreviated to 'r' (default)
% 'prismatic' for a prismatic joint, can be abbreviated to 'p'
%
% Notes::
% - The parameter D is unused in a revolute joint, it is simply a placeholder
% in the vector and the value given is ignored.
% - The parameter THETA is unused in a prismatic joint, it is simply a placeholder
% in the vector and the value given is ignored.
%
% Examples::
% A standard Denavit-Hartenberg link
% L3 = Link('d', 0.15005, 'a', 0.0203, 'alpha', -pi/2);
% since 'theta' is not specified the joint is assumed to be revolute, and
% since the kinematic convention is not specified it is assumed 'standard'.
%
% Using the old syntax
% L3 = Link([ 0, 0.15005, 0.0203, -pi/2], 'standard');
% the flag 'standard' is not strictly necessary but adds clarity. Only 4 parameters
% are specified so sigma is assumed to be zero, ie. the joint is revolute.
%
% L3 = Link([ 0, 0.15005, 0.0203, -pi/2, 0], 'standard');
% the flag 'standard' is not strictly necessary but adds clarity. 5 parameters
% are specified and sigma is set to zero, ie. the joint is revolute.
%
% L3 = Link([ 0, 0.15005, 0.0203, -pi/2, 1], 'standard');
% the flag 'standard' is not strictly necessary but adds clarity. 5 parameters
% are specified and sigma is set to one, ie. the joint is prismatic.
%
% For a modified Denavit-Hartenberg revolute joint
% L3 = Link([ 0, 0.15005, 0.0203, -pi/2, 0], 'modified');
%
% Notes::
% - Link object is a reference object, a subclass of Handle object.
% - Link objects can be used in vectors and arrays.
% - The joint offset is a constant added to the joint angle variable before
% forward kinematics and subtracted after inverse kinematics. It is useful
% if you want the robot to adopt a 'sensible' pose for zero joint angle
% configuration.
% - The link dynamic (inertial and motor) parameters are all set to
% zero. These must be set by explicitly assigning the object
% properties: m, r, I, Jm, B, Tc.
% - The gear ratio is set to 1 by default, meaning that motor friction and
% inertia will be considered if they are non-zero.
%
% See also Revolute, Prismatic, RevoluteMDH, PrismaticMDH.
if nargin == 0
% create an 'empty' Link object
% this call signature is needed to support arrays of Links
%% kinematic parameters
l.alpha = 0;
l.a = 0;
l.theta = 0;
l.d = 0;
l.jointtype = 'R';
l.mdh = 0;
l.offset = 0;
l.flip = false;
l.qlim = [];
%% dynamic parameters
% these parameters must be set by the user if dynamics is used
l.m = 0;
l.r = [0 0 0];
l.I = zeros(3,3);
% dynamic params with default (zero friction)
l.Jm = 0;
l.G = 1;
l.B = 0;
l.Tc = [0 0];
elseif nargin == 1 && isa(varargin{1}, 'Link')
% clone the passed Link object
this = varargin{1};
for j=1:length(this)
l(j) = Link();
% Copy all non-hidden properties.
p = properties(this(j));
for i = 1:length(p)
l(j).(p{i}) = this(j).(p{i});
end
end
else
% Create a new Link based on parameters
% parse all possible options
opt.theta = [];
opt.a = 0;
opt.d = [];
opt.alpha = 0;
opt.G = 0;
opt.B = 0;
opt.Tc = [0 0];
opt.Jm = 0;
opt.I = zeros(3,3);
opt.m = 0;
opt.r = [0 0 0];
opt.offset = 0;
opt.qlim = [];
opt.type = {[], 'revolute', 'prismatic', 'fixed'};
opt.convention = {'standard', 'modified'};
opt.sym = false;
opt.flip = false;
[opt,args] = tb_optparse(opt, varargin);
% return a parameter as a number of symbol depending on
% the 'sym' option
if isempty(args)
% This is the new call format, where all parameters are
% given by key/value pairs
%
% eg. L3 = Link('d', 0.15005, 'a', 0.0203, 'alpha', -pi/2);
assert(isempty(opt.d) || isempty(opt.theta), 'RTB:Link:badarg', 'cannot specify ''d'' and ''theta''');
if opt.type
switch (opt.type)
case 'revolute'
l.jointtype = 'R';
assert(isempty(opt.theta), 'RTB:Link:badarg', 'cannot specify ''theta'' for revolute link');
if isempty(opt.d)
opt.d = 0;
end
case 'prismatic'
l.jointtype = 'P';
assert(isempty(opt.d), 'RTB:Link:badarg', 'cannot specify ''d'' for prismatic link');
if isempty(opt.theta)
opt.theta = 0;
end
end
end
if ~isempty(opt.theta)
% constant value of theta means it must be prismatic
l.theta = value( opt.theta, opt);
l.jointtype = 'P';
end
if ~isempty(opt.d)
% constant value of d means it must be revolute
l.d = value( opt.d, opt);
l.jointtype = 'R';
end
l.a = value( opt.a, opt);
l.alpha = value( opt.alpha, opt);
l.offset = value( opt.offset, opt);
l.flip = value( opt.flip, opt);
l.qlim = value( opt.qlim, opt);
l.m = value( opt.m, opt);
l.r = value( opt.r, opt);
l.I = value( opt.I, opt);
l.Jm = value( opt.Jm, opt);
l.G = value( opt.G, opt);
l.B = value( opt.B, opt);
l.Tc = value( opt.Tc, opt);
else
% This is the old call format, where all parameters are
% given by a vector containing kinematic-only, or
% kinematic plus dynamic parameters
%
% eg. L3 = Link([ 0, 0.15005, 0.0203, -pi/2, 0], 'standard');
dh = args{1};
assert(length(dh) >= 4, 'RTB:Link:badarg', 'must provide params (theta d a alpha)');
% set the kinematic parameters
l.theta = dh(1);
l.d = dh(2);
l.a = dh(3);
l.alpha = dh(4);
l.jointtype = 'R'; % default to revolute
l.offset = 0;
l.flip = false;
l.mdh = 0; % default to standard D&H
% optionally set sigma and offset
if length(dh) >= 5
if dh(5) == 1
l.jointtype = 'P';
end
end
if length(dh) == 6
l.offset = dh(6);
end
if length(dh) > 6
% legacy DYN matrix
if dh(5) > 0
l.jointtype = 'P';
else
l.jointtype = 'R';
end
l.mdh = 0; % default to standard D&H
l.offset = 0;
% it's a legacy DYN matrix
l.m = dh(6);
l.r = dh(7:9).'; % a column vector
v = dh(10:15);
l.I = [ v(1) v(4) v(6)
v(4) v(2) v(5)
v(6) v(5) v(3)];
if length(dh) > 15
l.Jm = dh(16);
end
if length(dh) > 16
l.G = dh(17);
else
l.G = 1;
end
if length(dh) > 17
l.B = dh(18);
else
l.B = 0.0;
end
if length(dh) > 18
l.Tc = dh(19:20);
else
l.Tc = [0 0];
end
l.qlim = [];
else
% we know nothing about the dynamics
l.m = [];
l.r = [];
l.I = [];
l.Jm = [];
l.G = 0;
l.B = 0;
l.Tc = [0 0];
l.qlim = [];
end
end
% set the kinematic convention to be used
if strcmp(opt.convention, 'modified')
l.mdh = 1;
else
l.mdh = 0;
end
end
function out = value(v, opt)
if opt.sym
out = sym(v);
else
out = v;
end
end
end % link()
function tau = friction(l, qd)
%Link.friction Joint friction force
%
% F = L.friction(QD) is the joint friction force/torque (1xN) for joint
% velocity QD (1xN). The friction model includes:
% - Viscous friction which is a linear function of velocity.
% - Coulomb friction which is proportional to sign(QD).
%
% Notes::
% - The friction value should be added to the motor output torque, it has a
% negative value when QD>0.
% - The returned friction value is referred to the output of the gearbox.
% - The friction parameters in the Link object are referred to the motor.
% - Motor viscous friction is scaled up by G^2.
% - Motor Coulomb friction is scaled up by G.
% - The appropriate Coulomb friction value to use in the non-symmetric case
% depends on the sign of the joint velocity, not the motor velocity.
% - The absolute value of the gear ratio is used. Negative gear ratios are
% tricky: the Puma560 has negative gear ratio for joints 1 and 3.
%
% See also Link.nofriction.
% viscous friction
tau = l.B * abs(l.G) * qd;
% Coulomb friction
if ~isa(qd, 'sym')
if qd > 0
tau = tau + l.Tc(1);
elseif qd < 0
tau = tau + l.Tc(2);
end
end
% scale up by gear ratio
tau = -abs(l.G) * tau; % friction opposes motion
end % friction()
function tau = friction2(l, qd)
% experimental code
qdm = qd / l.G;
taum = -l.B * qdm;
if qdm > 0
taum = taum - l.Tc(1);
elseif qdm < 0
taum = taum - l.Tc(2);
end
tau = taum * l.G;
end
function l2 = nofriction(l, only)
%Link.nofriction Remove friction
%
% LN = L.nofriction() is a link object with the same parameters as L except
% nonlinear (Coulomb) friction parameter is zero.
%
% LN = L.nofriction('all') as above except that viscous and Coulomb friction
% are set to zero.
%
% LN = L.nofriction('coulomb') as above except that Coulomb friction is set to zero.
%
% LN = L.nofriction('viscous') as above except that viscous friction is set to zero.
%
% Notes::
% - Forward dynamic simulation can be very slow with finite Coulomb friction.
%
% See also Link.friction, SerialLink.nofriction, SerialLink.fdyn.
l2 = copy(l);
if nargin == 1
only = 'coulomb';
end
switch only
case 'all'
l2.B = 0;
l2.Tc = [0 0];
case 'viscous'
l2.B = 0;
case 'coulomb'
l2.Tc = [0 0];
end
end
function v = RP(l)
warning('RTB:Link:deprecated', 'use the .type() method instead');
v = l.type();
end
function v = type(l)
%Link.type Joint type
%
% c = L.type() is a character 'R' or 'P' depending on whether joint is
% revolute or prismatic respectively. If L is a vector of Link objects
% return an array of characters in joint order.
%
% See also SerialLink.config.
v = '';
for ll=l
switch ll.jointtype
case 'R'
v = strcat(v, 'R');
case 'P'
v = strcat(v, 'P');
otherwise
error('RTB:Link:badval', 'bad value for link jointtype %d', ll.type);
end
end
end
function set.r(l, v)
%Link.r Set centre of gravity
%
% L.r = R sets the link centre of gravity (COG) to R (3-vector).
%
if isempty(v)
return;
end
assert(length(v) == 3, 'RTB:Link:badarg', 'COG must be a 3-vector');
l.r = v(:).';
end % set.r()
function set.Tc(l, v)
%Link.Tc Set Coulomb friction
%
% L.Tc = F sets Coulomb friction parameters to [F -F], for a symmetric
% Coulomb friction model.
%
% L.Tc = [FP FM] sets Coulomb friction to [FP FM], for an asymmetric
% Coulomb friction model. FP>0 and FM<0. FP is applied for a positive
% joint velocity and FM for a negative joint velocity.
%
% Notes::
% - The friction parameters are defined as being positive for a positive
% joint velocity, the friction force computed by Link.friction uses the
% negative of the friction parameter, that is, the force opposing motion of
% the joint.
%
% See also Link.friction.
if isempty(v)
return;
end
if isa(v,'sym') && ~isempty(symvar(v))
l.Tc = sym('Tc');
elseif isa(v,'sym') && isempty(symvar(v))
v = double(v);
end
if length(v) == 1 ~isa(v,'sym')
l.Tc = [v -v];
elseif length(v) == 2 && ~isa(v,'sym')
assert(v(1) >= v(2), 'RTB:Link:badarg', 'Coulomb friction is [Tc+ Tc-]');
l.Tc = v;
else
error('RTB:Link:badarg', 'Coulomb friction vector can have 1 (symmetric) or 2 (asymmetric) elements only')
end
end % set.Tc()
function set.I(l, v)
%Link.I Set link inertia
%
% L.I = [Ixx Iyy Izz] sets link inertia to a diagonal matrix.
%
% L.I = [Ixx Iyy Izz Ixy Iyz Ixz] sets link inertia to a symmetric matrix with
% specified inertia and product of intertia elements.
%
% L.I = M set Link inertia matrix to M (3x3) which must be symmetric.
if isempty(v)
return;
end
if all(size(v) == [3 3])
assert(isa(v, 'sym') || (norm(v-v') < eps), 'RTB:Link:badarg', 'inertia matrix must be symmetric');
l.I = v;
elseif length(v) == 3
l.I = diag(v);
elseif length(v) == 6
l.I = [ v(1) v(4) v(6)
v(4) v(2) v(5)
v(6) v(5) v(3) ];
else
error('RTB:Link:badarg', 'must set I to 3-vector, 6-vector or symmetric 3x3');
end
end % set.I()
function v = islimit(l, q)
%Link.islimit Test joint limits
%
% L.islimit(Q) is true (1) if Q is outside the soft limits set for this joint.
%
% Note::
% - The limits are not currently used by any Toolbox functions.
assert(~isempty(l.qlim), 'RTB:Link:badarg', 'no limits assigned to link')
v = (q > l.qlim(2)) - (q < l.qlim(1));
end % islimit()
function v = isrevolute(L)
%Link.isrevolute Test if joint is revolute
%
% L.isrevolute() is true (1) if joint is revolute.
%
% See also Link.isprismatic.
v = [L.jointtype] == 'R';
end
function v = isprismatic(L)
%Link.isprismatic Test if joint is prismatic
%
% L.isprismatic() is true (1) if joint is prismatic.
%
% See also Link.isrevolute.
v = ~L.isrevolute();
end
function T = A(L, q)
%Link.A Link transform matrix
%
% T = L.A(Q) is an SE3 object representing the transformation between link
% frames when the link variable Q which is either the Denavit-Hartenberg
% parameter THETA (revolute) or D (prismatic). For:
% - standard DH parameters, this is from the previous frame to the current.
% - modified DH parameters, this is from the current frame to the next.
%
% Notes::
% - For a revolute joint the THETA parameter of the link is ignored, and Q used instead.
% - For a prismatic joint the D parameter of the link is ignored, and Q used instead.
% - The link offset parameter is added to Q before computation of the transformation matrix.
%
% See also SerialLink.fkine.
if iscell(q)
q = q{1}; % get value of cell, happens for the symfun case
end
sa = sin(L.alpha); ca = cos(L.alpha);
if L.flip
q = -q + L.offset;
else
q = q + L.offset;
end
if L.isrevolute
% revolute
st = sin(q); ct = cos(q);
d = L.d;
else
% prismatic
st = sin(L.theta); ct = cos(L.theta);
d = q;
end
if L.mdh == 0
% standard DH
T = [ ct -st*ca st*sa L.a*ct
st ct*ca -ct*sa L.a*st
0 sa ca d
0 0 0 1];
else
% modified DH
T = [ ct -st 0 L.a
st*ca ct*ca -sa -sa*d
st*sa ct*sa ca ca*d
0 0 0 1];
end
T = SE3(T);
end % A()
function display(l)
%Link.display Display parameters
%
% L.display() displays the link parameters in compact single line format. If L is a
% vector of Link objects displays one line per element.
%
% Notes::
% - This method is invoked implicitly at the command line when the result
% of an expression is a Link object and the command has no trailing
% semicolon.
%
% See also Link.char, Link.dyn, SerialLink.showlink.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
disp( char(l) );
end % display()
function s = char(links, from_robot)
%Link.char Convert to string
%
% s = L.char() is a string showing link parameters in a compact single line format.
% If L is a vector of Link objects return a string with one line per Link.
%
% See also Link.display.
% display in the order theta d a alpha
if nargin < 2
from_robot = false;
end
s = '';
for j=1:length(links)
l = links(j);
if l.mdh == 0
conv = 'std';
else
conv = 'mod';
end
if length(links) == 1
qname = 'q';
else
qname = sprintf('q%d', j);
end
if from_robot
fmt = '%11g';
% invoked from SerialLink.char method, format for table
if l.isprismatic
% prismatic joint
js = sprintf('|%3d|%11s|%11s|%11s|%11s|%11s|', ...
j, ...
render(l.theta, fmt), ...
qname, ...
render(l.a, fmt), ...
render(l.alpha, fmt), ...
render(l.offset, fmt));
else
% revolute joint
js = sprintf('|%3d|%11s|%11s|%11s|%11s|%11s|', ...
j, ...
qname, ...
render(l.d, fmt), ...
render(l.a, fmt), ...
render(l.alpha, fmt), ...
render(l.offset, fmt));
end
else
if length(links) == 1
if l.isprismatic
% prismatic joint
js = sprintf('Prismatic(%s): theta=%s, d=%s, a=%s, alpha=%s, offset=%s', ...
conv, ...
render(l.theta,'%g'), ...
qname, ...
render(l.a,'%g'), ...
render(l.alpha,'%g'), ...
render(l.offset,'%g') );
else
% revolute
js = sprintf('Revolute(%s): theta=%s, d=%s, a=%s, alpha=%s, offset=%s', ...
conv, ...
qname, ...
render(l.d,'%g'), ...
render(l.a,'%g'), ...
render(l.alpha,'%g'), ...
render(l.offset,'%g') );
end
else
if l.isprismatic
% prismatic joint
js = sprintf('Prismatic(%s): theta=%s d=%s a=%s alpha=%s offset=%s', ...
conv, ...
render(l.theta), ...
qname, ...
render(l.a), ...
render(l.alpha), ...
render(l.offset) );
else
% revolute
js = sprintf('Revolute(%s): theta=%s d=%s a=%s alpha=%s offset=%s', ...
conv, ...
qname, ...
render(l.d), ...
render(l.a), ...
render(l.alpha), ...
render(l.offset) );
end
end
end
if isempty(s)
s = js;
else
s = char(s, js);
end
end
end % char()
function dyn(links)
%Link.dyn Show inertial properties of link
%
% L.dyn() displays the inertial properties of the link object in a multi-line
% format. The properties shown are mass, centre of mass, inertia, friction,
% gear ratio and motor properties.
%
% If L is a vector of Link objects show properties for each link.
%
% See also SerialLink.dyn.
for j=1:numel(links)
l = links(j);
if numel(links) > 1
fprintf('\nLink %d::', j);
end
fprintf('%s\n', l.char());
if ~isempty(l.m)
fprintf(' m = %s\n', render(l.m))
end
if ~isempty(l.r)
s = render(l.r);
fprintf(' r = %s %s %s\n', s{:});
end
if ~isempty(l.I)
s = render(l.I(1,:));
fprintf(' I = | %s %s %s |\n', s{:});
s = render(l.I(2,:));
fprintf(' | %s %s %s |\n', s{:});
s = render(l.I(3,:));
fprintf(' | %s %s %s |\n', s{:});
end
if ~isempty(l.Jm)
fprintf(' Jm = %s\n', render(l.Jm));
end
if ~isempty(l.B)
fprintf(' Bm = %s\n', render(l.B));
end
if ~isempty(l.Tc)
fprintf(' Tc = %s(+) %s(-)\n', ...
render(l.Tc(1)), render(l.Tc(2)));
end
if ~isempty(l.G)
fprintf(' G = %s\n', render(l.G));
end
if ~isempty(l.qlim)
fprintf(' qlim = %f to %f\n', l.qlim(1), l.qlim(2));
end
end
end % dyn()
% Make a copy of a handle object.
% http://www.mathworks.com/matlabcentral/newsreader/view_thread/257925
% function new = copy(this)
%
% for j=1:length(this)
% % Instantiate new object of the same class.
% %new(j) = feval(class(this(j)));
% new(j) = Link();
% % Copy all non-hidden properties.
% p = properties(this(j));
% for i = 1:length(p)
% new(j).(p{i}) = this(j).(p{i});
% end
% end
% end
function links = horzcat(varargin)
%Link.horzcat Concatenate link objects
%
% [L1 L2] is a vector that contains deep copies of the Link class objects
% L1 and L2.
%
% Notes::
% - The elements of the vector are all of type Link.
% - If the elements were of a subclass type they are convered to type Link.
% - Extends to arbitrary number of objects in list.
%
% See also Link.plus.
% convert all elements to Link type
l = cellfun(@Link, varargin, 'UniformOutput', 0);
% convert to vector, cell2mat won't do this for me
links = cat(2, l{:});
end
function links = vertcat(this, varargin)
links = this.horzcat(varargin{:});
end
function R = plus(L1, L2)
%Link.plus Concatenate link objects into a robot
%
% L1+L2 is a SerialLink object formed from deep copies of the Link class objects
% L1 and L2.
%
% Notes::
% - The elements can belong to any of the Link subclasses.
% - Extends to arbitrary number of objects, eg. L1+L2+L3+L4.
%
% See also SerialLink, SerialLink.plus, Link.horzcat.
assert( isa(L1, 'Link') && isa(L2, 'Link'), 'RTB:Link: second operand for + operator must be a Link class');
R = SerialLink([L1 L2]);
end
function res = issym(l)
%Link.issym Check if link is a symbolic model
%
% res = L.issym() is true if the Link L has any symbolic parameters.
%
% See also Link.sym.
res = any( cellfun(@(x) isa(l.(x), 'sym'), properties(l)) );
end
function l = sym(l)
%Link.sym Convert link parameters to symbolic type
%
% LS = L.sym is a Link object in which all the parameters are symbolic
% ('sym') type.
%
% See also Link.issym.
% sl = Link(l); % clone the link
if ~isempty(l.theta)
l.theta = sym(l.theta);
end
if ~isempty(l.d)
l.d = sym(l.d);
end
l.alpha = sym(l.alpha);
l.a = sym(l.a);
l.offset = sym(l.offset);
l.I = sym(l.I);
l.r = sym(l.r);
l.m = sym(l.m);
l.Jm = sym(l.Jm);
l.G = sym(l.G);
l.B = sym(l.B);
l.Tc = sym(l.Tc);
end
end % methods
end % class
function s = render(v, fmt)
if nargin < 2
fmt = '%-11.4g';
end
if length(v) == 1
if isa(v, 'double')
s = sprintf(fmt, v);
elseif isa(v, 'sym')
s = char(v);
else
error('RTB:Link:badarg', 'Link parameter must be numeric or symbolic');
end
else
for i=1:length(v)
if isa(v, 'double')
s{i} = sprintf(fmt, v(i));
elseif isa(v, 'sym')
s{i} = char(v(i));
else
error('RTB:Link:badarg', 'Link parameter must be numeric or symbolic');
end
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
chi2inv_rtb.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/chi2inv_rtb.m
| 2,719 |
utf_8
|
4423a2dd1fe3d30b8b42770183814f06
|
%CHI2INV_RTB Inverse chi-squared function
%
% X = CHI2INV_RTB(P, N) is the inverse chi-squared CDF function of N-degrees of freedom.
%
% Notes::
% - only works for N=2
% - uses a table lookup with around 6 figure accuracy
% - an approximation to chi2inv() from the Statistics & Machine Learning Toolbox
%
% See also chi2inv.
% Copyright (C) 1993-2019 Peter I. Corke
%
% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
% of the Software, and to permit persons to whom the Software is furnished to do
% so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%
% https://github.com/petercorke/robotics-toolbox-matlab
function f = chi2inv_rtb(confidence, n)
assert(n == 2, 'RTB:chi2inv_rtb:badarg', 'only valid for 2DOF');
c = linspace(0,1,101);
% build a lookup table:
%x = chi2inv(c,2)
%fprintf('%f ');
% use the lookup table
x = [0.000000 0.020101 0.040405 0.060918 0.081644 0.102587 0.123751 0.145141 0.166763 0.188621 0.210721 0.233068 0.255667 0.278524 0.301646 0.325038 0.348707 0.372659 0.396902 0.421442 0.446287 0.471445 0.496923 0.522730 0.548874 0.575364 0.602210 0.629421 0.657008 0.684981 0.713350 0.742127 0.771325 0.800955 0.831031 0.861566 0.892574 0.924071 0.956072 0.988593 1.021651 1.055265 1.089454 1.124238 1.159637 1.195674 1.232372 1.269757 1.307853 1.346689 1.386294 1.426700 1.467938 1.510045 1.553058 1.597015 1.641961 1.687940 1.735001 1.783196 1.832581 1.883217 1.935168 1.988505 2.043302 2.099644 2.157619 2.217325 2.278869 2.342366 2.407946 2.475749 2.545931 2.618667 2.694147 2.772589 2.854233 2.939352 3.028255 3.121295 3.218876 3.321462 3.429597 3.543914 3.665163 3.794240 3.932226 4.080442 4.240527 4.414550 4.605170 4.815891 5.051457 5.318520 5.626821 5.991465 6.437752 7.013116 7.824046 9.210340 Inf];
f = interp1(c, x, confidence);
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
urdfparse.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/urdfparse.m
| 9,788 |
utf_8
|
d0af7861ce0ee091003833312f7cbaaf
|
function urdf = urdfparse(filename)
root = xmlread(filename);
robot = root.getElementsByTagName('robot').item(0);
%% process all the materials elements
% - these are optional but we do them first because link elements
% reference them
materialNodes = getChildrenByTagName(robot, 'material');
materials = [];
materialNames = [];
if ~isempty(materialNodes)
for i = 1:length(materialNodes)
node = materialNodes(i);
materials(i).name = string(node.getAttribute('name'));
materials(i).rgba = str2num(node.getElementsByTagName('color').item(0).getAttribute('rgba'));
materials(i).node = node;
end
urdf.materials = materials;
materialNames = [materials.name];
end
%% process all the link elements
% create a vector of joint structures, fields are:
% name name of the joint
% type type of joint (fixed, continuous, prismatic)
% T SE3 object for pose of joint wrt link frame
% xyz position of joint wrt link frame
% rpy RPY angles of joint frame wrt link frame
% node reference to XML DOM node for this <joint>
% child link index for downstream link
% parent link index for downstream link
linkNodes = getChildrenByTagName(robot, 'link');
for i = 1:length(linkNodes)
node = linkNodes(i);
links(i).name = string(node.getAttribute('name'));
try
links(i).geometry = node.getElementsByTagName('geometry').item(0);
links(i).mesh = links(i).geometry.getElementsByTagName('mesh').item(0).getAttribute('filename');
end
try
links(i).material = find(strcmp((node.getElementsByTagName('material').item(0).getAttribute('name')), materialNames));
end
try
inertial = node.getElementsByTagName('inertial').item(0);
try
links(i).m = str2num(inertial.getElementsByTagName('mass').item(0).getAttribute('value'));
end
try
I = inertial.getElementsByTagName('inertia').item(0);
links(i).I.xx = str2num(I.getAttribute('ixx'));
links(i).I.xy = str2num(I.getAttribute('ixy'));
links(i).I.xz = str2num(I.getAttribute('ixz'));
links(i).I.yy = str2num(I.getAttribute('iyy'));
links(i).I.yz = str2num(I.getAttribute('iyz'));
links(i).I.zz = str2num(I.getAttribute('izz'));
end
try
t = str2num( node.getElementsByTagName('origin').item(0).getAttribute('xyz'));
rpy = str2num( node.getElementsByTagName('origin').item(0).getAttribute('rpy'));
links(i).com = SE3(t) * SE3.rpy(rpy);
end
end
t = [0 0 0]; rpy = [0 0 0]; % in case not provided
try
t = str2num( node.getElementsByTagName('origin').item(0).getAttribute('xyz'));
rpy = str2num( node.getElementsByTagName('origin').item(0).getAttribute('rpy'));
end
if isempty(t)
t = [0 0 0]; % in case the tag has no attribute
end
if isempty(rpy)
rpy = [0 0 0]; % in case the tag has no attribute
end
links(i).T = SE3(t) * SE3.rpy(rpy);
links(i).node = node;
links(i).children = [];
links(i).parent = [];
end
linkNames = [links.name]; % a list of link names
%% process all the joint elements
% create a vector of link structures, fields are are:
% name name of the link
% geometry reference to XML DOM node
% T SE3 object for origin of visual wrt link frame
% node reference to XML DOM node for this <link>
% children list of joint indexes attaching this link to its children
% parent index of joint attaching this link to its parent
jointNodes = getChildrenByTagName(robot, 'joint');
joints = [];
for i = 1:length(jointNodes)
node = jointNodes(i);
joints(i).name = string(node.getAttribute('name'));
joints(i).type = string(node.getAttribute('type'));
try
joints(i).axis = str2num(node.getElementsByTagName('axis').item(0).getAttribute('xyz'));
end
p = find(strcmp(node.getElementsByTagName('parent').item(0).getAttribute('link'), linkNames));
c = find(strcmp(node.getElementsByTagName('child').item(0).getAttribute('link'), linkNames));
joints(i).parent = p;
joints(i).child = c;
links(p).children = [links(p).children i];
links(c).parent = i;
t = [0 0 0]; rpy = [0 0 0]; % in case not provided
try
t = str2num( node.getElementsByTagName('origin').item(0).getAttribute('xyz'));
rpy = str2num( node.getElementsByTagName('origin').item(0).getAttribute('rpy'));
end
if isempty(t)
t = [0 0 0]; % in case the tag has no attribute
end
if isempty(rpy)
rpy = [0 0 0]; % in case the tag has no attribute
end
joints(i).T = SE3(t) * SE3.rpy(rpy);
joints(i).xyz = t;
joints(i).rpy = rpy;
joints(i).node = node;
end
urdf.joints = joints;
urdf.links = links;
urdf.endlinks = find( cellfun('isempty', {links.children}) );
urdf.ets = [];
%% create a transform list
% the mechanism might have multiple endpoints (if branched), for each
% endpoint compute an ETS chain and return a string array
for endlink = urdf.endlinks
transforms = "";
joint = joints(links(endlink).parent);
while true
transforms = xform2s(joint) + axis2s(joint) + transforms;
joint = joints(links(joint.parent).parent);
if isempty(joint)
break;
end
end
transforms = strtrim(transforms);
urdf.ets = [urdf.ets transforms];
end
%% display a summary
fprintf('\nLinks::\n');
for i=1:length(links)
name = links(i).name;
if ismember(i, urdf.endlinks)
name = "*" + name;
end
geomlist = "";
if ~isempty(links(i).geometry)
g = links(i).geometry.getChildNodes;
for k=0:g.getLength-1
c = g.item(k);
if c.getNodeType == 1 % skip text nodes
if geomlist == ""
geomlist = "shape=";
else
geomlist = geomlist + ", ";
end
geomlist = geomlist + string(c.getNodeName);
end
end
end
fprintf('%2d: %10s; parentjoint=%s, childjoints=%s; %s\n', i, name, ...
formatj(links(i).parent), formatj(links(i).children), geomlist);
end
if ~isempty(joints)
fprintf('\nJoints::\n');
for i=1:length(joints)
fprintf('%2d: %10s; type=%s, parentlink=%d, childlink=%d\n', i, joints(i).name, joints(i).type, joints(i).parent, joints(i).child);
end
end
if ~isempty(materials)
fprintf('\nMaterials::\n');
for i=1:length(materials)
fprintf('%10s: %f %f %f %f\n', materials(i).name, materials(i).rgba);
end
end
if strlength(transforms) > 0
fprintf('\nForward kinematics::\n %s\n', transforms);
end
end
function s = formatj(j)
if isempty(j)
s = '-';
else
s = strip(num2str(j, '%d,'), 'right', ',');
end
end
function t = xform2s(joint)
t = "";
if joint.xyz(1) ~= 0
t = t + sprintf('Tx(%.12g) ', joint.xyz(1));
end
if joint.xyz(2) ~= 0
t = t + sprintf('Ty(%.12g) ', joint.xyz(2));
end
if joint.xyz(3) ~= 0
t = t + sprintf('Tz(%.12g) ', joint.xyz(3));
end
if joint.rpy(3) ~= 0
t = t + sprintf('Rz(%.12g) ', round(joint.rpy(3)*180/pi, 3));
end
if joint.rpy(2) ~= 0
t = t + sprintf('Ry(%.12g) ', round(joint.rpy(2)*180/pi,3));
end
if joint.rpy(1) ~= 0
t = t + sprintf('Rx(%.12g) ', round(joint.rpy(1)*180/pi, 3));
end
end
function t = axis2s(joint)
t = "";
switch joint.type
case {'revolute', 'continuous'}
assert(length(find(joint.axis)) == 1, 'Joint axis must be about x, y or z only');
if joint.axis(1) ~= 0
t = t + sprintf('Rx(%s) ', joint.name);
end
if joint.axis(2) ~= 0
t = t + sprintf('Ry(%s) ', joint.name);
end
if joint.axis(3) ~= 0
t = t + sprintf('Rz(%s) ', joint.name);
end
case 'prismatic'
assert(length(find(joint.axis)) == 1, 'Joint axis must be about x, y or z only');
if joint.axis(1) ~= 0
t = t + sprintf('Tx(%s) ', joint.name);
end
if joint.axis(2) ~= 0
t = t + sprintf('Ty(%s) ', joint.name);
end
if joint.axis(3) ~= 0
t = t + sprintf('Tz(%s) ', joint.name);
end
case 'fixed'
end
end
function children = getChildrenByTagName(parent, name)
% return array of immediate child nodes with node name equal to name
% REF https://stackoverflow.com/questions/18776408/get-all-the-children-for-a-given-xml-in-java
children = [];
childnodes = parent.getChildNodes;
for i=1:childnodes.getLength
node = childnodes.item(i-1);
if node.getNodeType == node.ELEMENT_NODE && strcmp(node.getNodeName, name)
children = [children node];
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockinvdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockinvdyn.m
| 5,724 |
utf_8
|
afad377845919de9ebcb17abab541250
|
%CODEGENERATOR.GENSLBLOCKINVDYN Generate Simulink block for inverse dynamics
%
% cGen.genslblockinvdyn() generates a robot-specific Simulink block to compute
% inverse dynamics.
%
% Notes::
% - Is called by CodeGenerator.geninvdyn if cGen has active flag genslblock
% - The generated Simulink block is composed of previously generated blocks
% for the inertia matrix, coriolis matrix, vector of gravitational load and
% joint friction vector. The block recombines these components to compute
% the forward dynamics.
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ output_args ] = genslblockinvdyn( CGen )
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
checkexistanceofblocks(CGen);
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
%% Generate Inertia Block
CGen.logmsg([datestr(now),'\tGenerating Simulink Block for the inverse robot dynamics:\n']);
nJoints = CGen.rob.n;
CGen.logmsg([datestr(now),'\t\t... enclosing subsystem ']);
InvDynBlock = [CGen.slib,'/invdyn'];
if ~isempty(find_system(CGen.slib,'Name','invdyn')) % Delete previously generated inertia matrix block
delete_block(InvDynBlock)
end
CGen.logmsg('\t%s\n',' done!');
% Subsystem in which individual rows are concatenated
CGen.logmsg([datestr(now),'\t\t... adding Simulink blocks for all components']);
add_block('built-in/SubSystem',InvDynBlock); % Add new inertia matrix block
add_block([CGen.slib,'/inertia'],[InvDynBlock,'/inertia']);
add_block([CGen.slib,'/coriolis'],[InvDynBlock,'/coriolis']);
add_block([CGen.slib,'/gravload'],[InvDynBlock,'/gravload']);
add_block([CGen.slib,'/friction'],[InvDynBlock,'/friction'])
add_block('simulink/Sources/In1',[InvDynBlock,'/q']);
add_block('simulink/Sources/In1',[InvDynBlock,'/qd']);
add_block('simulink/Sources/In1',[InvDynBlock,'/qdd']);
add_block('simulink/Sinks/Out1',[InvDynBlock,'/tau']);
add_block('built-in/Product',[InvDynBlock,'/inertiaTorque'],'multiplication','Matrix(*)');
add_block('built-in/Product',[InvDynBlock,'/coriolisTorque'],'multiplication','Matrix(*)');
add_block('built-in/Sum',[InvDynBlock,'/Sum'],'inputs','++++');
CGen.logmsg('\t%s\n',' done!');
% Connect individual Simulink blocks
CGen.logmsg([datestr(now),'\t\t... wiring']);
add_line(InvDynBlock,'q/1','inertia/1');
add_line(InvDynBlock,'q/1','coriolis/1');
add_line(InvDynBlock,'q/1','gravload/1');
add_line(InvDynBlock,'qd/1','coriolis/2');
add_line(InvDynBlock,'qd/1','friction/1');
add_line(InvDynBlock,'inertia/1','inertiaTorque/1');
add_line(InvDynBlock,'qdd/1','inertiaTorque/2');
add_line(InvDynBlock,'coriolis/1','coriolisTorque/1');
add_line(InvDynBlock,'qd/1','coriolisTorque/2');
add_line(InvDynBlock,'inertiaTorque/1','Sum/1');
add_line(InvDynBlock,'coriolisTorque/1','Sum/2');
add_line(InvDynBlock,'gravload/1','Sum/3');
add_line(InvDynBlock,'friction/1','Sum/4');
add_line(InvDynBlock,'Sum/1','tau/1');
distributeblocks(InvDynBlock);
CGen.logmsg('\t%s\n',' done!');
CGen.logmsg([datestr(now),'\tInverse dynamics block complete.\n']);
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
function [] = checkexistanceofblocks(CGen)
open_system(CGen.slibpath);
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','inertia'))
CGen.logmsg('\t\t%s\n','Inertia block not found! Generating:');
CGen.genslblockinertia;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','coriolis'))
CGen.logmsg('\t\t%s\n','Coriolis block not found! Generating:');
CGen.genslblockcoriolis;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','gravload'))
CGen.logmsg('\t\t%s\n','Gravload block not found! Generating:');
CGen.genslblockgravload;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','friction'))
CGen.logmsg('\t\t%s\n','Friction block not found! Generating:');
CGen.genslblockfriction;
open_system(CGen.slibpath);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodeinertia.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodeinertia.m
| 8,186 |
utf_8
|
b5b74e2dfe3efe794b0b2d5e95b6c1b8
|
%CODEGENERATOR.GENCCODEINERTIA Generate C-function for robot inertia matrix
%
% cGen.genccodeinertia() generates robot-specific C-functions to compute
% the robot inertia matrix.
%
% Notes::
% - Is called by CodeGenerator.geninertia if cGen has active flag genccode or
% genmex.
% - The generated .c and .h files are generated in the directory specified
% by the ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia, CodeGenerator.genmexinertia.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodeinertia(CGen)
%%
CGen.logmsg([datestr(now),'\tGenerating C-code for the robot inertia matrix row' ]);
% check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
Q = CGen.rob.gencoords;
nJoints = CGen.rob.n;
%% Individual inertia matrix rows
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuninertia:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{Q},'output',['I_row_',num2str(kJoints)]);
% Create the function description header
hStruct = createHeaderStructRow(CGen.rob,kJoints,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
end
CGen.logmsg('\t%s\n',' done!');
%% Full inertia matrix
CGen.logmsg([datestr(now),'\tGenerating full inertia matrix C-code']);
symname = 'inertia';
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
outname = 'I';
% Generate function prototype
[hstring] = ccodefunctionstring(sym(zeros(nJoints)),...
'funname',funname,...
'vars',{Q},'output',outname,'flag',1);
% Create the function description header
hStruct = createHeaderStructFull(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
fprintf(fid,'%s{\n\n',hstring);
fprintf(fid,'\t%s\n','/* allocate memory for individual rows */');
for kJoints = 1:nJoints
fprintf(fid,'\tdouble row%d[%d][1];\n',kJoints,nJoints);
end
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','/* call the row routines */');
for kJoints = 1:nJoints
fprintf(fid,'\t%s_inertia_row_%d(row%d, input1);\n',CGen.getrobfname,kJoints,kJoints);
end
fprintf(fid,'%s\n',' '); % empty line\n
% Copy results into output matrix
for iJoints = 1:nJoints
for kJoints = 1:nJoints
fprintf(fid,'\t%s[%d][%d] = row%d[%d][0];\n',outname,kJoints-1,iJoints-1,iJoints,kJoints-1);
end
fprintf(fid,'%s\n',' '); % empty line\n
end
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
for kJoints = 1:nJoints
rowstring = [CGen.getrobfname,'_inertia_row_',num2str(kJoints)];
fprintf(fid,'%s\n',...
['#include "',rowstring,'.h"']);
end
fprintf(fid,'%s\n',' '); % empty line
% Function prototype
fprintf(fid,'%s;\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Computation of the robot specific inertia matrix row for corresponding to joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
['inertia matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'. Angles have to be given in radians!']};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['I_row_',int2str(curJointIdx),': [1x',int2str(rob.n),'] output row of the robot inertia matrix.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFull(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Inertia matrix for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables the function computes the',...
'inertia Matrix of the robot. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['I: [',int2str(rob.n),'x',int2str(rob.n),']output inertia matrix.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodecoriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodecoriolis.m
| 8,395 |
utf_8
|
7cbd3d0c1dc4484f93e8bbf65eb3d5c8
|
%CODEGENERATOR.GENCCODECORIOLIS Generate C-function for robot inertia matrix
%
% cGen.genccodecoriolis() generates robot-specific C-functions to compute
% the robot coriolis matrix.
%
% Notes::
% - Is called by CodeGenerator.gencoriolis if cGen has active flag genccode or
% genmex.
% - The .c and .h files are generated in the directory specified by the
% ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis, CodeGenerator.genmexcoriolis.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodecoriolis(CGen)
%%
CGen.logmsg([datestr(now),'\tGenerating C-code for the robot coriolis matrix row' ]);
% check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
[Q,QD] = CGen.rob.gencoords;
nJoints = CGen.rob.n;
%% Individual coriolis matrix rows
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuncoriolis:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{Q,QD},'output',['C_row_',num2str(kJoints)]);
% Create the function description header
hStruct = createHeaderStructRow(CGen.rob,kJoints,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
end
CGen.logmsg('\t%s\n',' done!');
%% Full Coriolis matrix
CGen.logmsg([datestr(now),'\tGenerating full coriolis matrix C-code']);
symname = 'coriolis';
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
outname = 'C';
% Generate function prototype
[hstring] = ccodefunctionstring(sym(zeros(nJoints)),...
'funname',funname,...
'vars',{Q,QD},'output',outname,'flag',1);
% Create the function description header
hStruct = createHeaderStructFull(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
fprintf(fid,'%s{\n\n',hstring);
fprintf(fid,'\t%s\n','/* allocate memory for individual rows */');
for kJoints = 1:nJoints
fprintf(fid,'\tdouble row%d[%d][1];\n',kJoints,nJoints);
end
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','/* call the row routines */');
for kJoints = 1:nJoints
fprintf(fid,'\t%s_coriolis_row_%d(row%d, input1, input2);\n',CGen.getrobfname,kJoints,kJoints);
end
fprintf(fid,'%s\n',' '); % empty line\n
% Copy results into output matrix
for iJoints = 1:nJoints
for kJoints = 1:nJoints
fprintf(fid,'\t%s[%d][%d] = row%d[%d][0];\n',outname,kJoints-1,iJoints-1,iJoints,kJoints-1);
end
fprintf(fid,'%s\n',' '); % empty line\n
end
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
for kJoints = 1:nJoints
rowstring = [CGen.getrobfname,'_coriolis_row_',num2str(kJoints)];
fprintf(fid,'%s\n',...
['#include "',rowstring,'.h"']);
end
fprintf(fid,'%s\n',' '); % empty line
% Function prototype
fprintf(fid,'%s;\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Computation of the robot specific Coriolis matrix row for corresponding to joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
['Coriolis matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'. Angles have to be given in radians!']};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities']};
hStruct.outputs = {['C_row_',int2str(curJointIdx),': [1x',int2str(rob.n),'] row of the robot Coriolis matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFull(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Coriolis matrix for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables the function computes the',...
'Coriolis matrix of the robot. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities']};
hStruct.outputs = {['C: [',int2str(rob.n),'x',int2str(rob.n),'] Coriolis matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexinvdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexinvdyn.m
| 4,996 |
utf_8
|
291a151d3346724fcd00c543d7550c7b
|
%CODEGENERATOR.GENMEXINVDYN Generate C-MEX-function for inverse dynamics
%
% cGen.genmexinvdyn() generates a robot-specific MEX-function to compute
% the inverse dynamics.
%
% Notes::
% - Is called by CodeGenerator.geninvdyn if cGen has active flag genmex.
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexinvdyn(CGen)
CGen.logmsg([datestr(now),'\tGenerating inverse dynamics MEX-function: ']);
mexfunname = 'invdyn';
mexcfilename = fullfile(CGen.robjpath,[mexfunname,'.c']);
cfunname = [CGen.getrobfname,'_',mexfunname];
cfilename = [cfunname '.c'];
hfilename = [cfunname '.h'];
[Q, QD, QDD] = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStruct(CGen.rob,mexfunname);
hFString = CGen.constructheaderstringc(hStruct);
fid = fopen(mexcfilename,'w+');
% Insert description header
fprintf(fid,'%s\n',hFString);
% Includes
fprintf(fid,'%s\n%s\n\n',...
'#include "mex.h"',...
['#include "',hfilename,'"']);
dummy = sym(zeros(CGen.rob.n,1));
% Generate the mex gateway routine
funstr = CGen.genmexgatewaystring(dummy,'funname',cfunname, 'vars',{Q, QD, QDD});
fprintf(fid,'%s',sprintf(funstr));
fclose(fid);
%% Compile the MEX file
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
cfilelist = fullfile(srcDir,cfilename);
for kJoints = 1:CGen.rob.n
cfilelist = [cfilelist, ' ',fullfile(srcDir,[CGen.getrobfname,'_inertia_row_',num2str(kJoints),'.c'])];
end
for kJoints = 1:CGen.rob.n
cfilelist = [cfilelist, ' ',fullfile(srcDir,[CGen.getrobfname,'_coriolis_row_',num2str(kJoints),'.c'])];
end
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_gravload.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_friction.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,'dotprod.c')];
if CGen.verbose
eval(['mex ',mexcfilename, ' ',cfilelist,' -I',hdrDir, ' -v -outdir ',CGen.robjpath]);
else
eval(['mex ',mexcfilename, ' ',cfilelist,' -I',hdrDir,' -outdir ',CGen.robjpath]);
end
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C-implementation of the inverse dynamics for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables and their first and second order',...
'temporal derivatives this function computes the joint space',...
'torques needed to perform the particular motion. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities,'],...
['input3: ',int2str(rob.n),'-element vector of generalized accelerations.']};
hStruct.outputs = {['TAU: [',int2str(rob.n),'x1] vector of joint forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fdyn'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexfriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexfriction.m
| 3,721 |
utf_8
|
a9814b9b6e885a481dec4d4c55d862f5
|
%CODEGENERATOR.GENMEXFRICTION Generate C-MEX-function for joint friction
%
% cGen.genmexfriction() generates a robot-specific MEX-function to compute
% the vector of joint friction.
%
% Notes::
% - Is called by CodeGenerator.genfriction if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexfriction(CGen)
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating friction vector MEX-function: ']);
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfungravload:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
[QD] = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStruct(CGen.rob,symname);
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname),...
'funfilename',funfilename,...
'funname',[CGen.getrobfname,'_',symname],...
'vars',{QD},...
'output','F',...
'header',hStruct);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['Joint friction for the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of generalized joint velocities the function'],...
'computes the friction forces/torques. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized velocities.']};
hStruct.outputs = {['F: [',int2str(rob.n),'x1] output vector of joint friction forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'gravload'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexfdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexfdyn.m
| 5,183 |
utf_8
|
eb8eeeda2303e75caec906da342beb0d
|
%CODEGENERATOR.GENMEXFDYN Generate C-MEX-function for forward dynamics
%
% cGen.genmexfdyn() generates a robot-specific MEX-function to compute
% the forward dynamics.
%
% Notes::
% - Is called by CodeGenerator.genfdyn if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfdyn, CodeGenerator.genmexinvdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexfdyn(CGen)
CGen.logmsg([datestr(now),'\tGenerating inverse dynamics MEX-function: ']);
mexfunname = 'accel';
mexcfilename = fullfile(CGen.robjpath,[mexfunname,'.c']);
cfunname = [CGen.getrobfname,'_',mexfunname];
cfilename = [cfunname '.c'];
hfilename = [cfunname '.h'];
[Q, QD] = CGen.rob.gencoords;
[tau] = CGen.rob.genforces;
% Function description header
hStruct = createHeaderStruct(CGen.rob,mexfunname);
hFString = CGen.constructheaderstringc(hStruct);
fid = fopen(mexcfilename,'w+');
% Insert description header
fprintf(fid,'%s\n',hFString);
% Includes
fprintf(fid,'%s\n%s\n\n',...
'#include "mex.h"',...
['#include "',hfilename,'"']);
dummy = sym(zeros(CGen.rob.n,1));
% Generate the mex gateway routine
funstr = CGen.genmexgatewaystring(dummy,'funname',cfunname, 'vars',{Q, QD, tau});
fprintf(fid,'%s',sprintf(funstr));
fclose(fid);
%% Compile the MEX file
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
cfilelist = fullfile(srcDir,cfilename);
for kJoints = 1:CGen.rob.n
cfilelist = [cfilelist, ' ',fullfile(srcDir,[CGen.getrobfname,'_inertia_row_',num2str(kJoints),'.c'])];
end
for kJoints = 1:CGen.rob.n
cfilelist = [cfilelist, ' ',fullfile(srcDir,[CGen.getrobfname,'_coriolis_row_',num2str(kJoints),'.c'])];
end
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_inertia.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_coriolis.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_gravload.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,[CGen.getrobfname,'_friction.c'])];
cfilelist = [cfilelist, ' ', fullfile(srcDir,'matvecprod.c')];
cfilelist = [cfilelist, ' ', fullfile(srcDir,'gaussjordan.c')];
if CGen.verbose
eval(['mex ',mexcfilename, ' ',cfilelist,' -I',hdrDir, ' -v -outdir ',CGen.robjpath]);
else
eval(['mex ',mexcfilename, ' ',cfilelist,' -I',hdrDir,' -outdir ',CGen.robjpath]);
end
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C-implementation of the forward dynamics for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint angles and velocities',...
'this function computes the joint space accelerations effected by the generalized forces. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities'],...
['input3: [',int2str(rob.n),'x1] vector of generalized forces.']};
hStruct.outputs = {['QDD: ',int2str(rob.n),'-element output vector of generalized accelerations.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'invdyn'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockcoriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockcoriolis.m
| 6,317 |
utf_8
|
ee2b01938ede7878ddb96596bfb7cc30
|
%CODEGENERATOR.GENSLBLOCKCORIOLIS Generate Simulink block for Coriolis matrix
%
% cGen.genslblockcoriolis() generates a robot-specific Simulink block to compute
% Coriolis/centripetal matrix.
%
% Notes::
% - Is called by CodeGenerator.gencoriolis if cGen has active flag genslblock
% - The Coriolis matrix is stored row by row to avoid memory issues.
% - The Simulink block recombines the the individual blocks for each row.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = genslblockcoriolis( CGen )
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
[q,qd] = CGen.rob.gencoords;
%% Generate Coriolis Block
CGen.logmsg([datestr(now),'\tGenerating Simulink Block for the robot Coriolis matrix\n']);
nJoints = CGen.rob.n;
symname = 'coriolis';
CGen.logmsg([datestr(now),'\t\t... enclosing subsystem ']);
CoriolisBlock = [CGen.slib,'/',symname];
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(CoriolisBlock)
save_system;
end
% Subsystem in which individual rows are concatenated
add_block('built-in/SubSystem',CoriolisBlock); % Add new inertia matrix block
add_block('simulink/Math Operations/Matrix Concatenate'...
, [CoriolisBlock,'/coriolis']...
, 'NumInputs',num2str(nJoints)...
, 'ConcatenateDimension','1');
add_block('simulink/Sinks/Out1',[CoriolisBlock,'/out']);
add_block('simulink/Sources/In1',[CoriolisBlock,'/q']);
add_block('simulink/Sources/In1',[CoriolisBlock,'/qd']);
add_line(CoriolisBlock,'coriolis/1','out/1');
CGen.logmsg('\t%s\n',' done!');
for kJoints = 1:nJoints
CGen.logmsg([datestr(now),'\t\t... Embedded Matlab Function Block for joint ',num2str(kJoints),': ']);
% Generate Embedded Matlab Function block for each row
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genslblockcoriolis:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CoriolisBlock,'/',symname];
if doesblockexist(CGen.slib,symname)
delete_block(blockaddress);
save_system;
end
CGen.logmsg('%s',' block creation');
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q,qd});
% connect output
CGen.logmsg('%s',', output wiring');
if ( verLessThan('matlab','7.11.0.584') ) && ( isequal(tmpStruct.(symname),zeros(1,nJoints)) )
% There is a bug in earlier Matlab versions. If the symbolic
% vector is a zero vector, then the Simulink Embedded Matlab
% Function block outputs a scalar zero. We need to concatenate
% a row vector of zeros here, which we have to construct on our
% own.
add_block('simulink/Math Operations/Matrix Concatenate'... % Use a matrix concatenation block ...
, [CoriolisBlock,'/DimCorrection',num2str(kJoints)]... % ... named with the current row number ...
, 'NumInputs',num2str(nJoints),'ConcatenateDimension','2'); % ... intended to concatenate zero values for each joint ...
% ... columnwise. This will circumvent the bug.
for iJoints = 1:nJoints % Connect signal lines from the created block (which outputs
add_line(CoriolisBlock... % a scalar zero in this case) with the bugfix block.
, [symname,'/1']...
, ['DimCorrection',num2str(kJoints),'/', num2str(iJoints)]);
end
add_line(CoriolisBlock,['DimCorrection',num2str(kJoints)... % Connect the fixed row with other rows.
, '/1'],['coriolis/', num2str(kJoints)]);
else
add_line(CoriolisBlock,[symname,'/1']... % In case that no bug occurs, we can just connect the rows.
, ['coriolis/', num2str(kJoints)]);
end
% Vector generalized joint values
add_line(CoriolisBlock,'q/1',[symname,'/1']);
% Vector generalized joint velocities
add_line(CoriolisBlock,'qd/1',[symname,'/2']);
CGen.logmsg('\t%s\n','row complete!');
end
addterms(CoriolisBlock); % Add terminators where needed
distributeblocks(CoriolisBlock);
CGen.logmsg([datestr(now),'\tCoriolis matrix block complete\n']);
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
geninvdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/geninvdyn.m
| 4,980 |
utf_8
|
62f5f73b6e665fa36c21bf895c0aef31
|
%CODEGENERATOR.GENINVDYN Generate code for inverse dynamics
%
% TAU = cGen.geninvdyn() is the symbolic vector (1xN) of joint forces/torques.
%
% Notes::
% - The inverse dynamics vector is composed of the previously computed inertia matrix
% coriolis matrix, vector of gravitational load and joint friction for speedup.
% The generated code recombines these components to output the final vector.
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfdyn, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ tau ] = geninvdyn( CGen )
[q,qd,qdd] = CGen.rob.gencoords;
nJoints = CGen.rob.n;
%% Inertia matrix
CGen.logmsg([datestr(now),'\tLoading inertia matrix row by row']);
I = sym(zeros(nJoints));
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.geninertia;
end
tmpstruct = load(fname);
I(kJoints,:)=tmpstruct.(symname);
end
CGen.logmsg('\t%s\n',' done!');
%% Matrix of centrifugal and Coriolis forces/torques matrix
CGen.logmsg([datestr(now),'\tLoading Coriolis matrix row by row']);
C = sym(zeros(nJoints));
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.gencoriolis;
end
tmpstruct = load(fname);
C(kJoints,:)=tmpstruct.(symname);
end
CGen.logmsg('\t%s\n',' done!');
%% Vector of gravitational load
CGen.logmsg([datestr(now),'\tLoading vector of gravitational forces/torques']);
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.gengravload;
end
tmpstruct = load(fname);
G = tmpstruct.(symname);
CGen.logmsg('\t%s\n',' done!');
%% Joint friction
CGen.logmsg([datestr(now),'\tLoading joint friction vector']);
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.genfriction;
end
tmpstruct = load(fname);
F = tmpstruct.(symname);
CGen.logmsg('\t%s\n',' done!');
%% Full inverse dynamics
tau = I*qdd.'+C*qd.'+ G.' - F.';
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic inverse dynamics']);
CGen.savesym(tau,'invdyn','invdyn.mat')
CGen.logmsg('\t%s\n',' done!');
end
%% M-Functions
if CGen.genmfun
CGen.genmfuninvdyn;
end
%% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockinvdyn;
end
%% C-Code
if CGen.genccode
CGen.genccodeinvdyn;
end
%% MEX
if CGen.genmex
CGen.genmexinvdyn;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genfkine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genfkine.m
| 3,511 |
utf_8
|
e22c5af005a287a72b445b3bc1363c1c
|
%CODEGENERATOR.GENFKINE Generate code for forward kinematics
%
% T = cGen.genfkine() generates a symbolic homogeneous transform matrix (4x4) representing
% the pose of the robot end-effector in terms of the symbolic joint coordinates q1, q2, ...
%
% [T, ALLT] = cGen.genfkine() as above but also generates symbolic homogeneous transform
% matrices (4x4xN) for the poses of the individual robot joints.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genjacobian.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [t,allT] = genfkine(CGen)
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving forward kinematics']);
q = CGen.rob.gencoords;
[t, allT] = CGen.rob.fkine(q);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic forward kinematics up to end-effector frame']);
CGen.savesym(t,'fkine','fkine.mat')
CGen.logmsg('\t%s\n',' done!');
CGen.logmsg([datestr(now),'\tSaving symbolic forward kinematics for joint']);
for iJoint = 1:CGen.rob.n
CGen.logmsg(' %s ',num2str(iJoint));
tName = ['T0_',num2str(iJoint)];
eval([tName,' = allT(',num2str(iJoint),');']);
CGen.savesym(eval(tName),tName,[tName,'.mat']);
end
CGen.logmsg('\t%s\n',' done!');
end
%% M-Functions
if CGen.genmfun
CGen.genmfunfkine;
end
%% Embedded Matlab Function Simulink blocks
if CGen.genslblock
genslblockfkine(CGen);
end
%% C-Code
if CGen.genccode
CGen.genccodefkine;
end
%% MEX
if CGen.genmex
CGen.genmexfkine;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfunjacobian.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfunjacobian.m
| 6,072 |
utf_8
|
b7cac95f384568941c0b6461f9e59d9a
|
%CODEGENERATOR.GENMFUNJACOBIAN Generate M-functions for robot Jacobian
%
% cGen.genmfunjacobian() generates a robot-specific M-function to compute
% robot Jacobian.
%
% Notes::
% - Is called by CodeGenerator.genjacobian, if cGen has active flag genmfun
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmfunjacobian(CGen)
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
%% Forward kinematics up to tool center point
symname = 'jacob0';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
CGen.logmsg([datestr(now),'\tGenerating jacobian m-function with respect to the robot base frame']);
tmpStruct = load(fname);
else
error ('genmfunjacobian:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {symname},...
'vars', {'rob',[q]});
hStruct = createHeaderStructJacob0(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
symname = 'jacobe';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
CGen.logmsg([datestr(now),'\tGenerating jacobian m-function with respect to the robot end-effector frame']);
tmpStruct = load(fname);
else
error ('genMFunJacobian:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {symname},...
'vars', {'rob',[q]});
hStruct = createHeaderStructJacobe(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructJacob0(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Jacobian with respect to the base coordinate frame of the ',rob.name,' arm.'];
hStruct.calls = {['J0 = ',hStruct.funName,'(rob,q)'],...
['J0 = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the base frame.'};
hStruct.inputs = {['q: ',int2str(rob.n),'-element vector of generalized coordinates.'],...
'Angles have to be given in radians!'};
hStruct.outputs = {['J0: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'fkine,jacobe'};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructJacobe(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Jacobian with respect to the end-effector coordinate frame of the ',rob.name,' arm.'];
hStruct.calls = {['Jn = ',hStruct.funName,'(rob,q)'],...
['Jn = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the end-effector frame.'};
hStruct.inputs = {['q: ',int2str(rob.n),'-element vector of generalized coordinates.'],...
'Angles have to be given in radians!'};
hStruct.outputs = {['Jn: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'fkine,jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockgravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockgravload.m
| 2,915 |
utf_8
|
deff8478f55341abff93ff093a15d52a
|
%CODEGENERATOR.GENSLBLOCKGRAVLOAD Generate Simulink block for gravitational load
%
% cGen.genslblockgravload() generates a robot-specific Simulink block to compute
% gravitational load.
%
% Notes::
% - Is called by CodeGenerator.gengravload if cGen has active flag genslblock
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function genslblockgravload(CGen)
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
q = CGen.rob.gencoords;
%% Generate Block
CGen.logmsg([datestr(now),'\tGenerating Embedded Matlab Function Block for the vector of gravitational load forces/torques']);
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genslblockgravload:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CGen.slib,'/',symname];
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(blockaddress)
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q});
CGen.logmsg('\t%s\n',' done!');
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gengravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/gengravload.m
| 2,920 |
utf_8
|
bd14a1fd4ffcb79057a1eaa18024a62b
|
%CODEGENERATOR.GENGRAVLOAD Generate code for gravitational load
%
% G = cGen.gengravload() is a symbolic vector (1xN) of joint load
% forces/torques due to gravity.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genfdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [G] = gengravload(CGen)
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving gravitational load vector']);
q = CGen.rob.gencoords;
tmpRob = CGen.rob.nofriction;
G = tmpRob.gravload(q);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic expression for gravitational load']);
CGen.savesym(G,'gravload','gravload.mat');
CGen.logmsg('\t%s\n',' done!');
end
% M-Functions
if CGen.genmfun
CGen.genmfungravload;
end
% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockgravload;
end
%% C-Code
if CGen.genccode
CGen.genccodegravload;
end
%% MEX
if CGen.genmex
CGen.genmexgravload;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockfriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockfriction.m
| 2,955 |
utf_8
|
21e05afc6f65d9a2d1d0660c7d75833e
|
%CODEGENERATOR.GENSLBLOCKFRICTION Generate Simulink block for joint friction
%
% cGen.genslblockfriction() generates a robot-specific Simulink block to compute
% the joint friction model.
%
% Notes::
% - Is called by CodeGenerator.genfriction if cGen has active flag genslblock
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfriction.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ F ] = genslblockfriction( CGen )
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
[~,qd] = CGen.rob.gencoords;
%% Generate block
CGen.logmsg([datestr(now),'\tGenerating joint friction Embedded Matlab Function Block:']);
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genslblockgfriction:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(blockaddress)
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{qd});
CGen.logmsg('\t%s\n',' done!');
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfunfriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfunfriction.m
| 3,964 |
utf_8
|
d7fb64be7541246dfe5f3e5eb6e563e7
|
%CODEGENERATOR.GENMFUNFRICTION Generate M-function for joint friction
%
% cGen.genmfunfriction() generates a robot-specific M-function to compute
% joint friction.
%
% Notes::
% - Is called only if cGen has active flag genmfun
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ F ] = genmfunfriction( CGen )
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
%% Generate m-function
CGen.logmsg([datestr(now),'\tGenerating joint friction m-function']);
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfriction:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
[~,qd] = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {'F'},...
'vars', {'rob',[qd]});
hStruct = createHeaderStruct(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Joint friction for the ',rob.name,' arm.'];
hStruct.calls = {['F = ',hStruct.funName,'(rob,qd)'],...
['F = rob.',hStruct.funName,'(qd)']};
hStruct.detailedDescription = {['Given a full set of generalized joint velocities the function'],...
'computes the friction forces/torques.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
'Angles have to be given in radians!'};
hStruct.outputs = {['F: [',int2str(rob.n),'x1] vector of joint friction forces/torques']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'gravload'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexcoriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexcoriolis.m
| 6,232 |
utf_8
|
376fb3e5f05318511bb33842a1088824
|
%CODEGENERATION.GENMEXCORIOLIS Generate C-MEX-function for robot coriolis matrix
%
% cGen.genmexcoriolis() generates robot-specific MEX-functions to compute
% robot coriolis matrix.
%
% Notes::
% - Is called by CodeGenerator.gencoriolis if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated functions is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmexcoriolis(CGen)
%% Individual coriolis matrix rows
CGen.logmsg([datestr(now),'\tGenerating MEX-function for the robot coriolis matrix row' ]);
[Q, QD] = CGen.rob.gencoords;
nJoints = CGen.rob.n;
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuncoriolis:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
% Function description header
hStruct = createHeaderStructRow(CGen.rob,kJoints,symname); %generate header
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname), ...
'funfilename',funfilename,...
'funname',[CGen.getrobfname,'_',symname],...
'vars',{Q, QD},...
'output',['C_row',num2str(kJoints)],...
'header',hStruct);
end
CGen.logmsg('\t%s\n',' done!');
%% Full coriolis matrix
CGen.logmsg([datestr(now),'\tGenerating full coriolis matrix m-function']);
symname = 'coriolis';
f = sym(zeros(nJoints)); % dummy symbolic expression
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
funname = [CGen.getrobfname,'_',symname];
hStruct = createHeaderStructFull(CGen.rob,symname); % create header
hFString = CGen.constructheaderstringc(hStruct);
% Generate and compile MEX function
CGen.mexfunctionrowwise(f,...
'funfilename',funfilename,...
'funname',[CGen.getrobfname,'_',symname],...
'vars',{Q, QD},...
'output','C',...
'header',hStruct);
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.calls = '';
hStruct.shortDescription = ['Computation of the robot specific Coriolis matrix row for corresponding to joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
['Coriolis matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'. Angles have to be given in radians!']};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities']};
hStruct.outputs = {['C_row_',int2str(curJointIdx),': [1x',int2str(rob.n),'] row of the robot Coriolis matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFull(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['Coriolis matrix for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables the function computes the',...
'Coriolis matrix of the robot. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities']};
hStruct.outputs = {['C: [',int2str(rob.n),'x',int2str(rob.n),'] Coriolis matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfungravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfungravload.m
| 4,085 |
utf_8
|
d7da7274a9cd09da0e2ad7fb2004f6a4
|
%CODEGENERATOR.GENMFUNGRAVLOAD Generate M-functions for gravitational load
%
% cGen.genmfungravload() generates a robot-specific M-function to compute
% gravitation load forces and torques.
%
% Notes::
% - Is called by CodeGenerator.gengravload if cGen has active flag genmfun
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmfungravload(CGen)
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
CGen.logmsg([datestr(now),'\tGenerating m-function for the vector of gravitational load torques/forces' ]);
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfungravload:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {'G'},...
'vars', {'rob',[q]});
hStruct = createHeaderStructGravity(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
end
function hStruct = createHeaderStructGravity(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Computation of the configuration dependent vector of gravitational load forces/torques for ',rob.name];
hStruct.calls = {['G = ',hStruct.funName,'(rob,q)'],...
['G = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
'configuration dependent vector of gravitational load forces/torques.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
'Angles have to be given in radians!'};
hStruct.outputs = {['G: [',int2str(rob.n),'x1] vector of gravitational load forces/torques']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'inertia'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockfdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockfdyn.m
| 6,354 |
utf_8
|
8e9eae404cfb48d1211f10cba1a37699
|
%CODEGENERATOR.GENSLBLOCKFDYN Generate Simulink block for forward dynamics
%
% cGen.genslblockfdyn() generates a robot-specific Simulink block to compute
% forward dynamics.
%
% Notes::
% - Is called by CodeGenerator.genfdyn if cGen has active flag genslblock
% - The generated Simulink block is composed of previously generated blocks
% for the inertia matrix, coriolis matrix, vector of gravitational load and
% joint friction vector. The block recombines these components to compute
% the forward dynamics.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genslblockfdyn(CGen)
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
checkexistanceofblocks(CGen);
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
%% Generate forward dynamics block
CGen.logmsg([datestr(now),'\tGenerating Simulink Block for the forward dynamics\n']);
nJoints = CGen.rob.n;
CGen.logmsg([datestr(now),'\t\t... enclosing subsystem ']);
symname = 'fdyn';
forwDynamicsBlock = [CGen.slib,'/',symname];
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(forwDynamicsBlock)
save_system;
end
CGen.logmsg('\t%s\n',' done!');
% add required blocks
CGen.logmsg([datestr(now),'\t\t... adding Simulink blocks for all components']);
add_block('built-in/SubSystem',forwDynamicsBlock);
add_block([CGen.slib,'/invinertia'],[forwDynamicsBlock,'/invinertia']);
add_block([CGen.slib,'/coriolis'],[forwDynamicsBlock,'/coriolis']);
add_block([CGen.slib,'/gravload'],[forwDynamicsBlock,'/gravload']);
add_block([CGen.slib,'/friction'],[forwDynamicsBlock,'/friction']);
add_block('simulink/Sinks/Out1',[forwDynamicsBlock,'/q']);
add_block('simulink/Sinks/Out1',[forwDynamicsBlock,'/qDot']);
add_block('simulink/Sinks/Out1',[forwDynamicsBlock,'/qDDot']);
add_block('simulink/Sources/In1',[forwDynamicsBlock,'/tau']);
add_block('built-in/Sum',[forwDynamicsBlock,'/Sum'],'inputs','|+---');
add_block('built-in/Product',[forwDynamicsBlock,'/invInertiaMultiply'],'multiplication','Matrix(*)');
add_block('built-in/Product',[forwDynamicsBlock,'/coriolisMultiply'],'multiplication','Matrix(*)');
add_block('built-in/Integrator',[forwDynamicsBlock,'/Integrator1']);
add_block('built-in/Integrator',[forwDynamicsBlock,'/Integrator2']);
CGen.logmsg('\t%s\n',' done!');
% connect simulink blocks
CGen.logmsg([datestr(now),'\t\t... wiring']);
add_line(forwDynamicsBlock,'tau/1','Sum/1');
add_line(forwDynamicsBlock,'invInertiaMultiply/1','qDDot/1');
add_line(forwDynamicsBlock,'invInertiaMultiply/1','Integrator1/1');
add_line(forwDynamicsBlock,'Integrator1/1','Integrator2/1');
add_line(forwDynamicsBlock,'Integrator1/1','qDot/1');
add_line(forwDynamicsBlock,'Integrator2/1','q/1');
add_line(forwDynamicsBlock,'Integrator1/1','coriolis/2');
add_line(forwDynamicsBlock,'Integrator1/1','coriolisMultiply/2');
add_line(forwDynamicsBlock,'Integrator1/1','friction/1');
add_line(forwDynamicsBlock,'Integrator2/1','coriolis/1');
add_line(forwDynamicsBlock,'Integrator2/1','gravload/1');
add_line(forwDynamicsBlock,'Integrator2/1','invinertia/1');
add_line(forwDynamicsBlock,'invinertia/1','invInertiaMultiply/1');
add_line(forwDynamicsBlock,'Sum/1','invInertiaMultiply/2');
add_line(forwDynamicsBlock,'coriolisMultiply/1','Sum/2');
add_line(forwDynamicsBlock,'gravload/1','Sum/3');
add_line(forwDynamicsBlock,'friction/1','Sum/4');
add_line(forwDynamicsBlock,'coriolis/1','coriolisMultiply/1');
distributeblocks(forwDynamicsBlock);
CGen.logmsg('\t%s\n',' done!');
CGen.logmsg([datestr(now),'\tForward dynamics block complete\n']);
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
function [] = checkexistanceofblocks(CGen)
open_system(CGen.slibpath);
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','inertia')) || isempty(find_system(CGen.slib,'SearchDepth',1,'Name','invinertia'))
CGen.logmsg('\t\t%s\n','Inertia block not found! Generating:');
CGen.genslblockinertia;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','coriolis'))
CGen.logmsg('\t\t%s\n','Coriolis block not found! Generating:');
CGen.genslblockcoriolis;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','gravload'))
CGen.logmsg('\t\t%s\n','Gravload block not found! Generating:');
CGen.genslblockgravload;
open_system(CGen.slibpath);
end
if isempty(find_system(CGen.slib,'SearchDepth',1,'Name','friction'))
CGen.logmsg('\t\t%s\n','Friction block not found! Generating:');
CGen.genslblockfriction;
open_system(CGen.slibpath);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexinertia.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexinertia.m
| 6,022 |
utf_8
|
2885568f8638b139afbe322bb4e162e2
|
%CODEGENERATION.GENMEXINERTIA Generate C-MEX-function for robot inertia matrix
%
% cGen.genmexinertia() generates robot-specific MEX-functions to compute
% robot inertia matrix.
%
% Notes::
% - Is called by CodeGenerator.geninertia if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated functions is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmexinertia(CGen)
%% Individual inertia matrix rows
CGen.logmsg([datestr(now),'\tGenerating MEX-function for the robot inertia matrix row' ]);
Q = CGen.rob.gencoords;
nJoints = CGen.rob.n;
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuninertia:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
% Function description header
hStruct = createHeaderStructRow(CGen.rob,kJoints,symname); %generate header
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname), ...
'funfilename',funfilename,...
'funname',[CGen.getrobfname,'_',symname],...
'vars',{Q},...
'output',['I_row',num2str(kJoints)],...
'header',hStruct);
end
CGen.logmsg('\t%s\n',' done!');
%% Full inertia matrix
CGen.logmsg([datestr(now),'\tGenerating full inertia matrix m-function']);
symname = 'inertia';
f = sym(zeros(nJoints)); % dummy symbolic expression
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
funname = [CGen.getrobfname,'_',symname];
hStruct = createHeaderStructFull(CGen.rob,symname); % create header
hFString = CGen.constructheaderstringc(hStruct);
% Generate and compile MEX function
CGen.mexfunctionrowwise(f,...
'funfilename',funfilename,...
'funname',[CGen.getrobfname,'_',symname],...
'vars',{Q},...
'output','I',...
'header',hStruct);
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.calls = '';
hStruct.shortDescription = ['Computation of the robot specific inertia matrix row for corresponding to joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
['inertia matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'. Angles have to be given in radians!']};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['I_row_',int2str(curJointIdx),': [1x',int2str(rob.n),'] output row of the robot inertia matrix.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFull(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['Inertia matrix for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables the function computes the',...
'inertia Matrix of the robot. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['I: [',int2str(rob.n),'x',int2str(rob.n),']output inertia matrix.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'coriolis'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genjacobian.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genjacobian.m
| 3,105 |
utf_8
|
fcde6fa80b8188dab9370059f48c6bf7
|
%CODEGENERATOR.GENJACOBIAN Generate code for robot Jacobians
%
% J0 = cGen.genjacobian() is the symbolic expression for the Jacobian
% matrix (6xN) expressed in the base coordinate frame.
%
% [J0, Jn] = cGen.genjacobian() as above but also returns the symbolic
% expression for the Jacobian matrix (6xN) expressed in the end-effector
% frame.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [J0, Jn] = genjacobian(CGen)
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving robot jacobians']);
q = CGen.rob.gencoords;
J0 = CGen.rob.jacob0(q);
Jn = CGen.rob.jacobe(q);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic robot jacobians']);
CGen.savesym(J0,'jacob0','jacob0.mat');
CGen.savesym(Jn,'jacobe','jacobe.mat');
CGen.logmsg('\t%s\n',' done!');
end
% M-Functions
if CGen.genmfun
CGen.genmfunjacobian;
end
% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockjacobian;
end
%% C-Code
if CGen.genccode
CGen.genccodejacobian;
end
%% MEX
if CGen.genmex
CGen.genmexjacobian;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexjacobian.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexjacobian.m
| 5,809 |
utf_8
|
769e393febe884ab0c876ab91987b9ac
|
%CODEGENERATOR.GENMEXJACOBIAN Generate C-MEX-function for the robot Jacobians
%
% cGen.genmexjacobian() generates robot-specific MEX-function to compute
% the robot Jacobian with respect to the base as well as the end effector
% frame.
%
% Notes::
% - Is called by CodeGenerator.genjacobian if cGen has active flag genmex.
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genjacobian.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexjacobian(CGen)
%% Jacobian w.r.t. the robot base
symname = 'jacob0';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
CGen.logmsg([datestr(now),'\tGenerating Jacobian MEX-function with respect to the robot base frame']);
tmpStruct = load(fname);
else
error ('genmfunjacobian:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
Q = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStructJacob0(CGen.rob,symname); % create header
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname),'funfilename',funfilename,'funname',[CGen.getrobfname,'_',symname],'vars',{Q},'output','J0','header',hStruct);
CGen.logmsg('\t%s\n',' done!');
%% Jacobian w.r.t. the robot end effector
symname = 'jacobe';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
CGen.logmsg([datestr(now),'\tGenerating Jacobian MEX-function with respect to the robot end-effector frame']);
tmpStruct = load(fname);
else
error ('genMFunJacobian:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
Q = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStructJacobe(CGen.rob,symname); % create header
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname),'funfilename',funfilename,'funname',[CGen.getrobfname,'_',symname],'vars',{Q},'output','Jn','header',hStruct);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents for each generated file
function hStruct = createHeaderStructJacob0(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C code for the Jacobian with respect to the base coordinate frame of the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the base frame. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['J0: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fkine,jacobe'};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructJacobe(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C code for the Jacobian with respect to the end-effector coordinate frame of the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the end-effector frame. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['Jn: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fkine,jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genfdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genfdyn.m
| 4,945 |
utf_8
|
d074c077f64223415710f3dee7669505
|
%CODEGENERATOR.GENFDYN Generate code for forward dynamics
%
% Iqdd = cGen.genfdyn() is a symbolic vector (1xN) of joint inertial
% reaction forces/torques.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [Iqdd] = genfdyn(CGen)
[q,qd] = CGen.rob.gencoords;
tau = CGen.rob.genforces;
nJoints = CGen.rob.n;
CGen.logmsg([datestr(now),'\tLoading required symbolic expressions\n']);
%% Inertia matrix
CGen.logmsg([datestr(now),'\tLoading inertia matrix row by row']);
I = sym(zeros(nJoints));
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.geninertia;
end
tmpstruct = load(fname);
I(kJoints,:)=tmpstruct.(symname);
end
CGen.logmsg('\t%s\n',' done!');
%% Matrix of centrifugal and Coriolis forces/torques matrix
CGen.logmsg([datestr(now),'\t\tCoriolis matrix by row']);
C = sym(zeros(nJoints));
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.gencoriolis;
end
tmpstruct = load(fname);
C(kJoints,:)=tmpstruct.(symname);
end
CGen.logmsg('\t%s\n',' done!');
%% Vector of gravitational load
CGen.logmsg([datestr(now),'\t\tvector of gravitational forces/torques']);
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.gengravload;
end
tmpstruct = load(fname);
G = tmpstruct.(symname);
CGen.logmsg('\t%s\n',' done!');
%% Joint friction
CGen.logmsg([datestr(now),'\t\tjoint friction vector']);
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if ~exist(fname,'file')
CGen.logmsg(['\n',datestr(now),'\t Symbolics not found, generating...\n']);
CGen.genfriction;
end
tmpstruct = load(fname);
F = tmpstruct.(symname);
CGen.logmsg('\t%s\n',' done!');
% Full inverse dynamics
CGen.logmsg([datestr(now),'\tGenerating symbolic inertial reaction forces/torques expression\n']);
Iqdd = tau.'-C*qd.' -G.' +F.';
Iqdd = Iqdd.';
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic inertial reaction forces/torques expression']);
CGen.savesym(Iqdd,'Iqdd','Iqdd.mat')
CGen.logmsg('\t%s\n',' done!');
end
%% M-Functions
if CGen.genmfun
CGen.genmfunfdyn;
end
%% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockfdyn;
end
%% C-Code
if CGen.genccode
CGen.genccodefdyn;
end
%% MEX
if CGen.genmex
CGen.genmexfdyn;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gencoriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/gencoriolis.m
| 3,271 |
utf_8
|
610b6561d71cb22797305e5e86f83607
|
%CODEGENERATOR.GENCORIOLIS Generate code for Coriolis force
%
% coriolis = cGen.gencoriolis() is a symbolic matrix (NxN) of centrifugal and Coriolis
% forces/torques.
%
% Notes::
% - The Coriolis matrix is stored row by row to avoid memory issues.
% The generated code recombines these rows to output the full matrix.
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ coriolis ] = gencoriolis( CGen )
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving robot Coriolis matrix']);
nJoints = CGen.rob.n;
[q, qd] = CGen.rob.gencoords;
coriolis = CGen.rob.coriolis(q,qd);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving rows of the Coriolis matrix']);
for kJoints = 1:nJoints
CGen.logmsg(' %i ',kJoints);
coriolisRow = coriolis(kJoints,:);
symName = ['coriolis_row_',num2str(kJoints)];
CGen.savesym(coriolisRow,symName,[symName,'.mat']);
end
CGen.logmsg('\t%s\n',' done!');
end
% M-Functions
if CGen.genmfun
CGen.genmfuncoriolis;
end
% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockcoriolis;
end
%% C-Code
if CGen.genccode
CGen.genccodecoriolis;
end
%% MEX
if CGen.genmex
CGen.genmexinertia;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodefdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodefdyn.m
| 8,471 |
utf_8
|
06687706e358e81992fc0772aef81413
|
%CODEGENERATOR.GENCCODEFDYN Generate C-code for forward dynamics
%
% cGen.genccodeinvdyn() generates a robot-specific C-code to compute the
% forward dynamics.
%
% Notes::
% - Is called by CodeGenerator.genfdyn if cGen has active flag genccode or
% genmex.
% - The .c and .h files are generated in the directory specified
% by the ccodepath property of the CodeGenerator object.
% - The resulting C-function is composed of previously generated C-functions
% for the inertia matrix, Coriolis matrix, vector of gravitational load and
% joint friction vector. This function recombines these components to
% compute the forward dynamics.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfdyn,CodeGenerator.genccodeinvdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [ ] = genccodefdyn( CGen )
checkexistanceofcfunctions(CGen);
[Q, QD] = CGen.rob.gencoords;
tau = CGen.rob.genforces;
nJoints = CGen.rob.n;
% Check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
symname = 'fdyn';
outputname = 'QDD';
funname = [CGen.getrobfname,'_accel'];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
CGen.logmsg([datestr(now),'\tGenerating forward dynamics C-code']);
% Convert symbolic expression into C-code
dummy = sym(zeros(nJoints,1));
[funstr hstring] = ccodefunctionstring(dummy,...
'funname',funname,...
'vars',{Q, QD, tau},'output',outputname,...
'flag',1);
% Create the function description header
hStruct = createHeaderStruct(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s{\n\n',funstr);
% Allocate memory
fprintf(fid,'\t%s\n','/* declare variables */');
fprintf(fid,'\t%s\n','int iCol;');
fprintf(fid,'\t%s\n',['double inertia[',num2str(nJoints),'][',num2str(nJoints),'] = {0};']);
fprintf(fid,'\t%s\n',['double invinertia[',num2str(nJoints),'][',num2str(nJoints),'] = {0};']);
fprintf(fid,'\t%s\n',['double coriolis[',num2str(nJoints),'][',num2str(nJoints),'] = {0};']);
fprintf(fid,'\t%s\n',['double gravload[',num2str(nJoints),'][1] = {0};']);
fprintf(fid,'\t%s\n',['double friction[',num2str(nJoints),'][1] = {0};']);
fprintf(fid,'\t%s\n',['double tmpTau[1][',num2str(nJoints),'] = {0};']);
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','/* call the computational routines */');
fprintf(fid,'\t%s\n',[CGen.getrobfname,'_','inertia(inertia, input1);']);
fprintf(fid,'\t%s\n',[CGen.getrobfname,'_','coriolis(coriolis, input1, input2);']);
fprintf(fid,'\t%s\n',[CGen.getrobfname,'_','gravload(gravload, input1);']);
fprintf(fid,'\t%s\n',[CGen.getrobfname,'_','friction(friction, input2);']);
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n',['gaussjordan(inertia, invinertia, ',num2str(nJoints),');']);
fprintf(fid,'\t%s\n','/* fill temporary vector */');
fprintf(fid,'\t%s\n',['matvecprod(tmpTau, coriolis, input2,',num2str(nJoints),',',num2str(nJoints),');']);
fprintf(fid,'\t%s\n',['for (iCol = 0; iCol < ',num2str(nJoints),'; iCol++){']);
fprintf(fid,'\t\t%s\n','tmpTau[0][iCol] = input3[iCol] - tmpTau[0][iCol] - gravload[iCol][0] + friction[iCol][0];');
fprintf(fid,'\t%s\n','}');
fprintf(fid,'\t%s\n','/* compute acceleration */');
fprintf(fid,'\t%s\n',['matvecprod(QDD, invinertia, tmpTau,',num2str(nJoints),',',num2str(nJoints),');']);
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n%s\n%s\n%s\n%s\n%s\n\n',...
'#include "matvecprod.h"',...
'#include "gaussjordan.h"',...
['#include "',CGen.getrobfname,'_inertia.h"'],...
['#include "',CGen.getrobfname,'_coriolis.h"'],...
['#include "',CGen.getrobfname,'_gravload.h"'],...
['#include "',CGen.getrobfname,'_gravload.h"'],...
['#include "',CGen.getrobfname,'_friction.h"']);
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function [] = checkexistanceofcfunctions(CGen)
if ~(exist(fullfile(CGen.ccodepath,'src','inertia.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','inertia.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Inertia C-code not found or not complete! Generating:');
CGen.genccodeinertia;
end
if ~(exist(fullfile(CGen.ccodepath,'src','coriolis.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'coriolis','inertia.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Coriolis C-code not found or not complete! Generating:');
CGen.genccodecoriolis;
end
if ~(exist(fullfile(CGen.ccodepath,'src','gravload.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','gravload.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Gravload C-code not found or not complete! Generating:');
CGen.genccodegravload;
end
if ~(exist(fullfile(CGen.ccodepath,'src','friction.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','friction.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Friction C-code not found or not complete! Generating:');
CGen.genccodefriction;
end
if ~(exist(fullfile(CGen.ccodepath,'src','matvecprod.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','matvecprod.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Matrix-Vector product C-code not found or not complete! Generating:');
CGen.genmatvecprodc;
end
if ~(exist(fullfile(CGen.ccodepath,'src','gaussjordan.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','gaussjordan.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Gauss-Jordan matrix inversion C-code not found or not complete! Generating:');
CGen.gengaussjordanc;
end
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C-implementation of the forward dynamics for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint angles and velocities',...
'this function computes the joint space accelerations effected by the generalized forces. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities'],...
['input3: [',int2str(rob.n),'x1] vector of generalized forces.']};
hStruct.outputs = {['QDD: ',int2str(rob.n),'-element output vector of generalized accelerations.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'invdyn'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexgravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexgravload.m
| 3,809 |
utf_8
|
95249b29ad89b9de4377217b7f4044ef
|
%CODEGENERATOR.GENMEXGRAVLOAD Generate C-MEX-function for gravitational load
%
% cGen.genmexgravload() generates a robot-specific MEX-function to compute
% gravitation load forces and torques.
%
% Notes::
% - Is called by CodeGenerator.gengravload if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexgravload(CGen)
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating gravload MEX-function: ']);
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmexgravload:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
Q = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStructGravity(CGen.rob,symname);
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname), 'funfilename',funfilename,'funname',[CGen.getrobfname,'_',symname],'vars',{Q},'output','G','header',hStruct)
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStructGravity(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['Computation of the configuration dependent vector of gravitational load forces/torques for ',rob.name];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
'configuration dependent vector of gravitational load forces/torques. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['G: [',int2str(rob.n),'x1] output vector of gravitational load forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'inertia'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodefriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodefriction.m
| 4,427 |
utf_8
|
2eb6f6400cf827015abfcbe17a999fb1
|
%CODEGENERATOR.GENCCODEFRICTION Generate C-code for the joint friction
%
% cGen.genccodefriction() generates a robot-specific C-function to compute
% vector of friction torques/forces.
%
% Notes::
% - Is called by CodeGenerator.genfriction if cGen has active flag genccode or
% genmex
% - The generated .c and .h files are wirtten to the directory specified in
% the ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfriction, CodeGenerator.genmexfriction.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodefriction(CGen)
%% Check for existance symbolic expressions
% Load symbolics
symname = 'friction';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfriction:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
%% Prerequesites
CGen.logmsg([datestr(now),'\tGenerating C-code for the vector of frictional torques/forces' ]);
% Check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
[~,QD] = CGen.rob.gencoords;
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{QD},'output','F');
% Create the function description header
hStruct = createHeaderStruct(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Joint friction for the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of generalized joint velocities the function'],...
'computes the friction forces/torques. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized velocities.']};
hStruct.outputs = {['F: [',int2str(rob.n),'x1] output vector of joint friction forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'gravload'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
logmsg.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/logmsg.m
| 2,036 |
utf_8
|
2436af4090a0f6d9e9844e979169f194
|
%CODEGENERATOR.LOGMSG Print CodeGenerator logs.
%
% count = CGen.logmsg( FORMAT, A, ...) is the number of characters written to the CGen.logfile.
% For the additional arguments see fprintf.
%
% Note::
% Matlab ships with a function for writing formatted strings into a text
% file or to the console (fprintf). The function works with single
% target identifiers (file, console, string). This function uses the
% same syntax as for the fprintf function to output log messages to
% either the Matlab console, a log file or both.
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also multidfprintf,fprintf,sprintf.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [cnt] = logmsg(CGen, varargin)
% Output to logfile?
if ~isempty(CGen.logfile)
logfid = fopen(CGen.logfile,'a+');
else
logfid = [];
end
% write message to multiple destinations
cnt = multidfprintf([CGen.verbose, logfid],varargin{:});
% Logfile to close?
if ~isempty(CGen.logfile)
logfid = fclose(logfid);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfuncoriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfuncoriolis.m
| 7,000 |
utf_8
|
b7c51342bc78385a5e666aa6d2c05fca
|
%CODEGENERATOR.GENMFUNCORIOLIS Generate M-functions for Coriolis matrix
%
% cGen.genmfuncoriolis() generates a robot-specific M-function to compute
% the Coriolis matrix.
%
% Notes::
% - Is called by CodeGenerator.gencoriolis if cGen has active flag genmfun
% - The Coriolis matrix is stored row by row to avoid memory issues.
% - The generated M-function recombines the individual M-functions for each row.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis, CodeGenerator.geninertia.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = genmfuncoriolis( CGen )
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
%%
CGen.logmsg([datestr(now),'\tGenerating m-function for the Coriolis matrix row' ]);
[q, qd] = CGen.rob.gencoords;
nJoints = CGen.rob.n;
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['coriolis_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuncoriolis:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {'Crow'},...
'vars', {'rob',q,qd});
hStruct = createHeaderStructRow(CGen.rob,kJoints,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
end
CGen.logmsg('\t%s\n',' done!');
CGen.logmsg([datestr(now),'\tGenerating full Coriolis matrix m-function: ']);
funfilename = fullfile(CGen.robjpath,'coriolis.m');
hStruct = createHeaderStructFull(CGen.rob,funfilename);
fid = fopen(funfilename,'w+');
fprintf(fid, '%s\n', ['function C = coriolis(rob,q,qd)']); % Function definition
fprintf(fid, '%s\n',constructheaderstring(CGen,hStruct)); % Header
fprintf(fid, '%s \n', 'C = zeros(length(q));'); % Code
for iJoints = 1:nJoints
funCall = ['C(',num2str(iJoints),',:) = ','rob.coriolis_row_',num2str(iJoints),'(q,qd);'];
fprintf(fid, '%s \n', funCall);
end
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Computation of the robot specific Coriolis matrix row for joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.calls = {['Crow = ',hStruct.funName,'(rob,q,qd)'],...
['Crow = rob.',hStruct.funName,'(q,qd)']};
hStruct.detailedDescription = {'Given a full set of joint variables and their first order temporal derivatives this function computes the',...
['Coriolis matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'.']};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates';
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
'Angles have to be given in radians!'};
hStruct.outputs = {['Crow: [1x',int2str(rob.n),'] row of the robot Coriolis matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function.',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFull(rob,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Coriolis matrix for the ',rob.name,' arm'];
hStruct.calls = {['Crow = ',hStruct.funName,'(rob,q,qd)'],...
['Crow = rob.',hStruct.funName,'(q,qd)']};
hStruct.detailedDescription = {'Given a full set of joint variables and their first order temporal derivatives the function computes the',...
'Coriolis matrix of the robot.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates';
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
'Angles have to be given in radians!'};
hStruct.outputs = {['C: [',int2str(rob.n),'x',int2str(rob.n),'] Coriolis matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'inertia'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfuninertia.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfuninertia.m
| 6,637 |
utf_8
|
a4f2e4e44a8a5fd374e40f7262c76406
|
%CODEGENERATION.GENMFUNINERTIA Generate M-function for robot inertia matrix
%
% cGen.genmfuninertia() generates a robot-specific M-function to compute
% robot inertia matrix.
%
% Notes::
% - Is called by CodeGenerator.geninertia if cGen has active flag genmfun
% - The inertia matrix is stored row by row to avoid memory issues.
% - The generated M-function recombines the individual M-functions for each row.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gencoriolis.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmfuninertia(CGen)
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
%%
CGen.logmsg([datestr(now),'\tGenerating m-function for the robot inertia matrix row' ]);
q = CGen.rob.gencoords;
nJoints = CGen.rob.n;
for kJoints = 1:nJoints
CGen.logmsg(' %s ',num2str(kJoints));
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfuninertia:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {'Irow'},...
'vars', {'rob',[q]});
hStruct = createHeaderStructRow(CGen.rob,kJoints,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
end
CGen.logmsg('\t%s\n',' done!');
CGen.logmsg([datestr(now),'\tGenerating full inertia matrix m-function']);
funfilename = fullfile(CGen.robjpath,'inertia.m');
hStruct = createHeaderStructFullInertia(CGen.rob,funfilename);
fid = fopen(funfilename,'w+');
fprintf(fid, '%s\n', ['function I = inertia(rob,q)']); % Function definition
fprintf(fid, '%s\n',constructheaderstring(CGen,hStruct)); % Header
fprintf(fid, '%s \n', 'I = zeros(length(q));'); % Code
for iJoints = 1:nJoints
funcCall = ['I(',num2str(iJoints),',:) = ','rob.inertia_row_',num2str(iJoints),'(q);'];
fprintf(fid, '%s \n', funcCall);
end
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function hStruct = createHeaderStructRow(rob,curJointIdx,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Computation of the robot specific inertia matrix row for corresponding to joint ', num2str(curJointIdx), ' of ',num2str(rob.n),'.'];
hStruct.calls = {['Irow = ',hStruct.funName,'(rob,q)'],...
['Irow = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
['inertia matrix row number ', num2str(curJointIdx),' of ',num2str(rob.n),' for ',rob.name,'.']};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
'Angles have to be given in radians!'};
hStruct.outputs = {['Irow: [1x',int2str(rob.n),'] row of the robot inertia matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'coriolis'};
end
function hStruct = createHeaderStructFullInertia(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Inertia matrix for the ',rob.name,' arm.'];
hStruct.calls = {['I = ',hStruct.funName,'(rob,q)'],...
['I = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {'Given a full set of joint variables the function computes the',...
'inertia Matrix of the robot.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
'Angles have to be given in radians!'};
hStruct.outputs = {['I: [',int2str(rob.n),'x',int2str(rob.n),'] inertia matrix']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'coriolis'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genfriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genfriction.m
| 2,873 |
utf_8
|
249a2f1d069ecc943808440dca0baf26
|
%CODEGENERATOR.GENFRICTION Generate code for joint friction
%
% F = cGen.genfriction() is the symbolic vector (1xN) of joint friction
% forces.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genfdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ F ] = genfriction( CGen )
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving joint friction model']);
[~,qd] = CGen.rob.gencoords;
F = CGen.rob.friction(qd);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic friction expression']);
CGen.savesym(F,'friction','friction.mat')
CGen.logmsg('\t%s\n',' done!');
end
%% M-Functions
if CGen.genmfun
CGen.genmfunfriction;
end
%% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockfriction;
end
%% C-Code
if CGen.genccode
CGen.genccodefriction;
end
%% MEX
if CGen.genmex
CGen.genmexfriction;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodejacobian.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodejacobian.m
| 7,361 |
utf_8
|
fae915fcd1ebfbab22c51a50cf6ddd2a
|
%CODEGENERATOR.GENCCODEJACOBIAN Generate C-functions for robot jacobians
%
% cGen.genccodejacobian() generates a robot-specific C-function to compute
% the jacobians with respect to the robot base as well as the end effector.
%
% Notes::
% - Is called by CodeGenerator.genjacobian if cGen has active flag genccode or
% genmex.
% - The generated .c and .h files are generated in the directory specified
% by the ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genccodefkine, CodeGenerator.genjacobian.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodejacobian(CGen)
%% Check for existance symbolic expressions
% Load symbolics
symname = 'jacob0';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
%% Jacobian w.r.t. the robot base
CGen.logmsg([datestr(now),'\tGenerating jacobian C-code with respect to the robot base frame']);
% Prerequesites
% check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
Q = CGen.rob.gencoords;
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{Q},'output','J0');
% Create the function description header
hStruct = createHeaderStructJacob0(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([symname,'_h'])],...
['#define ', upper([symname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function signature
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([symname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
%% Jacobian w.r.t. the robot end effector
% Load symbolics
symname = 'jacobe';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
CGen.logmsg([datestr(now),'\tGenerating jacobian C-code with respect to the robot end-effector frame']);
tmpStruct = load(fname);
else
error ('genMFunJacobian:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{Q},'output','Jn');
% Create the function description header
hStruct = createHeaderStructJacobe(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function signature
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents for each generated file
function hStruct = createHeaderStructJacob0(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C code for the Jacobian with respect to the base coordinate frame of the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the base frame. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['J0: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fkine,jacobe'};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructJacobe(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C code for the Jacobian with respect to the end-effector coordinate frame of the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the robot jacobian with respect to the end-effector frame. Angles have to be given in radians!'};
hStruct.inputs = {['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['Jn: [6x',num2str(rob.n),'] Jacobian matrix']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fkine,jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfuninvdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfuninvdyn.m
| 5,357 |
utf_8
|
33b9d3ed4432a00d0db5f7a3b96e2d0f
|
%CODEGENERATOR.GENMFUNINVDYN Generate M-functions for inverse dynamics
%
% cGen.genmfuninvdyn() generates a robot-specific M-function to compute
% inverse dynamics.
%
% Notes::
% - Is called by CodeGenerator.geninvdyn if cGen has active flag genmfun
% - The generated M-function is composed of previously generated M-functions
% for the inertia matrix, coriolis matrix, vector of gravitational load and
% joint friction vector. This function recombines these components to
% compute the inverse dynamics.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = genmfuninvdyn( CGen )
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
checkexistanceofmfunctions(CGen);
%%
CGen.logmsg([datestr(now),'\tGenerating inverse dynamics m-function']);
funfilename = fullfile(CGen.robjpath,'invdyn.m');
hStruct = createHeaderStruct(CGen.rob,funfilename);
fid = fopen(funfilename,'w+');
fprintf(fid, '%s\n', ['function tau = invdyn(rob,q,qd,qdd)']); % Function definition
fprintf(fid, '%s\n',constructheaderstring(CGen,hStruct)); % Header
fprintf(fid, '%s \n', 'tau = zeros(length(q),1);'); % Code
funcCall = ['tau = rob.inertia(q)*qdd(:) + ',...
'rob.coriolis(q,qd)*qd(:) + ',...
'rob.gravload(q).'' - ', ...
'rob.friction(qd).'';'];
fprintf(fid, '%s \n', funcCall);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function [] = checkexistanceofmfunctions(CGen)
if ~(exist(fullfile(CGen.robjpath,'inertia.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Inertia m-function not found! Generating:');
CGen.genmfuninertia;
end
if ~(exist(fullfile(CGen.robjpath,'coriolis.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Coriolis m-function not found! Generating:');
CGen.genmfuncoriolis;
end
if ~(exist(fullfile(CGen.robjpath,'gravload.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Gravload m-function not found! Generating:');
CGen.genmfungravload;
end
if ~(exist(fullfile(CGen.robjpath,'friction.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Friction m-function not found! Generating:');
CGen.genmfunfriction;
end
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Inverse dynamics for the',rob.name,' arm.'];
hStruct.calls = {['tau = ',hStruct.funName,'(rob,q,qd,qdd)'],...
['tau = rob.',hStruct.funName,'(q,qd,qdd)']};
hStruct.detailedDescription = {'Given a full set of joint variables and their first and second order',...
'temporal derivatives this function computes the joint space',...
'torques needed to perform the particular motion.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
['qdd: ',int2str(rob.n),'-element vector of generalized'],...
' accelerations',...
'Angles have to be given in radians!'};
hStruct.outputs = {['tau: [',int2str(rob.n),'x1] vector of joint forces/torques.']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'fdyn'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodeinvdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodeinvdyn.m
| 8,084 |
utf_8
|
63bb90993fadc9d1e626689792ee26fc
|
%CODEGENERATOR.GENCCODEINVDYN Generate C-code for inverse dynamics
%
% cGen.genccodeinvdyn() generates a robot-specific C-code to compute the
% inverse dynamics.
%
% Notes::
% - Is called by CodeGenerator.geninvdyn if cGen has active flag genccode or
% genmex.
% - The .c and .h files are generated in the directory specified
% by the ccodepath property of the CodeGenerator object.
% - The resulting C-function is composed of previously generated C-functions
% for the inertia matrix, coriolis matrix, vector of gravitational load and
% joint friction vector. This function recombines these components to
% compute the inverse dynamics.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genccodefdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [ ] = genccodeinvdyn( CGen )
checkexistanceofcfunctions(CGen);
[Q, QD, QDD] = CGen.rob.gencoords;
nJoints = CGen.rob.n;
% Check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
symname = 'invdyn';
outputname = 'TAU';
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
%%
CGen.logmsg([datestr(now),'\tGenerating inverse dynamics C-code']);
% Convert symbolic expression into C-code
dummy = sym(zeros(nJoints,1));
[funstr hstring] = ccodefunctionstring(dummy,...
'funname',funname,...
'vars',{Q, QD, QDD},'output',outputname,...
'flag',1);
% Create the function description header
hStruct = createHeaderStruct(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s{\n\n',funstr);
% Allocate memory
fprintf(fid,'%s\n','/* declare variables */');
for iJoints = 1:nJoints
fprintf(fid,'%s\n',['double inertia_row',num2str(iJoints),'[',num2str(nJoints),'][1];']);
end
for iJoints = 1:nJoints
fprintf(fid,'%s\n',['double coriolis_row',num2str(iJoints),'[',num2str(nJoints),'][1];']);
end
fprintf(fid,'%s\n',['double gravload[',num2str(nJoints),'][1];']);
fprintf(fid,'%s\n',['double friction[',num2str(nJoints),'][1];']);
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'%s\n','/* call the computational routines */');
fprintf(fid,'%s\n',[CGen.getrobfname,'_','gravload(gravload, input1);']);
fprintf(fid,'%s\n',[CGen.getrobfname,'_','friction(friction, input2);']);
fprintf(fid,'%s\n','/* rowwise routines */');
for iJoints = 1:nJoints
fprintf(fid,'%s\n',[CGen.getrobfname,'_','inertia_row_',num2str(iJoints),'(inertia_row',num2str(iJoints),', input1);']);
end
for iJoints = 1:nJoints
fprintf(fid,'%s\n',[CGen.getrobfname,'_','coriolis_row_',num2str(iJoints),'(coriolis_row',num2str(iJoints),', input1, input2);']);
end
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'%s\n','/* fill output vector */');
for iJoints = 1:nJoints
fprintf(fid,'%s\n',[outputname,'[0][',num2str(iJoints-1),'] = dotprod(inertia_row',num2str(iJoints),', input3, ',num2str(nJoints),') /* inertia */']);
fprintf(fid,'\t%s\n',[' + dotprod(coriolis_row',num2str(iJoints),', input2, ',num2str(nJoints),') /* coriolis */']);
fprintf(fid,'\t%s\n',[' + gravload[',num2str(iJoints-1),'][0]']);
fprintf(fid,'\t%s\n',[' - friction[',num2str(iJoints-1),'][0];']);
end
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n%s\n%s\n%s\n%s\n\n',...
'#include "dotprod.h"',...
['#include "',CGen.getrobfname,'_inertia.h"'],...
['#include "',CGen.getrobfname,'_coriolis.h"'],...
['#include "',CGen.getrobfname,'_gravload.h"'],...
['#include "',CGen.getrobfname,'_friction.h"']);
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function [] = checkexistanceofcfunctions(CGen)
if ~(exist(fullfile(CGen.ccodepath,'src','inertia.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','inertia.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Inertia C-code not found or not complete! Generating:');
CGen.genccodeinertia;
end
if ~(exist(fullfile(CGen.ccodepath,'src','coriolis.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'coriolis','inertia.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Coriolis C-code not found or not complete! Generating:');
CGen.genccodecoriolis;
end
if ~(exist(fullfile(CGen.ccodepath,'src','gravload.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','gravload.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Gravload C-code not found or not complete! Generating:');
CGen.genccodegravload;
end
if ~(exist(fullfile(CGen.ccodepath,'src','friction.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','friction.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Friction C-code not found or not complete! Generating:');
CGen.genccodefriction;
end
if ~(exist(fullfile(CGen.ccodepath,'src','dotprod.c'),'file') == 2) || ~(exist(fullfile(CGen.ccodepath,'include','dotprod.h'),'file') == 2)
CGen.logmsg('\t\t%s\n','Dot product C-code not found or not complete! Generating:');
CGen.gendotprodc;
end
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C-implementation of the inverse dynamics for the ',rob.name,' arm.'];
hStruct.detailedDescription = {'Given a full set of joint variables and their first and second order',...
'temporal derivatives this function computes the joint space',...
'torques needed to perform the particular motion. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates'],...
['input2: ',int2str(rob.n),'-element vector of generalized velocities,'],...
['input3: ',int2str(rob.n),'-element vector of generalized accelerations.']};
hStruct.outputs = {['TAU: [',int2str(rob.n),'x1] vector of joint forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'fdyn'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfunfkine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfunfkine.m
| 6,536 |
utf_8
|
0bc4348782a4ebdd012388967a6f647e
|
%CODEGENERATOR.GENMFUNFKINE Generate M-function for forward kinematics
%
% cGen.genmfunfkine() generates a robot-specific M-function to compute
% forward kinematics.
%
% Notes::
% - Is called by CodeGenerator.genfkine if cGen has active flag genmfun
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genjacobian.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmfunfkine(CGen)
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating forward kinematics m-function up to the end-effector frame: ']);
symname = 'fkine';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname).T,'file',funfilename,... % generate function m-file
'outputs', {symname},...
'vars', {'rob',[q]});
hStruct = createHeaderStructFkine(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
%% Individual joint forward kinematics
CGen.logmsg([datestr(now),'\tGenerating forward kinematics m-function up to joint: ']);
for iJoints=1:CGen.rob.n
CGen.logmsg(' %i ',iJoints);
symname = ['T0_',num2str(iJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
tmpStruct = struct;
tmpStruct = load(fname);
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
matlabFunction(tmpStruct.(symname).T,'file',funfilename,... % generate function m-file
'outputs', {symname},...
'vars', {'rob',[q]});
hStruct = createHeaderStruct(CGen.rob,iJoints,symname); % replace autogenerated function header
CGen.replaceheader(hStruct,funfilename);
end
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,curBody,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Forward kinematics for the ',rob.name,' arm up to frame ',int2str(curBody),' of ',int2str(rob.n),'.'];
hStruct.calls = {['T = ',hStruct.funName,'(rob,q)'],...
['T = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {['Given a set of joint variables up to joint number ',int2str(curBody),' the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = {['q: ',int2str(curBody),'-element vector of generalized coordinates.'],...
'Angles have to be given in radians!'};
hStruct.outputs = {['T: [4x4] Homogenous transformation matrix relating the pose of joint ',int2str(curBody),' of ',int2str(rob.n)],...
' for the given joint values to the base frame.'};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {rob.name};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructFkine(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Forward kinematics solution including tool transformation for the ',rob.name,' arm.'];
hStruct.calls = {['T = ',hStruct.funName,'(rob,q)'],...
['T = rob.',hStruct.funName,'(q)']};
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
'Angles have to be given in radians!'};
hStruct.outputs = {['T: [4x4] Homogenous transformation matrix relating the pose of the tool'],...
' for the given joint values to the base frame.'};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodefkine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodefkine.m
| 7,649 |
utf_8
|
a418fbd3ca20f226e0b1b8bf9ad90e25
|
%CODEGENERATOR.GENCCODEFKINE Generate C-code for the forward kinematics
%
% cGen.genccodefkine() generates a robot-specific C-function to compute
% forward kinematics.
%
% Notes::
% - Is called by CodeGenerator.genfkine if cGen has active flag genccode or
% genmex
% - The generated .c and .h files are wirtten to the directory specified in
% the ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine, CodeGenerator.genmexfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodefkine(CGen)
%% Check for existance symbolic expressions
% Load symbolics
symname = 'fkine';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating forward kinematics c-code up to the end-effector frame: ']);
%% Prerequesites
% check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
Q = CGen.rob.gencoords;
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname).T,...
'funname',funname,...
'vars',{Q},'output','T');
% Create the function description header
hStruct = createHeaderStructFkine(CGen.rob,symname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
%% Individual joint forward kinematics
CGen.logmsg([datestr(now),'\tGenerating forward kinematics m-function up to joint: ']);
for iJoints=1:CGen.rob.n
CGen.logmsg(' %i ',iJoints);
% Load symbolics
symname = ['T0_',num2str(iJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
tmpStruct = struct;
tmpStruct = load(fname);
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
Q = CGen.rob.gencoords;
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname).T,...
'funname',funname,...
'vars',{Q},'output','T');
% Create the function description header
hStruct = createHeaderStruct(CGen.rob,iJoints,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
end
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,curBody,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C version of the forward kinematics for the ',rob.name,' arm up to frame ',int2str(curBody),' of ',int2str(rob.n),'.'];
hStruct.detailedDescription = {['Given a set of joint variables up to joint number ',int2str(curBody),' the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = { 'input1 Vector of generalized coordinates. Angles have to be given in radians!'};
hStruct.outputs = {'T [4x4] Homogenous transformation matrix relating the pose of the tool for the given joint values to the base frame.'};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!<BR>',...
'Code generator written by:<BR>',...
'Joern Malzahn ([email protected])<BR>'};
hStruct.seeAlso = {rob.name};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructFkine(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['C version of the forward kinematics solution including tool transformation for the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = { 'input1 Vector of generalized coordinates. Angles have to be given in radians!'};
hStruct.outputs = {'T [4x4] Homogenous transformation matrix relating the pose of the tool for the given joint values to the base frame.'};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!<BR>',...
'Code generator written by:<BR>',...
'Joern Malzahn ([email protected])<BR>'};
hStruct.seeAlso = {'jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockinertia.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockinertia.m
| 7,916 |
utf_8
|
5a887f4106ba9ad23136714e42238dfb
|
%CODEGENERATOR.GENSLBLOCKINERTIA Generate Simulink block for inertia matrix
%
% cGen.genslbgenslblockinertia() generates a robot-specific Simulink block to compute
% robot inertia matrix.
%
% Notes::
% - Is called by CodeGenerator.geninertia if cGen has active flag genslblock
% - The Inertia matrix is stored row by row to avoid memory issues.
% - The Simulink block recombines the the individual blocks for each row.
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninertia.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function genslblockinertia(CGen)
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
q = CGen.rob.gencoords;
%% Generate Inertia Block
CGen.logmsg([datestr(now),'\tGenerating Simulink Block for the robot inertia matrix\n']);
nJoints = CGen.rob.n;
CGen.logmsg([datestr(now),'\t\t... enclosing subsystem ']);
symname = 'inertia';
InertiaBlock = [CGen.slib,'/',symname];
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated inertia matrix block
delete_block(InertiaBlock);
save_system;
end
% Subsystem in which individual rows are concatenated
add_block('built-in/SubSystem',InertiaBlock); % Add new inertia matrix block
add_block('simulink/Math Operations/Matrix Concatenate'...
, [InertiaBlock,'/inertia']...
, 'NumInputs',num2str(nJoints)...
, 'ConcatenateDimension','1');
add_block('simulink/Sinks/Out1',[InertiaBlock,'/out']);
add_block('simulink/Sources/In1',[InertiaBlock,'/q']);
add_line(InertiaBlock,'inertia/1','out/1');
CGen.logmsg('\t%s\n',' done!');
for kJoints = 1:nJoints
CGen.logmsg([datestr(now),'\t\t... Embedded Matlab Function Block for joint ',num2str(kJoints),': ']);
% Generate Embedded Matlab Function block for each row
symname = ['inertia_row_',num2str(kJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genslblockinertia:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [InertiaBlock,'/',symname];
if doesblockexist(CGen.slib,symname)
delete_block(blockaddress);
save_system;
end
CGen.logmsg('%s',' block creation');
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q});
% connect output
CGen.logmsg('%s',', output wiring');
if ( verLessThan('matlab','7.11.0.584') ) && ( isequal(tmpStruct.(symname),zeros(1,nJoints)) )
% There is a bug in earlier Matlab versions. If the symbolic
% vector is a zero vector, then the Simulink Embedded Matlab
% Function block outputs a scalar zero. We need to concatenate
% a row vector of zeros here, which we have to construct on our
% own.
add_block('simulink/Math Operations/Matrix Concatenate'... % Use a matrix concatenation block ...
, [InertiaBlock,'/DimCorrection',num2str(kJoints)]... % ... named with the current row number ...
, 'NumInputs',num2str(nJoints),'ConcatenateDimension','2'); % ... intended to concatenate zero values for each joint ...
% ... columnwise. This will circumvent the bug.
for iJoints = 1:nJoints % Connect signal lines from the created block (which outputs
add_line(InertiaBlock... % a scalar zero in this case) with the bugfix block.
, [symname,'/1']...
, ['DimCorrection',num2str(kJoints),'/', num2str(iJoints)]);
end
add_line(InertiaBlock,['DimCorrection',num2str(kJoints)... % Connect the fixed row with other rows.
, '/1'],['inertia/', num2str(kJoints)]);
else
add_line(InertiaBlock,[symname,'/1']... % In case that no bug occurs, we can just connect the rows.
, ['inertia/', num2str(kJoints)]);
end
% Connect inputs
CGen.logmsg('%s',', input wiring');
add_line(InertiaBlock,'q/1',[symname,'/1']);
CGen.logmsg('\t%s\n','row complete!');
end
addterms(InertiaBlock); % Add terminators where needed
distributeblocks(InertiaBlock);
CGen.logmsg([datestr(now),'\tInertia matrix block complete\n']);
%% Built inverse Inertia matrix block
CGen.logmsg([datestr(now),'\tGenerating Simulink Block for the inverse robot inertia matrix\n']);
CGen.logmsg([datestr(now),'\t\t... enclosing subsystem ']);
% block address
symname = 'invinertia';
invInertiaBlock = [CGen.slib,'/',symname];
% remove any existing blocks
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(invInertiaBlock);
save_system;
end
add_block('built-in/SubSystem',invInertiaBlock);
CGen.logmsg('\t%s\n',' done!');
% matrix inversion
CGen.logmsg([datestr(now),'\t\t... matrix inversion block ']);
add_block('simulink/Math Operations/Product',[invInertiaBlock,'/inverse']); % Use a product block...
set_param([invInertiaBlock,'/inverse'],'Inputs','/'); % ... with single input '/'...
set_param([invInertiaBlock,'/inverse'],'Multiplication','Matrix(*)'); % ... and matrix multiplication
CGen.logmsg('\t%s\n',' done!');
% wire the input and output
CGen.logmsg([datestr(now),'\t\t... input and output ']);
add_block(InertiaBlock,[invInertiaBlock,'/inertiaMatrix']);
add_block('simulink/Sources/In1',[invInertiaBlock,'/q']);
add_block('simulink/Sinks/Out1',[invInertiaBlock,'/out']);
% wire the blocks among each other
CGen.logmsg('and internal wiring');
add_line(invInertiaBlock,'q/1','inertiaMatrix/1');
add_line(invInertiaBlock,'inertiaMatrix/1','inverse/1');
add_line(invInertiaBlock,'inverse/1','out/1');
CGen.logmsg('\t%s\n',' done!');
% add terminators where necessary
addterms(invInertiaBlock);
distributeblocks(invInertiaBlock);
CGen.logmsg([datestr(now),'\tInverse inertia matrix block complete.\n']);
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
geninertia.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/geninertia.m
| 3,230 |
utf_8
|
51f1f4564b3b247968023865edd6e009
|
%CODEGENERATOR.GENINERTIA Generate code for inertia matrix
%
% I = cGen.geninertia() is the symbolic robot inertia matrix (NxN).
%
% Notes::
% - The inertia matrix is stored row by row to avoid memory issues.
% The generated code recombines these rows to output the full matrix.
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genfdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [inertia] = geninertia(CGen)
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving robot inertia matrix']);
nJoints = CGen.rob.n;
q = CGen.rob.gencoords;
tmpRob = CGen.rob.nofriction;
inertia = tmpRob.inertia(q);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving rows of the inertia matrix']);
for kJoints = 1:nJoints
CGen.logmsg(' %i ',kJoints);
inertiaRow = inertia(kJoints,:);
symName = ['inertia_row_',num2str(kJoints)];
CGen.savesym(inertiaRow,symName,[symName,'.mat']);
end
CGen.logmsg('\t%s\n',' done!');
end
% M-Functions
if CGen.genmfun
CGen.genmfuninertia;
end
% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockinertia;
end
%% C-Code
if CGen.genccode
CGen.genccodeinertia;
end
%% MEX
if CGen.genmex
CGen.genmexinertia;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genccodegravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genccodegravload.m
| 4,591 |
utf_8
|
acf3c492e810b6f39a8316024060f23c
|
%CODEGENERATOR.GENCCODEGRAVLOAD Generate C-code for the vector of
%gravitational load torques/forces
%
% cGen.genccodegravload() generates a robot-specific C-function to compute
% vector of gravitational load torques/forces.
%
% Notes::
% - Is called by CodeGenerator.gengravload if cGen has active flag genccode or
% genmex
% - The generated .c and .h files are wirtten to the directory specified in
% the ccodepath property of the CodeGenerator object.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.gengravload, CodeGenerator.genmexgravload.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genccodegravload(CGen)
%% Check for existance symbolic expressions
% Load symbolics
symname = 'gravload';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfungravload:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
%% Prerequesites
CGen.logmsg([datestr(now),'\tGenerating C-code for the vector of gravitational load torques/forces' ]);
% check for existance of C-code directories
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
funname = [CGen.getrobfname,'_',symname];
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
Q = CGen.rob.gencoords;
% Convert symbolic expression into C-code
[funstr hstring] = ccodefunctionstring(tmpStruct.(symname),...
'funname',funname,...
'vars',{Q},'output','G');
% Create the function description header
hStruct = createHeaderStructGravity(CGen.rob,funname); % create header
hStruct.calls = hstring;
hFString = CGen.constructheaderstringc(hStruct);
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n\n',funstr);
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Includes
fprintf(fid,'%s\n\n',...
'#include "math.h"');
% Function prototype
fprintf(fid,'%s\n\n',hstring);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStructGravity(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Computation of the configuration dependent vector of gravitational load forces/torques for ',rob.name];
hStruct.detailedDescription = {'Given a full set of joint variables this function computes the',...
'configuration dependent vector of gravitational load forces/torques. Angles have to be given in radians!'};
hStruct.inputs = { ['input1: ',int2str(rob.n),'-element vector of generalized coordinates.']};
hStruct.outputs = {['G: [',int2str(rob.n),'x1] output vector of gravitational load forces/torques.']};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'inertia'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockjacobian.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockjacobian.m
| 3,835 |
utf_8
|
bc03280451d3efff3953c11d5517b9ac
|
%CODEGENERATOR.GENSLBLOCKJACOBIAN Generate Simulink block for robot Jacobians
%
% cGen.genslblockjacobian() generates a robot-specific Simulink block to compute
% robot Jacobians (world and tool frame).
%
% Notes::
% - Is called by CodeGenerator.genjacobian if cGen has active flag genslblock
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genjacobian.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function genslblockjacobian(CGen)
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
q = CGen.rob.gencoords;
%% Jacobian0
CGen.logmsg([datestr(now),'\tGenerating jacobian Embedded Matlab Function Block with respect to the robot base frame']);
% [datestr(now),'\tGenerating jacobian Embedded Matlab Function Block with respect to the end-effector frame']);
symname = 'jacob0';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genSLBlockFkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(blockaddress);
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q});
CGen.logmsg('\t%s\n',' done!');
%% Jacobe
CGen.logmsg([datestr(now),'\tGenerating jacobian Embedded Matlab Function Block with respect to the end-effector frame']);
symname = 'jacobe';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genSLBlockFkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(blockaddress);
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname),'vars',{q});
CGen.logmsg('\t%s\n',' done!');
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genslblockfkine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genslblockfkine.m
| 3,829 |
utf_8
|
5b4703a7c085b86a61340e8f257bb502
|
%CODEGENERATOR.GENSLBLOCKFKINE Generate Simulink block for forward kinematics
%
% cGen.genslblockfkine() generates a robot-specific Simulink block to compute
% forward kinematics.
%
% Notes::
% - Is called by CodeGenerator.genfkine if cGen has active flag genslblock.
% - The Simulink blocks are generated and stored in a robot specific block
% library cGen.slib in the directory cGen.basepath.
% - Blocks are created for intermediate transforms T0, T1 etc. as well.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function genslblockfkine(CGen)
%% Open or create block library
bdclose('all') % avoid problems with previously loaded libraries
load_system('simulink');
if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists
CGen.createnewblocklibrary;
end
open_system(CGen.slibpath);
set_param(CGen.slib,'lock','off');
q = CGen.rob.gencoords;
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating forward kinematics Simulink block up to the end-effector frame']);
symname = 'fkine';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genslblockfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately
if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block
delete_block(blockaddress);
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q});
CGen.logmsg('\t%s\n',' done!');
%% Individual joint forward kinematics
CGen.logmsg([datestr(now),'\tGenerating forward kinematics Simulink block up to joint']);
for iJoints=1:CGen.rob.n
CGen.logmsg(' %i ',iJoints);
symname = ['T0_',num2str(iJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
tmpStruct = struct;
tmpStruct = load(fname);
funFileName = fullfile(CGen.robjpath,[symname,'.m']);
q = CGen.rob.gencoords;
blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately
if doesblockexist(CGen.slib,symname)
delete_block(blockaddress);
save_system;
end
symexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q});
end
CGen.logmsg('\t%s\n',' done!');
%% Cleanup
% Arrange blocks
distributeblocks(CGen.slib);
% Lock, save and close library
set_param(CGen.slib,'lock','on');
save_system(CGen.slib,CGen.slibpath);
close_system(CGen.slib);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmfunfdyn.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmfunfdyn.m
| 7,802 |
utf_8
|
9294c682375b50e7be5d15fec731151d
|
%CODEGENERATOR.GENMFUNFDYN Generate M-function for forward dynamics
%
% cGen.genmfunfdyn() generates a robot-specific M-function to compute
% the forward dynamics.
%
% Notes::
% - Is called by CodeGenerator.genfdyn if cGen has active flag genmfun
% - The generated M-function is composed of previously generated M-functions
% for the inertia matrix, coriolis matrix, vector of gravitational load and
% joint friction vector. This function recombines these components to compute
% the forward dynamics.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.geninvdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = genmfunfdyn(CGen)
%% Does robot class exist?
if ~exist(fullfile(CGen.robjpath,[CGen.getrobfname,'.m']),'file')
CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
CGen.createmconstructor;
CGen.logmsg('\t%s\n',' done!');
end
checkexistanceofmfunctions(CGen);
%%
CGen.logmsg([datestr(now),'\tGenerating m-function for the joint inertial reaction forces/torques' ]);
symname = 'Iqdd';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfdyn:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.m']);
[q qd] = CGen.rob.gencoords;
tau = CGen.rob.genforces;
matlabFunction(tmpStruct.(symname),'file',funfilename,... % generate function m-file
'outputs', {'Iacc'},...
'vars', {'rob',q,qd,tau});
hStruct = createHeaderStructIqdd(CGen.rob,symname); % replace autogenerated function header
replaceheader(CGen,hStruct,funfilename);
CGen.logmsg('\t%s\n',' done!');
%% Generate mfunction for the acceleration
CGen.logmsg([datestr(now),'\tGenerating joint acceleration m-function:']);
funfilename = fullfile(CGen.robjpath,'accel.m');
hStruct = createHeaderStructAccel(CGen.rob,funfilename);
fid = fopen(funfilename,'w+');
fprintf(fid, '%s\n', ['function qdd = accel(rob,q,qd,tau)']); % Function definition
fprintf(fid, '%s\n',constructheaderstring(CGen,hStruct)); % Header
fprintf(fid, '%s \n', 'qdd = zeros(length(q),1);'); % Code
funcCall = 'qdd = rob.inertia(q) \ rob.Iqdd(q,qd,tau).'';';
fprintf(fid, '%s \n', funcCall);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
function [] = checkexistanceofmfunctions(CGen)
if ~(exist(fullfile(CGen.robjpath,'inertia.m'),'file') == 2) || ~(exist(fullfile(CGen.robjpath,'Iqdd.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Inertia m-function not found! Generating:');
CGen.genmfuninertia;
end
if ~(exist(fullfile(CGen.robjpath,'coriolis.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Coriolis m-function not found! Generating:');
CGen.genmfuncoriolis;
end
if ~(exist(fullfile(CGen.robjpath,'gravload.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Gravload m-function not found! Generating:');
CGen.genmfungravload;
end
if ~(exist(fullfile(CGen.robjpath,'friction.m'),'file') == 2)
CGen.logmsg('\t\t%s\n','Friction m-function not found! Generating:');
CGen.genmfunfriction;
end
end
function hStruct = createHeaderStructIqdd(rob,fName)
[~,hStruct.funName] = fileparts(fName);
hStruct.shortDescription = ['Vector of computed inertial forces/torques for ',rob.name];
hStruct.calls = {['Iacc = ',hStruct.funName,'(rob,q,qd,tau)'],...
['Iacc = rob.',hStruct.funName,'(q,qd,tau)']};
hStruct.detailedDescription = {'Given a full set of joint variables, their temporal derivatives and applied joint forces/torques',...
'this function computes the reaction inertial forces/torques due to joint acceleration.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
['tau: ',int2str(rob.n),'-element vector of joint'],...
' input forces/torques',...
'Angles have to be given in radians!'};
hStruct.outputs = {['Iqdd: [1x',int2str(rob.n),'] vector of inertial reaction forces/torques']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'accel'};
end
function hStruct = createHeaderStructAccel(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Computation of the joint acceleration for ',rob.name];
hStruct.calls = {['qdd = ',hStruct.funName,'(rob,q,qd,tau)'],...
['qdd = rob.',hStruct.funName,'(q,qd,tau)']};
hStruct.detailedDescription = {'Given a full set of joint variables, their temporal derivatives and applied joint forces/torques',...
'this function computes the joint acceleration.'};
hStruct.inputs = { ['rob: robot object of ', rob.name, ' specific class'],...
['q: ',int2str(rob.n),'-element vector of generalized'],...
' coordinates',...
['qd: ',int2str(rob.n),'-element vector of generalized'],...
' velocities', ...
['tau: ',int2str(rob.n),'-element vector of joint'],...
' input forces/torques',...
'Angles have to be given in radians!'};
hStruct.outputs = {['qdd: [1x',int2str(rob.n),'] vector of joint accelerations']};
hStruct.references = {'1) Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'2) Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'3) Introduction to Robotics, Mechanics and Control - Craig',...
'4) Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn',...
'2012 RST, Technische Universitaet Dortmund, Germany',...
'http://www.rst.e-technik.tu-dortmund.de'};
hStruct.seeAlso = {'Iqdd'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexfkine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/genmexfkine.m
| 5,869 |
utf_8
|
072591863c353293642ac20d685a9e26
|
%CODEGENERATOR.GENMEXFKINE Generate C-MEX-function for forward kinematics
%
% cGen.genmexfkine() generates a robot-specific MEX-function to compute
% forward kinematics.
%
% Notes::
% - Is called by CodeGenerator.genfkine if cGen has active flag genmex
% - The MEX file uses the .c and .h files generated in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - Access to generated function is provided via subclass of SerialLink
% whose class definition is stored in cGen.robjpath.
% - You will need a C compiler to use the generated MEX-functions. See the
% MATLAB documentation on how to setup the compiler in MATLAB.
% Nevertheless the basic C-MEX-code as such may be generated without a
% compiler. In this case switch the cGen flag compilemex to false.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmexfkine(CGen)
%% Forward kinematics up to tool center point
CGen.logmsg([datestr(now),'\tGenerating forward kinematics MEX-function up to the end-effector frame: ']);
symname = 'fkine';
fname = fullfile(CGen.sympath,[symname,'.mat']);
if exist(fname,'file')
tmpStruct = load(fname);
else
error ('genmfunfkine:SymbolicsNotFound','Save symbolic expressions to disk first!')
end
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
Q = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStructFkine(CGen.rob,symname);
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname).T, 'funfilename',funfilename,'funname',[CGen.getrobfname,'_',symname],'vars',{Q},'output','T','header',hStruct)
CGen.logmsg('\t%s\n',' done!');
%% Individual joint forward kinematics
CGen.logmsg([datestr(now),'\tGenerating forward kinematics MEX-function up to joint: ']);
for iJoints=1:CGen.rob.n
CGen.logmsg(' %i ',iJoints);
symname = ['T0_',num2str(iJoints)];
fname = fullfile(CGen.sympath,[symname,'.mat']);
tmpStruct = load(fname);
funfilename = fullfile(CGen.robjpath,[symname,'.c']);
Q = CGen.rob.gencoords;
% Function description header
hStruct = createHeaderStruct(CGen.rob,iJoints,symname); % create header
% Generate and compile MEX function
CGen.mexfunction(tmpStruct.(symname).T,'funfilename',funfilename,'funname',[CGen.getrobfname,'_',symname],'vars',{Q},'output','T','header',hStruct);
end
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStruct(rob,curBody,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C version of the forward kinematics for the ',rob.name,' arm up to frame ',int2str(curBody),' of ',int2str(rob.n),'.'];
hStruct.detailedDescription = {['Given a set of joint variables up to joint number ',int2str(curBody),' the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = { 'input1 Vector of generalized coordinates. Angles have to be given in radians!'};
hStruct.outputs = {'T [4x4] Homogenous transformation matrix relating the pose of the tool for the given joint values to the base frame.'};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!<BR>',...
'Code generator written by:<BR>',...
'Joern Malzahn ([email protected])<BR>'};
hStruct.seeAlso = {rob.name};
end
%% Definition of the header contents for each generated file
function hStruct = createHeaderStructFkine(rob,fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.calls = '';
hStruct.shortDescription = ['C version of the forward kinematics solution including tool transformation for the ',rob.name,' arm.'];
hStruct.detailedDescription = {['Given a full set of joint variables the function'],...
'computes the pose belonging to that joint with respect to the base frame.'};
hStruct.inputs = { 'input1 Vector of generalized coordinates. Angles have to be given in radians!'};
hStruct.outputs = {'T [4x4] Homogenous transformation matrix relating the pose of the tool for the given joint values to the base frame.'};
hStruct.references = {'Robot Modeling and Control - Spong, Hutchinson, Vidyasagar',...
'Modelling and Control of Robot Manipulators - Sciavicco, Siciliano',...
'Introduction to Robotics, Mechanics and Control - Craig',...
'Modeling, Identification & Control of Robots - Khalil & Dombre'};
hStruct.authors = {'This is an autogenerated function!<BR>',...
'Code generator written by:<BR>',...
'Joern Malzahn ([email protected])<BR>'};
hStruct.seeAlso = {'jacob0'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gengaussjordanc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/gengaussjordanc.m
| 6,903 |
utf_8
|
5f38ad2847d7c72550af20ec560b0091
|
%CODEGENERATOR.GENGAUSSJORDANC Generates a Gauss-Jordan C-implementation.
%
% cGen.gengaussjordanc generates a .h and a .c file in the directory
% specified by ccodepath.
%
% Notes::
% - Is called by genfdyn if cGen has active flag genmex or genccode.
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator, CodeGenerator.gendotprodc.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = gengaussjordanc(CGen)
funname = 'gaussjordan';
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
% Check for already existing gauss-jordan C-files
if exist(fullfile(srcDir,funfilename),'file') && exist(fullfile(srcDir,funfilename),'file')
return;
end
% Check for existance of C-code directories
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
% Create the function description header
hStruct = createHeaderStruct(funname); % create header
if ~isempty(hStruct)
hFString = CGen.constructheaderstringc(hStruct);
end
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
fprintf(fid,'%s\n\n',...
'#include "stdlib.h"'); % include stdlib.h, otherwise malloc will return int and not void*
% Start actual function implementation
fprintf(fid,'%s\n',['void ',funname,'(const double* inMatrix, double* outMatrix, int dim){']);
fprintf(fid,'%s\n',' '); % empty line
% variable declarations
fprintf(fid,'\t%s\n','int iRow, iCol, diagIndex;');
fprintf(fid,'\t%s\n','double diagFactor, tmpFactor;');
fprintf(fid,'\t%s\n','double* inMatrixCopy = (double*) malloc(dim*dim*sizeof(double));');
fprintf(fid,'%s\n',' '); % empty line
% input initialization
fprintf(fid,'\t%s\n','/* make deep copy of input matrix */');
fprintf(fid,'\t%s\n','for(iRow = 0; iRow < dim; iRow++ ){');
fprintf(fid,'\t\t%s\n','for (iCol = 0; iCol < dim; iCol++){');
fprintf(fid,'\t\t\t%s\n','inMatrixCopy[dim*iCol+iRow] = inMatrix[dim*iCol+iRow];');
fprintf(fid,'\t\t%s\n','}');
fprintf(fid,'\t%s\n','}');
fprintf(fid,'\t%s\n','/* Initialize output matrix as identity matrix. */');
fprintf(fid,'\t%s\n','for (iRow = 0; iRow < dim; iRow++ ){');
fprintf(fid,'\t\t%s\n','for (iCol = 0; iCol < dim; iCol++ ){');
fprintf(fid,'\t\t\t%s\n','if (iCol == iRow){');
fprintf(fid,'\t\t\t\t%s\n','outMatrix[dim*iCol+iRow] = 1;');
fprintf(fid,'\t\t\t%s\n','}');
fprintf(fid,'\t\t\t%s\n','else{');
fprintf(fid,'\t\t\t\t%s\n','outMatrix[dim*iCol+iRow] = 0;');
fprintf(fid,'\t\t\t%s\n','}');
fprintf(fid,'\t\t%s\n','}');
fprintf(fid,'\t%s\n','}');
fprintf(fid,'%s\n',' '); % empty line
% actual elimination
fprintf(fid,'\t%s\n','for (diagIndex = 0; diagIndex < dim; diagIndex++ )');
fprintf(fid,'\t%s\n','{');
fprintf(fid,'\t\t%s\n','/* determine diagonal factor */');
fprintf(fid,'\t\t%s\n','diagFactor = inMatrixCopy[dim*diagIndex+diagIndex];');
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t\t%s\n','/* divide column entries by diagonal factor */');
fprintf(fid,'\t\t%s\n','for (iCol = 0; iCol < dim; iCol++){');
fprintf(fid,'\t\t\t%s\n','inMatrixCopy[dim*iCol+diagIndex] /= diagFactor;');
fprintf(fid,'\t\t\t%s\n','outMatrix[dim*iCol+diagIndex] /= diagFactor;');
fprintf(fid,'\t\t%s\n','}');
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t\t%s\n','/* perform line-by-line elimination */');
fprintf(fid,'\t\t%s\n','for (iRow = 0; iRow < dim; iRow++){');
fprintf(fid,'\t\t\t%s\n','if (iRow != diagIndex){');
fprintf(fid,'\t\t\t\t%s\n','tmpFactor = inMatrixCopy[dim*diagIndex+iRow];');
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t\t\t\t%s\n','for(iCol = 0; iCol < dim; iCol++){');
fprintf(fid,'\t\t\t\t%s\n','inMatrixCopy[dim*iCol+iRow] -= inMatrixCopy[dim*iCol+diagIndex]*tmpFactor;');
fprintf(fid,'\t\t\t\t%s\n','outMatrix[dim*iCol+iRow] -= outMatrix[dim*iCol+diagIndex]*tmpFactor;');
fprintf(fid,'\t\t\t\t%s\n','}');
fprintf(fid,'\t\t\t%s\n','}');
fprintf(fid,'\t\t%s\n','} /* line-by-line elimination */');
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','}');
fprintf(fid,'\t%s\n','free(inMatrixCopy);');
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Function prototype
fprintf(fid,'%s\n\n',['void ',funname,'(const double *inMatrix, double *outMatrix, int dim);']);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStruct(fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Compute the inverse of a positive definite square matrix'];
hStruct.calls = [hStruct.funName,'(const double* inMatrix, double* outMatrix, int dim)'];
hStruct.detailedDescription = {'Given a positive definite square matrix of dimension dim in inMatrix,',...
'the function returns its inverse outMatrix. The inverse is computed using Gauss-Jordan elimination ',...
'without pivoting.'};
hStruct.inputs = { ['inMatrix: array of doubles storing [dim x dim] elements of the input square matrix column by column,'],...
'dim: dimension of the square matrix.'};
hStruct.outputs = {['outMatrix: array of doubles storing [dim x dim] elements of the output square matrix column by column.']};
hStruct.references = {'The C Book: http://publications.gbdirect.co.uk/c_book/'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'CodeGenerator'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
replaceheader.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/replaceheader.m
| 3,138 |
utf_8
|
d97bfc9ab9c0179cce2fb9501d843416
|
%CODEGENERATOR.REPLACEHEADER Replace autogenerated function headers by Toolbox-headers.
%
% CGen.replaceheader(HSTRUCT,FILENAME)
% HSTRUCT is the struct defining the contents of the header.
% FILENAME is the relative or full path to the file that has an autogenerated
% header to be replaced.
%
% Notes::
% The MatLab built-in function "matlabFunction" generates a standard
% header stub of 3 lines. This header is extended by the common
% toolbox-header. The contents of the header are coded in a struct that is
% the first input parameter and has the following self-explaining fields:
%
% Fieldname Datatype
% - funName 'string'
% - shortDescription 'string'
% - detailedDescription {'line1','line2',...}
% - inputs {'input1: description','input2: description',...}
% - outputs {'output1: description','output2: description',...}
% - examples {'line1','line2',...}
% - knownBugs {'line1','line2',...}
% - toDO {'line1','line2',...}
% - references {'line1','line2',...}
% - authors {'line1','line2',...}
% - seeAlso {'function1','function2',...}
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also matlabFunction, CodeGenerator.constructheaderstring.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = replaceheader(CGen,hStruct,fileName)
%% Get the first three lines of the original file
threeLines = cell(1,3); % innitialize storage cell
fid = fopen(fileName,'r'); % open the file
threeLines{1} = fgetl(fid); % read the three lines
threeLines{2} = fgetl(fid);
threeLines{3} = fgetl(fid);
fclose(fid); % close the file
%% Delete old header
CGen.ffindreplace(fileName,threeLines{1},''); % Erase first line
CGen.ffindreplace(fileName,threeLines{2},''); % Erase second line
CGen.ffindreplace(fileName,threeLines{3},''); % Erase third line
%% Insert new header
hFString = CGen.constructheaderstring(hStruct);
CGen.finsertfront(fileName, sprintf([threeLines{1},'\n%s\n%s'],hFString,CGen.getpibugfixstring));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ffindreplace.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/ffindreplace.m
| 2,477 |
utf_8
|
a1601d071fd66ed97f1660b3e2c2360c
|
%CODEGENERATOR.FFINDREPLACE Find and replace all occurrences of string in a file.
%
% CGen.ffindreplace(fName, oText, nText, varargin)
% FNAME is the absolute or relative path to the file to replace the text in.
% OTEXT is the text passage to replace.
% NTEXT is the new text.
%
% Notes::
% The function opens and sweeps the text file FNAME. All occurrences of
% OTEXT are replaced by NTEXT.
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.finsertfront.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = ffindreplace(CGen, fName, oText, nText, varargin)
fid = fopen(fName,'r'); % open the file
% determine number of lines in the file
nLines = getNLines(fid);
% read all lines to cell
oldLines = cell(1,nLines);
newLines = {1,nLines};
for iLines = 1:nLines
oldLines{iLines} = fgets(fid);
end
% close the file again
fclose(fid);
% replace all occurrences of oText by nText in each line
for iLines = 1:nLines
newLines{iLines}= strrep(oldLines{iLines}, oText, nText);
end
% rewrite the file
fid = fopen(fName,'w');
for iLines = 1:nLines
fprintf(fid,'%s',newLines{iLines});
end
fclose(fid);
end
function [nLines] = getNLines(fid)
nLines = 0;
while (~feof(fid)) % go through each line until eof is reached
fgets(fid);
nLines = nLines +1; % increment line counter
end
frewind(fid); % set file indicator back to the beginning of the file
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
createmconstructor.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/createmconstructor.m
| 2,503 |
utf_8
|
5cfd4be539ea29857cbe7f50f31a41b7
|
%CODEGENERATOR.CREATEMCONSTRUCTOR Creates the constructor of the specialized robot class collecting the generated m-function code.
%
% cGen.createmconstructor()
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.genfkine, CodeGenerator.genmfunfkine.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [] = createmconstructor(CGen)
objdir = CGen.robjpath;
robname = CGen.getrobfname;
if ~exist(objdir,'dir')
mkdir(objdir)
end
sr = CGen.rob;
save(fullfile(objdir,['mat',robname]), 'sr');
fid = fopen(fullfile(objdir,[robname,'.m']),'w+');
fprintf(fid,'%s\n',['classdef ',robname,' < SerialLink']);
fprintf(fid,'%s\n',' ');
fprintf(fid,'\t%s\n', 'properties');
fprintf(fid,'\t%s\n','end');
fprintf(fid,'%s\n',' ');
fprintf(fid,'\t%s\n','methods');
fprintf(fid,'\t\t%s\n',['function ro = ',robname,'()']);
fprintf(fid,'\t\t\t%s\n',['objdir = which(''',robname,''');']);
fprintf(fid,'\t\t\t%s\n','idx = find(objdir == filesep,2,''last'');');
fprintf(fid,'\t\t\t%s\n','objdir = objdir(1:idx(1));');
fprintf(fid,'\t\t\t%s\n',' ');
fprintf(fid,'\t\t\t%s\n',['tmp = load(fullfile(objdir,',['''@',robname],''',''mat',robname,'.mat''));']);
fprintf(fid,'\t\t\t%s\n',' ');
fprintf(fid,'\t\t\t%s\n','ro = ro@SerialLink(tmp.sr);');
fprintf(fid,'\t\t\t%s\n', ' ');
fprintf(fid,'\t\t\t%s\n',' ');
fprintf(fid,'\t\t%s\n','end');
fprintf(fid,'\t%s\n','end');
fprintf(fid,'\t%s\n',' ');
fprintf(fid,'%s\n','end');
fclose(fid);
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mexfunctionrowwise.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/mexfunctionrowwise.m
| 5,495 |
utf_8
|
93572d05950dd529cd66565fc95ce739
|
%MEXFUNCTION Converts a symbolic expression into a MEX-function
%
% [] = cGen.mexfunction(SYMEXPR, ARGLIST) translates a symbolic expression
% into C-code and joins it with a MEX gateway routine. The resulting C-file
% is ready to be compiled using the matlab built-in mex command.
%
% The argumentlist ARGLIST may contain the following property-value pairs
% PROPERTY, VALUE
% - 'funname', 'name_string'
% 'name_string' is the actual identifier of the obtained C-function.
% Default: 'myfun'
%
% - 'funfilename', 'file_name_string'
% 'file_name_string' is the name of the generated C-file including
% relativepath or absolute path information.
% Default: 'myfunfilename'
%
% - 'output', 'output_name'
% Defines the identifier of the output variable in the C-function.
% Default: 'out'
%
% - 'vars', {symVar1, symVar2,...}
% The inputs to the C-code function must be defined as a cell array. The
% elements of this cell array contain the symbolic variables required to
% compute the output. The elements may be scalars, vectors or matrices
% symbolic variables. The C-function prototype will be composed accordingly
% as exemplified above.
%
% - 'header', hStruct
% Struct containing header information. See constructheaderstring
% Default: []
%
% Example::
%
%
% Notes::
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also mex, ccode, matlabFunction.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = mexfunctionrowwise(CGen, f, varargin )
%% Read parameters
% option defaults
opt.funname = 'myfun';
opt.vars = {};
opt.output = 'out';
opt.funfilename = 'myfunfilename';
opt.hStruct = [];
% tb_optparse is not applicable here,
% since handling cell inputs and extracting input variable names is
% required. Thus, scan varargin manually:
if mod(nargin,2)~=0
error('CodeGenerator:mexfunction:wrongArgumentList',...
'Wrong number of elements in the argument list.');
end
for iArg = 1:2:nargin-2
switch lower(varargin{iArg})
case 'funname'
if ~isempty(varargin{iArg+1})
opt.funname = varargin{iArg+1};
end
case 'funfilename'
if ~isempty(varargin{iArg+1})
opt.funfilename = varargin{iArg+1};
end
case 'output'
if ~isempty(varargin{iArg+1})
opt.outputName{1} = varargin{iArg+1};
end
case 'vars'
opt.vars = varargin{iArg+1};
case 'header'
opt.hStruct = varargin{iArg+1};
otherwise
error('genmexgatewaystring:unknownArgument',...
['Argument ',inputname(iArg),' unknown.']);
end
end
%% Copyright Note
cprNote = CGen.generatecopyrightnote;
cprNote = regexprep(cprNote, '%', '//');
%% Create compilation command
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
cfilelist = fullfile(srcDir,[opt.funname,'.c']);
for kJoints = 1:CGen.rob.n
cfilelist = [cfilelist, ' ',fullfile(srcDir,[opt.funname,'_row_',num2str(kJoints),'.c'])];
end
if CGen.verbose
mexCompCmnd = ['mex ',opt.funfilename, ' ',cfilelist,' -I',hdrDir, ' -v -outdir ',CGen.robjpath];
else
mexCompCmnd = ['mex ',opt.funfilename, ' ',cfilelist,' -I',hdrDir,' -outdir ',CGen.robjpath];
end
%% Generate C code
fid = fopen(opt.funfilename,'w+');
% Add compilation note
fprintf(fid,'/* %s\n',[upper(opt.funname) ,' - This file contains auto generated C-code for a MATLAB MEX function.']);
fprintf(fid,'// %s\n',['For details on how to use the complied MEX function see the documentation provided in ',opt.funname,'.m']);
fprintf(fid,'// %s\n//\n',['The compiled MEX function replaces this .m-function with identical usage but substantial execution speedup.']);
fprintf(fid,'// %s\n//\n',['For compilation of this C-code using MATLAB please run:']);
fprintf(fid,'// \t\t%s\n//\n',['''',mexCompCmnd,'''']);
fprintf(fid,'// %s\n',['Make sure you have a C-compiler installed and your MATLAB MEX environment readily configured.']);
fprintf(fid,'// %s\n//\n',['Type ''doc mex'' for additional help.']);
% Insert Copyright Note
fprintf(fid,'// %s\n','__Copyright Note__:');
fprintf(fid,'%s */\n',cprNote);
% Includes
fprintf(fid,'%s\n%s\n\n',...
'#include "mex.h"',...
['#include "',[opt.funname,'.h'],'"']);
% Generate the mex gateway routine
funstr = CGen.genmexgatewaystring(f,'funname',opt.funname, 'vars',opt.vars);
fprintf(fid,'%s',sprintf(funstr));
fclose(fid);
%% Compile the MEX file
if CGen.compilemex
eval(mexCompCmnd)
end
CGen.logmsg('\t%s\n',' done!');
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gendotprodc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/gendotprodc.m
| 4,005 |
utf_8
|
a3d8b369a875e0d81802ac04de3617d6
|
%CODEGENERATOR.GENDOTPRODC Generates a dot product C-implementation.
%
% cGen.gendotprodc generates a .h and a .c file in the directory
% specified by ccodepath.
%
% Notes::
% - Is called by geninvdyn if cGen has active flag genmex or genccode.
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator, CodeGenerator.gengaussjordanc.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = gendotprodc(CGen)
funname = 'dotprod';
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
% Check for existance of dotProd C-files
if exist(fullfile(srcDir,funfilename),'file') && exist(fullfile(srcDir,funfilename),'file')
return;
end
% Check for existance of C-code directories
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
fSignature = ['double ',funname,'(const double *input1, const double *input2, int nEl)'];
% Create the function description header
hStruct = createHeaderStruct(funname); % create header
hStruct.calls = fSignature;
if ~isempty(hStruct)
hFString = CGen.constructheaderstringc(hStruct);
end
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n',[fSignature,'{']);
fprintf(fid,'\t%s\n','double res = 0;');
fprintf(fid,'\t%s\n\n','int iEl = 0;');
fprintf(fid,'\t%s\n','for (iEl = 0; iEl < nEl; iEl++){');
fprintf(fid,'\t\t%s\n','res += input1[iEl] * input2[iEl];');
fprintf(fid,'\t%s\n\n','}');
fprintf(fid,'\t%s\n','return res;');
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Function prototype
fprintf(fid,'%s\n\n',['double ',funname,'(const double *input1, const double *input2, int nEl);']);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStruct(fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Compute the dot product of two vectors'];
hStruct.detailedDescription = {['Given two vectors of length nEl in the input arrays'],...
'input1 and input 2 the function computes the dot product (or scalar product) of both vectors.'};
hStruct.inputs = { ['input1: nEl element array of doubles,'],...
['input2: nEl element array of doubles,'],...
'nEl: dimension of the two arrays.'};
hStruct.outputs = {};
hStruct.references = {'The C Book: http://publications.gbdirect.co.uk/c_book/'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'CodeGenerator'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmexgatewaystring.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/genmexgatewaystring.m
| 6,250 |
utf_8
|
3867ec5d50475db795eb1075fd926a80
|
%GENMEXGATEWAYSTRING Generates a mex gateway function
%
% [FUNSTR] = genmexgatewaystring(SYMEXPR, ARGLIST) returns a string
% representing a C-code implementation of a mex gateway function.
%
% The argumentlist ARGLIST may contain the following property-value pairs
% PROPERTY, VALUE
% - 'funname', 'name_string'
% 'name_string' is the identifier of the actual computational C-function
% called by the gateway routine. If this optional argument is omitted,
% the identifier 'myfun' is used
%
% - 'vars', {symVar1, symVar2,...}
% The inputs to the actual computational C-code function called by the
% gateway routine must be defined as a cell array. The elements of this
% cell array contain the symbolic variables required to compute the
% output. The elements may be scalars, vectors or matrices symbolic
% variables.
%
% Example::
% % Create symbolic variables
% syms q1 q2 q3
%
% Q = [q1 q2 q3];
% % Create symbolic expression
% myrot = rotz(q3)*roty(q2)*rotx(q1)
%
% % Generate C-function string
% [funstr] = genmexgatewaystring(myrot,'vars',{Q},'funname','rotate_xyz')
%
% Notes::
%
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also ccode, ccodefunctionstring.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [ gwstring ] = genmexgatewaystring(CGen, f, varargin )
%% Read parameters
% option defaults
opt.funname = 'myfun';
opt.output{1} = zeros(size(f));
opt.vars = {};
% tb_optparse is not applicable here,
% since handling cell inputs and extracting input variable names is
% required. Thus, scan varargin manually:
if mod(nargin,2)~=0
error('CodeGenerator:genmexgatewaystring:wrongArgumentList',...
'Wrong number of elements in the argument list.');
end
for iArg = 1:2:nargin-2
switch lower(varargin{iArg})
case 'funname'
if ~isempty(varargin{iArg+1})
opt.funname = varargin{iArg+1};
end
case 'vars'
opt.vars = varargin{iArg+1};
otherwise
error('genmexgatewaystring:unknownArgument',...
['Argument ',inputname(iArg),' unknown.']);
end
end
nIn = numel(opt.vars);
%% begin to write the function string
% gwstring = sprintf('\n\n\n');
gwstring = sprintf('\n');
gwstring = [gwstring, sprintf('%s\n','/* The gateway function */')];
gwstring = [gwstring, sprintf('%s\n','void mexFunction( int nlhs, mxArray *plhs[],')];
gwstring = [gwstring, sprintf('%s\n',' int nrhs, const mxArray *prhs[])')];
gwstring = [gwstring, sprintf('%s\n','{')];
%% variable declaration
gwstring = [gwstring, sprintf('\t%s\n','/* variable declarations */')];
% output
gwstring = [gwstring, sprintf('\t%s\n','double* outMatrix; /* output matrix */')];
% inputs
for iIn = 1:nIn
tmpInName = ['input',num2str(iIn)];
tmpIn = opt.vars{iIn};
gwstring = [gwstring, sprintf('\tdouble* %s;\n', tmpInName ) ];
end
gwstring = [gwstring, sprintf('%s\n',' ')]; % Empty line
%% argument checks
% number of input arguments
gwstring = [gwstring, sprintf('\t%s\n','/* check for proper number of arguments */')];
gwstring = [gwstring, sprintf('\t%s%u%s\n','if(nrhs!=',nIn+1,') {')];
gwstring = [gwstring, sprintf('\t\t%s%s%s\n','mexErrMsgIdAndTxt("',opt.funname,':nrhs",')];
gwstring = [gwstring, sprintf('\t\t%s%u%s\n',' "',nIn,' inputs required.");')];
gwstring = [gwstring, sprintf('\t%s\n','}')];
% dimensions of input arguments
% number of output arguments
gwstring = [gwstring, sprintf('\t%s%u%s\n','if(nlhs>',1,') {')];
gwstring = [gwstring, sprintf('\t\t%s%s%s\n','mexErrMsgIdAndTxt("',opt.funname,':nlhs",')];
gwstring = [gwstring, sprintf('\t\t%s\n',' "Only single output allowed.");')];
gwstring = [gwstring, sprintf('\t%s\n','}')];
gwstring = [gwstring, sprintf('%s\n',' ')]; % Empty line
%% pointer initialization for...
% the output
gwstring = [gwstring, sprintf('\t%s\n','/* allocate memory for the output matrix */')];
gwstring = [gwstring, sprintf('\t%s\n',['plhs[0] = mxCreateDoubleMatrix(',num2str(size(f,1)),',',num2str(size(f,2)),', mxREAL);'])];
gwstring = [gwstring, sprintf('\t%s\n','/* get a pointer to the real data in the output matrix */')];
gwstring = [gwstring, sprintf('\t%s\n','outMatrix = mxGetPr(plhs[0]);')];
gwstring = [gwstring, sprintf('%s\n',' ')]; % Empty line
% inputs
gwstring = [gwstring, sprintf('\t%s\n','/* get a pointers to the real data in the input matrices */')];
for iIn = 1:nIn
tmpInName = ['input',num2str(iIn)];%opt.varsName{iIn};
tmpIn = opt.vars{iIn};
gwstring = [gwstring, sprintf('\t%s\n',[tmpInName,' = mxGetPr(prhs[',num2str(iIn),']);'])]; % first input argument is the robot object, thus count one-based here
end
gwstring = [gwstring, sprintf('%s\n',' ')]; % Empty line
%% call computational routine
gwstring = [gwstring, sprintf('\t%s\n','/* call the computational routine */')];
gwstring = [gwstring, sprintf('\t%s',[opt.funname,'(','outMatrix, '])];
% comma separated list of input arguments
for iIn = 1:nIn
tmpInName = ['input',num2str(iIn)];
gwstring = [gwstring, sprintf('%s',tmpInName)];
% separate argument list by commas
if ( iIn ~= nIn )
gwstring = [gwstring,', '];
else
gwstring = [gwstring,sprintf('%s\n',');')];
end
end
%% finalize
gwstring = [gwstring, sprintf('%s\n','}')];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
getpibugfixstring.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/getpibugfixstring.m
| 2,208 |
utf_8
|
31ba4fc3a8c2f06af6c3cb2d844140af
|
%CODEGENERATOR.GETPIBUGFIXSTRING Returns a string to fix PI-Bug in auto genereated functions.
%
% bfixString = cGen.getPiBugfixString() Is the string with explanation comment
% and variable declaration as described below.
%
% Notes::
% In some versions the symbolic toolbox writes the constant $pi$ in
% capital letters. This way autogenerated functions might not work properly.
% To fix this issue a local variable is introduced:
% PI = pi
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.constructheaderstring, CodeGenerator.replaceheader.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function bfixString = getpibugfixstring(CGen)
bfixString = [];
bfixString = [bfixString, sprintf('%s\n','%% Bugfix')];
bfixString = [bfixString, sprintf('%s\n','% In some versions the symbolic toolbox writes the constant $pi$ in')];
bfixString = [bfixString, sprintf('%s\n','% capital letters. This way autogenerated functions might not work properly.')];
bfixString = [bfixString, sprintf('%s\n','% To fix this issue a local variable is introduced:')];
bfixString = [bfixString, sprintf('%s\n','PI = pi;')];
bfixString = [bfixString, sprintf('%s\n',' ')];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genmatvecprodc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/genmatvecprodc.m
| 4,521 |
utf_8
|
6d83466255b1dddae8de802f25a5e52e
|
%CODEGENERATOR.GENMATVECPRODC Generates a matrix-vector product C-implementation.
%
% cGen.gendotprodc generates a .h and a .c file in the directory
% specified by ccodepath.
%
% Notes::
% - Is called by geninvdyn and genfdyn if cGen has active flag genmex or genccode.
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator, CodeGenerator.gengaussjordanc.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = genmatvecprodc(CGen)
funname = 'matvecprod';
funfilename = [funname,'.c'];
hfilename = [funname,'.h'];
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
% Check for existance of dotProd C-files
if exist(fullfile(srcDir,funfilename),'file') && exist(fullfile(srcDir,funfilename),'file')
return;
end
% Check for existance of C-code directories
if ~exist(srcDir,'dir')
mkdir(srcDir);
end
if ~exist(hdrDir,'dir')
mkdir(hdrDir);
end
% Create the function description header
hStruct = createHeaderStruct(funname); % create header
if ~isempty(hStruct)
hFString = CGen.constructheaderstringc(hStruct);
end
%% Generate C implementation file
fid = fopen(fullfile(srcDir,funfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Includes
fprintf(fid,'%s\n\n',...
['#include "', hfilename,'"']);
% Function
fprintf(fid,'%s\n',['void ', funname, '(double *outVector, const double *inMatrix, const double *inVector, int nRow, int nCol){']);
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','int iRow, iCol = 0;');
fprintf(fid,'%s\n',' '); % empty line
fprintf(fid,'\t%s\n','for (iRow = 0; iRow < nRow; iRow++){');
fprintf(fid,'\t\t%s\n','for (iCol = 0; iCol < nCol; iCol++){');
fprintf(fid,'\t\t\t%s\n','outVector[iCol] += inMatrix[nRow*iRow+iCol] * inVector[iRow];');
fprintf(fid,'\t\t%s\n','}');
fprintf(fid,'\t%s\n','} ');
fprintf(fid,'%s\n','}');
fclose(fid);
%% Generate C header file
fid = fopen(fullfile(hdrDir,hfilename),'w+');
% Function description header
fprintf(fid,'%s\n\n',hFString);
% Include guard
fprintf(fid,'%s\n%s\n\n',...
['#ifndef ', upper([funname,'_h'])],...
['#define ', upper([funname,'_h'])]);
% Function prototype
fprintf(fid,'%s\n\n',['void ',funname,'(double *outVector, const double *inMatrix, const double *inVector, int nRow, int nCol);']);
% Include guard
fprintf(fid,'%s\n',...
['#endif /*', upper([funname,'_h */'])]);
fclose(fid);
CGen.logmsg('\t%s\n',' done!');
end
%% Definition of the function description header contents
function hStruct = createHeaderStruct(fname)
[~,hStruct.funName] = fileparts(fname);
hStruct.shortDescription = ['Compute the product of a matrix and a vector'];
hStruct.calls = ['void ',hStruct.funName,'(double *outVector, const double *inMatrix, const double *inVector, int nRow, int nCol)'];
hStruct.detailedDescription = {['Given an [nRow x nCol] inMatrix and a nCol-element inVector, the function'],...
'computes the nRow-element outVector as: outVector = inMatrix*inVector.'};
hStruct.inputs = { ['inMatrix: [nRow x nCol] input matrix,'],...
['inVector: nCol-element input vector,'],...
['nRow: number of rows of inMatrix,'],...
'nCol: number of columns of inMatrix and elements of inVector.'};
hStruct.outputs = {['outVector: nRow-element output vector.']};
hStruct.references = {'The C Book: http://publications.gbdirect.co.uk/c_book/'};
hStruct.authors = {'This is an autogenerated function!',...
'Code generator written by:',...
'Joern Malzahn ([email protected])'};
hStruct.seeAlso = {'CodeGenerator'};
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mexfunction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/mexfunction.m
| 5,325 |
utf_8
|
c949fe9c525e5caa5983bb6b6af3efc1
|
%MEXFUNCTION Converts a symbolic expression into a MEX-function
%
% [] = cGen.mexfunction(SYMEXPR, ARGLIST) translates a symbolic expression
% into C-code and joins it with a MEX gateway routine. The resulting C-file
% is ready to be compiled using the matlab built-in mex command.
%
% The argumentlist ARGLIST may contain the following property-value pairs
% PROPERTY, VALUE
% - 'funname', 'name_string'
% 'name_string' is the actual identifier of the obtained C-function.
% Default: 'myfun'
%
% - 'funfilename', 'file_name_string'
% 'file_name_string' is the name of the generated C-file including
% relativepath or absolute path information.
% Default: 'myfunfilename'
%
% - 'output', 'output_name'
% Defines the identifier of the output variable in the C-function.
% Default: 'out'
%
% - 'vars', {symVar1, symVar2,...}
% The inputs to the C-code function must be defined as a cell array. The
% elements of this cell array contain the symbolic variables required to
% compute the output. The elements may be scalars, vectors or matrices
% symbolic variables. The C-function prototype will be composed accordingly
% as exemplified above.
%
% - 'header', hStruct
% Struct containing header information. See constructheaderstring
% Default: []
%
% Example::
%
%
% Notes::
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also mex, ccode, matlabFunction.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [] = mexfunction(CGen, f, varargin )
%% Read parameters
% option defaults
opt.funname = 'myfun';
opt.vars = {};
opt.output = 'out';
opt.funfilename = 'myfunfilename';
opt.hStruct = [];
% tb_optparse is not applicable here,
% since handling cell inputs and extracting input variable names is
% required. Thus, scan varargin manually:
if mod(nargin,2)~=0
error('CodeGenerator:mexfunction:wrongArgumentList',...
'Wrong number of elements in the argument list.');
end
for iArg = 1:2:nargin-2
switch lower(varargin{iArg})
case 'funname'
if ~isempty(varargin{iArg+1})
opt.funname = varargin{iArg+1};
end
case 'funfilename'
if ~isempty(varargin{iArg+1})
opt.funfilename = varargin{iArg+1};
end
case 'output'
if ~isempty(varargin{iArg+1})
opt.outputName{1} = varargin{iArg+1};
end
case 'vars'
opt.vars = varargin{iArg+1};
case 'header'
opt.hStruct = varargin{iArg+1};
otherwise
error('genmexgatewaystring:unknownArgument',...
['Argument ',inputname(iArg),' unknown.']);
end
end
%% Create Copyright Note
cprNote = CGen.generatecopyrightnote;
cprNote = regexprep(cprNote, '%', '//');
%% Create Compilation Command
srcDir = fullfile(CGen.ccodepath,'src');
hdrDir = fullfile(CGen.ccodepath,'include');
if CGen.verbose
mexCompCmnd = ['mex ',opt.funfilename, ' ',fullfile(srcDir,[opt.funname,'.c']),' -I',hdrDir, ' -v -outdir ',CGen.robjpath];
else
mexCompCmnd = ['mex ',opt.funfilename, ' ',fullfile(srcDir,[opt.funname,'.c']),' -I',hdrDir,' -outdir ',CGen.robjpath];
end
%% Generate C code
fid = fopen(opt.funfilename,'w+');
% Add compilation note
fprintf(fid,'/* %s\n',[upper(opt.funname) ,' - This file contains auto generated C-code for a MATLAB MEX function.']);
fprintf(fid,'// %s\n',['For details on how to use the complied MEX function see the documentation provided in ',opt.funname,'.m']);
fprintf(fid,'// %s\n//\n',['The compiled MEX function replaces this .m-function with identical usage but substantial execution speedup.']);
fprintf(fid,'// %s\n//\n',['For compilation of this C-code using MATLAB please run:']);
fprintf(fid,'// \t\t%s\n//\n',['''',mexCompCmnd,'''']);
fprintf(fid,'// %s\n',['Make sure you have a C-compiler installed and your MATLAB MEX environment readily configured.']);
fprintf(fid,'// %s\n//\n',['Type ''doc mex'' for additional help.']);
% Insert Copyright Note
fprintf(fid,'// %s\n','__Copyright Note__:');
fprintf(fid,'%s */\n',cprNote);
% Includes
fprintf(fid,'%s\n%s\n\n',...
'#include "mex.h"',...
['#include "',[opt.funname,'.h'],'"']);
% Generate the mex gateway routine
funstr = CGen.genmexgatewaystring(f,'funname',opt.funname, 'vars',opt.vars);
fprintf(fid,'%s',sprintf(funstr));
fclose(fid);
%% Compile the MEX file
if CGen.compilemex
eval(mexCompCmnd)
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
constructheaderstringc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/constructheaderstringc.m
| 8,788 |
utf_8
|
548ed9f487884f775aee44949e490f1e
|
%CODEGENERATOR.CONSTRUCTHEADERSTRINGC Creates common toolbox header string.
%
% HFSTRING = CGen.constructheaderstringc(HSTRUCT) is the formatted header
% string.
% HSTRUCT is the header content struct
%
% Notes::
% The contents of the header are coded in a struct that is the input
% parameter and has the following self-explaining fields:
% Fieldname Datatype
% - funName 'string'
% - shortDescription 'string'
% - detailedDescription {'line1','line2',...}
% - inputs {'input1: description','input2: description',...}
% - outputs {'output1: description','output2: description',...}
% - examples {'line1','line2',...}
% - knownBugs {'line1','line2',...}
% - toDO {'line1','line2',...}
% - references {'line1','line2',...}
% - authors {'line1','line2',...}
% - seeAlso {'function1','function2',...}
%
% Example::
% hStruct.funName = 'myFirstFunction';
% hStruct.shortDescription = ['Just an example!'];
% hStruct.calls = {'result = myFirstFunction(A,B)'};
% constructheaderstringc(hStruct)
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator.constructheaderstring, sprintf.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
% function [hFString] = constructheaderstringc(CGen,hStruct)
%
% % reuse existing header construction routine,
% hFString = CGen.constructheaderstring(hStruct);
%
% % replace comment characters for C-compliance
% hFString = regexprep(hFString, '%', '//');
%CODEGENERATOR.CONSTRUCTHEADERSTRING Creates common toolbox header string.
%
% HFSTRING = CGen.constructheaderstring(HSTRUCT) is the formatted header
% string.
% HSTRUCT is the geader content struct
%
% Notes::
% The contents of the header are coded in a struct that is the input
% parameter and has the following self-explaining fields:
% Fieldname Datatype
% - funName 'string'
% - shortDescription 'string'
% - detailedDescription {'line1','line2',...}
% - inputs {'input1: description','input2: description',...}
% - outputs {'output1: description','output2: description',...}
% - examples {'line1','line2',...}
% - knownBugs {'line1','line2',...}
% - toDO {'line1','line2',...}
% - references {'line1','line2',...}
% - authors {'line1','line2',...}
% - seeAlso {'function1','function2',...}
%
% Example::
% hStruct.funName = 'myFirstFunction';
% hStruct.shortDescription = ['Just an example!'];
% hStruct.calls = {'result = myFirstFunction(A,B)'};
% constructheaderstring(hStruct)
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator.replaceheader, sprintf.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [hFString] = constructheaderstringc(CGen,hStruct)
hFString = [];
hFString = [hFString,sprintf('%s\n',['/*! \file ',hStruct.funName,'.h'])];
if isfield(hStruct,'funName') && isfield(hStruct,'shortDescription')
hFString = [hFString, sprintf('%s \n',['\brief ', hStruct.shortDescription, ''])];
hFString = [hFString, sprintf('%s \n', ' ')]; % Empty line
else
error('Header must include the function name and provide a short description!')
end
%% Detailed description
hFString = [hFString, sprintf('%s \n', ' ')];
if isfield(hStruct,'detailedDescription')
nDescription = length(hStruct.detailedDescription);
for iDescription = 1:nDescription
hFString = [hFString, sprintf('%s \n', [hStruct.detailedDescription{iDescription}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')]; % Empty line
%% Examples
hFString = [hFString, sprintf('%s \n', '__Example__:<BR>')];
if isfield(hStruct,'example')
nExamples = length(hStruct.example);
for iExamples = 1:nExamples
hFString = [hFString, sprintf('%s \n', [hStruct.example{iExamples}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')];
%% Known Bugs
hFString = [hFString, sprintf('%s \n', '__Known Bugs__:<BR>')];
if isfield(hStruct,'knownBugs')
nBugs = length(hStruct.knownBugs);
for iBugs = 1:nBugs
hFString = [hFString, sprintf('%s \n', [hStruct.knownBugs{iBugs}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')];
%% TODO list
hFString = [hFString, sprintf('%s \n', '__TODO__:<BR>')];
if isfield(hStruct,'toDo')
nToDo = length(hStruct.toDo);
for iToDo = 1:nToDo
hFString = [hFString, sprintf('%s \n', [hStruct.toDo{iToDo}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')];
%% References
hFString = [hFString, sprintf('%s \n', '__References__:<BR>')];
if isfield(hStruct,'references')
nRef = length(hStruct.references);
for iRef = 1:nRef
hFString = [hFString, sprintf('+ %s \n', [hStruct.references{iRef}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')];
%% Authors
hFString = [hFString, sprintf('%s \n', '__Authors__:<BR>')];
if isfield(hStruct,'authors')
nAuthors = length(hStruct.authors);
for iAuthors = 1:nAuthors
hFString = [hFString, sprintf('%s', [hStruct.authors{iAuthors}])];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString, sprintf('%s \n', ' ')];
hFString = [hFString, sprintf('%s \n', '<BR><BR>')];
%% Copyright note
hFString = [hFString, sprintf('%s \n', '__Copyright Note__:')];
cprNote = CGen.generatecopyrightnote;
cprNote = regexprep(cprNote, '%', ' ');
cprNote = regexprep(cprNote, 'Copyright', '<BR>Copyright ');
hFString = [hFString,cprNote];
hFString = [hFString,sprintf('%s\n','*/')];
hFString = [hFString, sprintf('%s \n', ' ')]; % Empty line
hFString = [hFString,sprintf('%s\n',['/*!\fn ',hStruct.calls])];
%% Explanation of the Inputs
if isfield(hStruct,'inputs')
nInputs = length(hStruct.inputs);
for iInputs = 1:nInputs
hFString = [hFString, sprintf('\\param %s\n', hStruct.inputs{iInputs})];
end
else
hFString = [hFString, sprintf('%s \n', '')];
end
%% Explanation of the Outputs
if isfield(hStruct,'outputs')
nOutputs = length(hStruct.outputs);
for iOutputs = 1:nOutputs
hFString = [hFString, sprintf('\\param %s\n', hStruct.outputs{iOutputs})];
end
else
hFString = [hFString, sprintf('%s \n', ' ')];
end
hFString = [hFString,sprintf('%s\n','*/')];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
finsertfront.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/finsertfront.m
| 2,406 |
utf_8
|
9b6cb8a19f152fb355999afdaa253882
|
%CODEGENERATOR.FINSERTFRONT Insert a string at the beginning of a textfile.
%
% cGen.finsertfront(FNAME,NTEXT)
% FNAME is the full or relative path to the text file.
% NTEXT is the string containing the text to be inserted at the beginning
% of the file.
%
% Notes::
% MatLab ships with functions for reading, overwriting and appending text
% to files. This function is used to insert text at the beginning of a
% text file.
%
% Authors::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator.ffindreplace.
% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = finsertfront(CGen, fName,nText)
%% analyse the file
fid = fopen(fName,'r'); % open the file
% determine number of lines in the file
nLines = getNLines(fid);
% read all lines to cell
oldLines = cell(1,nLines);
for iLines = 1:nLines
oldLines{iLines} = fgets(fid);
end
% close the file again
fclose(fid);
%% rewrite the file
fid = fopen(fName,'w');
fprintf(fid,'%s',nText);
for iLines = 1:nLines
fprintf(fid,'%s',oldLines{iLines});
end
fclose(fid);
end
%% Determine the number of lines in a file
function [nLines] = getNLines(fid)
nLines = 0;
while (~feof(fid)) % go through each line until eof is reached
fgets(fid);
nLines = nLines +1; % increment line counter
end
frewind(fid); % set file indicator back to the beginning of the file
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
constructheaderstring.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@CodeGenerator/private/constructheaderstring.m
| 7,035 |
utf_8
|
3d9e9ae8d5e39a036b9315489ef211bb
|
%CODEGENERATOR.CONSTRUCTHEADERSTRING Creates common toolbox header string.
%
% HFSTRING = CGen.constructheaderstring(HSTRUCT) is the formatted header
% string.
% HSTRUCT is the geader content struct
%
% Notes::
% The contents of the header are coded in a struct that is the input
% parameter and has the following self-explaining fields:
% Fieldname Datatype
% - funName 'string'
% - shortDescription 'string'
% - detailedDescription {'line1','line2',...}
% - inputs {'input1: description','input2: description',...}
% - outputs {'output1: description','output2: description',...}
% - examples {'line1','line2',...}
% - knownBugs {'line1','line2',...}
% - toDO {'line1','line2',...}
% - references {'line1','line2',...}
% - authors {'line1','line2',...}
% - seeAlso {'function1','function2',...}
%
% Example::
% hStruct.funName = 'myFirstFunction';
% hStruct.shortDescription = ['Just an example!'];
% hStruct.calls = {'result = myFirstFunction(A,B)'};
% constructheaderstring(hStruct)
%
% Authors::
% Joern Malzahn ([email protected])
%
% See also CodeGenerator.replaceheader, sprintf.
% Copyright (C) 1993-2014, by Peter I. Corke
% Copyright (C) 2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [hFString] = constructheaderstring(CGen,hStruct)
if isfield(hStruct,'funName') && isfield(hStruct,'shortDescription')
hFString = [];
hFString = [hFString, sprintf('%s \n',['%% ',upper(hStruct.funName),' - ', hStruct.shortDescription, ''])];
hFString = [hFString, sprintf('%s \n', '% =========================================================================')];
hFString = [hFString, sprintf('%s \n', '% ')];
else
error('Header must include the function name and provide a short description!')
end
%% Possible Function calls
if isfield(hStruct,'calls')
nCalls = length(hStruct.calls);
for iCall = 1:nCalls
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.calls{iCall}])];
end
else
error('Header must provide function call information!')
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Detailed description
hFString = [hFString, sprintf('%s \n', '% Description::')];
if isfield(hStruct,'detailedDescription')
nDescription = length(hStruct.detailedDescription);
for iDescription = 1:nDescription
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.detailedDescription{iDescription}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Explanation of the Inputs
hFString = [hFString, sprintf('%s \n', '% Input::')];
if isfield(hStruct,'inputs')
nInputs = length(hStruct.inputs);
for iInputs = 1:nInputs
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.inputs{iInputs}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Explanation of the Outputs
hFString = [hFString, sprintf('%s \n', '% Output::')];
if isfield(hStruct,'outputs')
nOutputs = length(hStruct.outputs);
for iOutputs = 1:nOutputs
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.outputs{iOutputs}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Examples
hFString = [hFString, sprintf('%s \n', '% Example::')];
if isfield(hStruct,'example')
nExamples = length(hStruct.example);
for iExamples = 1:nExamples
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.example{iExamples}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Known Bugs
hFString = [hFString, sprintf('%s \n', '% Known Bugs::')];
if isfield(hStruct,'knownBugs')
nBugs = length(hStruct.knownBugs);
for iBugs = 1:nBugs
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.knownBugs{iBugs}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% TODO list
hFString = [hFString, sprintf('%s \n', '% TODO::')];
if isfield(hStruct,'toDo')
nToDo = length(hStruct.toDo);
for iToDo = 1:nToDo
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.toDo{iToDo}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% References
hFString = [hFString, sprintf('%s \n', '% References::')];
if isfield(hStruct,'references')
nRef = length(hStruct.references);
for iRef = 1:nRef
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.references{iRef}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% Authors
hFString = [hFString, sprintf('%s \n', '% Authors::')];
if isfield(hStruct,'authors')
nAuthors = length(hStruct.authors);
for iAuthors = 1:nAuthors
hFString = [hFString, sprintf('%s \n', ['% ',hStruct.authors{iAuthors}])];
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
%% See also
hFString = [hFString, sprintf('%s ', '% See also')];
if isfield(hStruct,'seeAlso')
nAlso = length(hStruct.seeAlso);
for iAlso = 1:nAlso
hFString = [hFString, sprintf('%s', hStruct.seeAlso{iAlso})];
if iAlso < nAlso
hFString = [hFString, sprintf('%s', ', ')];
else
hFString = [hFString, sprintf('%s\n', '.')];
end
end
else
hFString = [hFString, sprintf('%s \n', '% ---')];
end
hFString = [hFString, sprintf('%s \n', '% ')];
hFString = [hFString, sprintf('%s \n', ' ')];
%% Copyright note
hFString = [hFString,CGen.generatecopyrightnote];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
SerialLink.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/SerialLink.m
| 42,158 |
utf_8
|
b461733844a23ff0905fde5becd05682
|
%SerialLink Serial-link robot class
%
% A concrete class that represents a serial-link arm-type robot. Each link
% and joint in the chain is described by a Link-class object using Denavit-Hartenberg
% parameters (standard or modified).
%
% Constructor methods::
% SerialLink general constructor
% L1+L2 construct from Link objects
%
% Display/plot methods::
% animate animate robot model
% display print the link parameters in human readable form
% dyn display link dynamic parameters
% edit display and edit kinematic and dynamic parameters
% getpos get position of graphical robot
% plot display graphical representation of robot
% plot3d display 3D graphical model of robot
% teach drive the graphical robot
%
% Testing methods::
% islimit test if robot at joint limit
% isconfig test robot joint configuration
% issym test if robot has symbolic parameters
% isprismatic index of prismatic joints
% isrevolute index of revolute joints
% isspherical test if robot has spherical wrist
% isdh test if robot has standard DH model
% ismdh test if robot has modified DH model
%
% Conversion methods::
% char convert to string
% sym convert to symbolic parameters
% todegrees convert joint angles to degrees
% toradians convert joint angles to radians
% Kinematic methods::
% A link transforms
% fkine forward kinematics
% ikine6s inverse kinematics for 6-axis spherical wrist revolute robot
% ikine inverse kinematics using iterative numerical method
% ikunc inverse kinematics using optimisation
% ikcon inverse kinematics using optimisation with joint limits
% ikine_sym analytic inverse kinematics obtained symbolically
% trchain forward kinematics as a chain of elementary transforms
% DH convert modified DH model to standard
% MDH convert standard DH model to modified
% twists joint axis twists
%
% Velocity kinematic methods::
% fellipse display force ellipsoid
% jacob0 Jacobian matrix in world frame
% jacobe Jacobian matrix in end-effector frame
% jacob_dot Jacobian derivative
% maniplty manipulability
% vellipse display velocity ellipsoid
% qmincon null space motion to centre joints between limits
%
% Dynamics methods::
% accel joint acceleration
% cinertia Cartesian inertia matrix
% coriolis Coriolis joint force
% fdyn forward dynamics
% friction friction force
% gravjac gravity load and Jacobian
% gravload gravity joint force
% inertia joint inertia matrix
% itorque inertial torque
% jointdynamics model of LTI joint dynamics
% nofriction set friction parameters to zero
% perturb randomly perturb link dynamic parameters
% rne inverse dynamics
%-
% pay payload effect
% payload add a payload in end-effector frame
% gravjac gravity load and Jacobian
% paycap payload capacity
%
% Operation methods::
% jtraj joint space trajectory
% gencoords symbolic generalized coordinates
% genforces symbolic generalized forces
%
% Properties (read/write)::
% links vector of Link objects (1xN)
% gravity direction of gravity [gx gy gz]
% base pose of robot's base (4x4 homog xform)
% tool robot's tool transform, T6 to tool tip (4x4 homog xform)
% qlim joint limits, [qmin qmax] (Nx2)
% offset kinematic joint coordinate offsets (Nx1)
% name name of robot, used for graphical display
% manuf annotation, manufacturer's name
% comment annotation, general comment
% plotopt options for plot() method (cell array)
% fast use MEX version of RNE. Can only be set true if the mex
% file exists. Default is true.
%
% Properties (read only)::
% n number of joints
% config joint configuration string, eg. 'RRRRRR'
% mdh kinematic convention boolean (0=DH, 1=MDH)
% theta kinematic: joint angles (1xN)
% d kinematic: link offsets (1xN)
% a kinematic: link lengths (1xN)
% alpha kinematic: link twists (1xN)
%
% Overloaded operators::
% R+L append a Link object to a SerialLink manipulator
% R1*R2 concatenate two SerialLink manipulators R1 and R2
%
% Note::
% - SerialLink is a reference object.
% - SerialLink objects can be used in vectors and arrays
%
% Reference::
% - Robotics, Vision & Control, Chaps 7-9,
% P. Corke, Springer 2011.
% - Robot, Modeling & Control,
% M.Spong, S. Hutchinson & M. Vidyasagar, Wiley 2006.
%
% See also Link, DHFactor.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% TODO:
% fix payload as per GG discussion
% if we subclass mixin.Copyable there are problem with
%subclass constructures...
classdef SerialLink < handle & dynamicprops % & matlab.mixin.Copyable
properties
name
gravity
base
tool
manufacturer
comment
plotopt % options for the plot method, follow plot syntax
fast % mex version of rne detected
interface % interface to a real robot platform
ikineType
trail % to support trail option
% to support plot method
movie
delay
loop
% to support plot3d method
model3d
faces
points
plotopt3d % options for the plot3d method, follow plot3d syntax
end
events
Moved
end
properties (SetAccess = private)
% needs to be public readable for access by MEX file
n
links
T
mdh
end
properties (Dependent = true, SetAccess = private)
config
end
properties (Dependent = true)
offset
qlim
d
a
alpha
theta
end
methods
function r = SerialLink(varargin)
%SerialLink Create a SerialLink robot object
%
% R = SerialLink(LINKS, OPTIONS) is a robot object defined by a vector
% of Link class objects which includes the subclasses Revolute,
% Prismatic, RevoluteMDH or PrismaticMDH.
%
% R = SerialLink(OPTIONS) is a null robot object with no links.
%
% R = SerialLink([R1 R2 ...], OPTIONS) concatenate robots, the base of
% R2 is attached to the tip of R1. Can also be written as R1*R2 etc.
%
% R = SerialLink(R1, options) is a deep copy of the robot object R1,
% with all the same properties.
%
% R = SerialLink(DH, OPTIONS) is a robot object with kinematics defined by
% the matrix DH which has one row per joint and each row is [theta d a
% alpha] and joints are assumed revolute. An optional fifth column sigma
% indicate revolute (sigma=0) or prismatic (sigma=1). An optional sixth
% column is the joint offset.
%
% Options::
%
% 'name',NAME set robot name property to NAME
% 'comment',COMMENT set robot comment property to COMMENT
% 'manufacturer',MANUF set robot manufacturer property to MANUF
% 'base',T set base transformation matrix property to T
% 'tool',T set tool transformation matrix property to T
% 'gravity',G set gravity vector property to G
% 'plotopt',P set default options for .plot() to P
% 'plotopt3d',P set default options for .plot3d() to P
% 'nofast' don't use RNE MEX file
% 'configs',P provide a cell array of predefined
% configurations, as name, value pairs
%
% Examples::
%
% Create a 2-link robot
% L(1) = Link([ 0 0 a1 pi/2], 'standard');
% L(2) = Link([ 0 0 a2 0], 'standard');
% twolink = SerialLink(L, 'name', 'two link');
%
% Create a 2-link robot (most descriptive)
% L(1) = Revolute('d', 0, 'a', a1, 'alpha', pi/2);
% L(2) = Revolute('d', 0, 'a', a2, 'alpha', 0);
% twolink = SerialLink(L, 'name', 'two link');
%
% Create a 2-link robot (least descriptive)
% twolink = SerialLink([0 0 a1 0; 0 0 a2 0], 'name', 'two link');
%
% Robot objects can be concatenated in two ways
% R = R1 * R2;
% R = SerialLink([R1 R2]);
%
% Note::
% - SerialLink is a reference object, a subclass of Handle object.
% - SerialLink objects can be used in vectors and arrays
% - Link subclass elements passed in must be all standard, or all modified,
% DH parameters.
% - When robots are concatenated (either syntax) the intermediate base and
% tool transforms are removed since general constant transforms cannot
% be represented in Denavit-Hartenberg notation.
%
% See also Link, Revolute, Prismatic, RevoluteMDH, PrismaticMDH, SerialLink.plot.
r.links = [];
r.n = 0;
% default properties
default.name = 'noname';
default.comment = '';
default.manufacturer = '';
default.base = eye(4,4);
default.tool = eye(4,4);
default.gravity = [0; 0; 9.81];
% process the rest of the arguments in key, value pairs
opt.name = [];
opt.comment = [];
opt.manufacturer = [];
opt.base = [];
opt.tool = [];
opt.gravity = [];
opt.offset = [];
opt.qlim = [];
opt.plotopt = {};
opt.plotopt3d = {};
opt.ikine = [];
opt.fast = r.fast;
opt.modified = false;
opt.configs = [];
[opt,arg] = tb_optparse(opt, varargin);
if length(arg) == 1
% at least one argument, either a robot or link array
L = arg{1};
if isa(L, 'Link')
% passed an array of Link objects
r.links = L;
elseif numcols(L) >= 4 && (isa(L, 'double') || isa(L, 'sym'))
% passed a legacy DH matrix
dh_dyn = L;
clear L
for j=1:numrows(dh_dyn)
if opt.modified
L(j) = Link(dh_dyn(j,:), 'modified');
else
L(j) = Link(dh_dyn(j,:));
end
end
r.links = L;
elseif isa(L, 'SerialLink')
% passed a SerialLink object
if length(L) == 1
% clone the passed robot and the attached links
copy(r, L);
r.links = copy(L.links);
default.name = [L.name ' copy'];
else
% compound the robots in the vector
copy(r, L(1));
for k=2:length(L)
r.links = [r.links copy(L(k).links)];
r.name = [r.name '+' L(k).name];
end
r.tool = L(end).tool; % tool of composite robot from the last one
r.gravity = L(1).gravity; % gravity of composite robot from the first one
end
else
error('unknown type passed to robot');
end
r.n = length(r.links);
end
% set properties of robot object from passed options or defaults
for p=properties(r)'
p = p{1}; % property name
if isfield(opt, p) && ~isempty( opt.(p) )
% if there's a set option, override what's in the robot
r.(p) = opt.(p);
end
if isfield(default, p) && isempty( r.(p) )
% otherwise if there's a set default, use that
r.(p) = default.(p);
end
end
% other properties
if exist('frne') == 3
r.fast = true;
else
r.fast = false;
end
r.ikineType = opt.ikine;
r.gravity = r.gravity(:);
assert(length(r.gravity) == 3, 'RTB:SerialLink:badarg', 'gravity must be a 3-vector');
% set the robot object mdh status flag
if ~isempty(r.links)
mdh = [r.links.mdh];
if all(mdh == 0)
r.mdh = mdh(1);
elseif all (mdh == 1)
r.mdh = mdh(1);
else
error('RTB:SerialLink:badarg', 'robot has mixed D&H links conventions');
end
end
if ~isempty(opt.configs)
% add passed configurations as dynamic properties of the robot
for i=1:2:length(opt.configs)
name = opt.configs{i}; val = opt.configs{i+1};
assert(ischar(name), 'configs: expecting a char array')
assert(isnumeric(val) && length(val) == length(r.links), 'configs: expecting a n-vector');
addprop(r, name);
r.(name) = val;
end
end
end
%{
function delete(r)
disp('in destructor');
if ~isempty(r.teachfig)
delete(r.teachfig);
end
rh = findobj('Tag', r.name);
for f=rh
delete(f);
end
end
%}
function copy(out, in)
C = metaclass(in);
P = C.Properties;
for k=1:length(P)
if ~P{k}.Dependent
out.(P{k}.Name) = in.(P{k}.Name);
end
end
end
function r2 = plus(R, L)
%SerialLink.plus Append a link objects to a robot
%
% R+L is a SerialLink object formed appending a deep copy of the Link L to the SerialLink
% robot R.
%
% Notes::
% - The link L can belong to any of the Link subclasses.
% - Extends to arbitrary number of objects, eg. R+L1+L2+L3+L4.
%
% See also Link.plus.
assert( isa(L, 'Link'), 'RTB:SerialLink: second operand for + operator must be a Link class');
R.links = [R.links L];
r2 = R;
r2.n = length(R.links);
end
function r2 = mtimes(r, l)
%SerialLink.mtimes Concatenate robots
%
% R = R1 * R2 is a robot object that is equivalent to mechanically attaching
% robot R2 to the end of robot R1.
%
% Notes::
% - If R1 has a tool transform or R2 has a base transform these are
% discarded since DH convention does not allow for general intermediate
% transformations.
if isa(l, 'SerialLink')
r2 = SerialLink([r l]);
elseif isa(l, 'Link')
r2 = SerialLink(r);
r2.links = [r2.links l];
r2.n = length(r2.links);
end
end
function display(r)
%SerialLink.display Display parameters
%
% R.display() displays the robot parameters in human-readable form.
%
% Notes::
% - This method is invoked implicitly at the command line when the result
% of an expression is a SerialLink object and the command has no trailing
% semicolon.
%
% See also SerialLink.char, SerialLink.dyn.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
if loose
disp(' ');
end
disp(char(r))
if loose
disp(' ');
end
end
function s = char(robot)
%SerialLink.char Convert to string
%
% S = R.char() is a string representation of the robot's kinematic parameters,
% showing DH parameters, joint structure, comments, gravity vector, base and
% tool transform.
s = '';
for j=1:length(robot)
r = robot(j);
% informational line
info = '';
if r.mdh
info = strcat(info, 'modDH');
else
info = strcat(info, 'stdDH');
end
if r.fast
info = strcat(info, ', fastRNE');
else
info = strcat(info, ', slowRNE');
end
if r.issym
info = strcat(info, ', Symbolic');;
end
manuf = '';
if ~isempty(r.manufacturer)
manuf = [' [' r.manufacturer ']'];
end
s = sprintf('%s%s:: %d axis, %s, %s', r.name, manuf, r.n, r.config, info);
% comment and other info
line = '';
% if ~isempty(r.manufacturer)
% line = strcat(line, sprintf(' from %s;', r.manufacturer));
% end
if ~isempty(r.comment)
line = strcat(line, sprintf(' - %s;', r.comment));
end
if ~isempty(line)
s = char(s, line);
end
% link parameters
s = char(s, '+---+-----------+-----------+-----------+-----------+-----------+');
s = char(s, '| j | theta | d | a | alpha | offset |');
s = char(s, '+---+-----------+-----------+-----------+-----------+-----------+');
s = char(s, char(r.links, true));
s = char(s, '+---+-----------+-----------+-----------+-----------+-----------+');
% gravity, base, tool
% s_grav = horzcat(char('grav = ', ' ', ' '), mat2str(r.gravity'));
% s_grav = char(s_grav, ' ');
% s_base = horzcat(char(' base = ',' ',' ', ' '), mat2str(r.base));
%
% s_tool = horzcat(char(' tool = ',' ',' ', ' '), mat2str(r.tool));
%
% line = horzcat(s_grav, s_base, s_tool);
%s = char(s, sprintf('gravity: (%g, %g, %g)', r.gravity));
if ~isidentity(r.base)
s = char(s, ['base: ' trprint(r.base.T, 'xyz')]);
end
if ~isidentity(r.tool)
s = char(s, ['tool: ' trprint(r.tool.T, 'xyz')]);
end
if j ~= length(robot)
s = char(s, ' ');
end
end
end
function T = A(r, joints, q)
%SerialLink.A Link transformation matrices
%
% S = R.A(J, Q) is an SE3 object (4x4) that transforms between link frames
% for the J'th joint. Q is a vector (1xN) of joint variables. For:
% - standard DH parameters, this is from frame {J-1} to frame {J}.
% - modified DH parameters, this is from frame {J} to frame {J+1}.
%
% S = R.A(JLIST, Q) as above but is a composition of link transform
% matrices given in the list JLIST, and the joint variables are taken from
% the corresponding elements of Q.
%
% Exmaples::
% For example, the link transform for joint 4 is
% robot.A(4, q4)
%
% The link transform for joints 3 through 6 is
% robot.A(3:6, q)
% where q is 1x6 and the elements q(3) .. q(6) are used.
%
% Notes::
% - Base and tool transforms are not applied.
%
% See also Link.A.
T = SE3;
for joint=joints
T = T * r.links(joint).A(q(joint));
end
end
function q = getpos(robot)
%SerialLink.getpos Get joint coordinates from graphical display
%
% q = R.getpos() returns the joint coordinates set by the last plot or
% teach operation on the graphical robot.
%
% See also SerialLink.plot, SerialLink.teach.
rhandles = findobj('Tag', robot.name);
% find the graphical element of this name
if isempty(rhandles)
error('RTB:getpos:badarg', 'No graphical robot of this name found');
end
% get the info from its Userdata
info = get(rhandles(1), 'UserData');
% the handle contains current joint angles (set by plot)
if ~isempty(info.q)
q = info.q;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set/get methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function set.tool(r, v)
if isempty(v)
r.base = SE(3);
else
r.tool = SE3(v);
end
end
function set.fast(r,v)
if v && exist('frne') == 3
r.fast = true;
else
r.fast = false;
end
end
function set.base(r, v)
if isempty(v)
r.base = SE3();
else
r.base = SE3(v);
end
end
function v = get.d(r)
v = [r.links.d];
end
function v = get.a(r)
v = [r.links.a];
end
function v = get.theta(r)
v = [r.links.theta];
end
function v = get.alpha(r)
v = [r.links.alpha];
end
function set.offset(r, v)
if length(v) ~= length(v)
error('offset vector length must equal number DOF');
end
L = r.links;
for i=1:r.n
L(i).offset = v(i);
end
r.links = L;
end
function v = get.offset(r)
v = [r.links.offset];
end
function set.qlim(r, v)
if numrows(v) ~= r.n
error('insufficient rows in joint limit matrix');
end
L = r.links;
for i=1:r.n
L(i).qlim = v(i,:);
end
r.links = L;
end
function v = get.qlim(r)
L = r.links;
v = zeros(r.n, 2);
for i=1:r.n
if isempty(L(i).qlim)
if L(i).isrevolute
v(i,:) = [-pi pi];
else
v(i,:) = [-Inf Inf];
end
else
v(i,:) = L(i).qlim;
end
end
end
function set.gravity(r, v)
if isvec(v, 3)
r.gravity = v(:);
else
error('gravity must be a 3-vector');
end
end
function v = get.config(r)
%SerialLink.config Returnt the joint configuration string
v = '';
for i=1:r.n
v(i) = r.links(i).type;
end
end
% general methods
function v = configstr(r)
%SerialLink.configstr
%
% V = R.configstr is a string describing the joint types and successive
% joint relative orientation. The symbol R is used to denote a revolute
% joint and P for a prismatic joint. The symbol between these letters
% indicates whether the adjacent joints are parallel or orthogonal.
%
% See also: SerialLink.config.
v = '';
for i=1:r.n
v = [v r.links(i).type];
if i < r.n
if r.links(i).alpha == 0
v = [v char(hex2dec('007c'))]; % pipe
elseif abs(abs(r.links(i).alpha) - pi/2) < 1*eps
v = [v char(hex2dec('27c2'))]; % perp
else
v = [v '?'];
end
end
end
end
function v = islimit(r,q)
%SerialLink.islimit Joint limit test
%
% V = R.islimit(Q) is a vector of boolean values, one per joint,
% false (0) if Q(i) is within the joint limits, else true (1).
%
% Notes::
% - Joint limits are not used by many methods, exceptions being:
% - ikcon() to specify joint constraints for inverse kinematics.
% - by plot() for prismatic joints to help infer the size of the
% workspace
%
% See also Link.islimit.
L = r.links;
if length(q) ~= r.n
error('argument for islimit method is wrong length');
end
v = zeros(r.n, 2);
for i=1:r.n
v(i,:) = L(i).islimit(q(i));
end
end
function v = isspherical(r)
%SerialLink.isspherical Test for spherical wrist
%
% R.isspherical() is true if the robot has a spherical wrist, that is, the
% last 3 axes are revolute and their axes intersect at a point.
%
% See also SerialLink.ikine6s.
L = r.links(end-2:end);
alpha = [-pi/2 pi/2];
v = all([L(1:2).a] == 0) && ...
(L(2).d == 0) && ...
(all([L(1:2).alpha] == alpha) || all([L(1:2).alpha] == -alpha)) && ...
all([L(1:3).isrevolute]);
end
function v = isconfig(r, s)
%SerialLink.isconfig Test for particular joint configuration
%
% R.isconfig(s) is true if the robot has the joint configuration string
% given by the string s.
%
% Example:
% robot.isconfig('RRRRRR');
%
% See also SerialLink.config.
v = strcmpi(r.config, s);
end
function payload(r, m, p)
%SerialLink.payload Add payload mass
%
% R.payload(M, P) adds a payload with point mass M at position P
% in the end-effector coordinate frame.
%
% R.payload(0) removes added payload
%
% Notes::
% - An added payload will affect the inertia, Coriolis and gravity terms.
% - Sets, rather than adds, the payload. Mass and CoM of the last link is
% overwritten.
%
% See also SerialLink.rne, SerialLink.gravload.
lastlink = r.links(r.n);
if nargin == 3
lastlink.m = m;
lastlink.r = p;
elseif nargin == 2 && m == 0
% clear/reset the payload
lastlink.m = m;
end
end
function t = jointdynamics(robot, q, qd)
%SerialLink.jointdyamics Transfer function of joint actuator
%
% TF = R.jointdynamic(Q) is a vector of N continuous-time transfer function
% objects that represent the transfer function 1/(Js+B) for each joint
% based on the dynamic parameters of the robot and the configuration Q
% (1xN). N is the number of robot joints.
%
% % TF = R.jointdynamic(Q, QD) as above but include the linearized effects
% of Coulomb friction when operating at joint velocity QD (1xN).
%
% Notes::
% - Coulomb friction is ignoredf.
%
% See also tf, SerialLink.rne.
for j=1:robot.n
link = robot.links(j);
% compute inertia for this joint
zero = zeros(1, robot.n);
qdd = zero; qdd(j) = 1;
M = robot.rne(q, zero, qdd, 'gravity', [0 0 0]);
J = link.Jm + M(j)/abs(link.G)^2;
% compute friction
B = link.B;
if nargin == 3
% add linearized Coulomb friction at the operating point
if qd > 0
B = B + link.Tc(1)/qd(j);
elseif qd < 0
B = B + link.Tc(2)/qd(j);
end
end
t(j) = tf(1, [J B]);
end
end
function jt = jtraj(r, T1, T2, t, varargin)
%SerialLink.jtraj Joint space trajectory
%
% Q = R.jtraj(T1, T2, K, OPTIONS) is a joint space trajectory (KxN) where
% the joint coordinates reflect motion from end-effector pose T1 to T2 in K
% steps, where N is the number of robot joints. T1 and T2 are SE3 objects or homogeneous transformation
% matrices (4x4). The trajectory Q has one row per time step, and one
% column per joint.
%
% Options::
% 'ikine',F A handle to an inverse kinematic method, for example
% F = @p560.ikunc. Default is ikine6s() for a 6-axis spherical
% wrist, else ikine().
%
% Notes::
% - Zero boundary conditions for velocity and acceleration are assumed.
% - Additional options are passed as trailing arguments to the
% inverse kinematic function, eg. configuration options like 'ru'.
%
% See also jtraj, SerialLink.ikine, SerialLink.ikine6s.
if r.isspherical && (r.n == 6)
opt.ikine = @r.ikine6s;
else
opt.ikine = @r.ikine;
end
[opt,args] = tb_optparse(opt, varargin);
q1 = opt.ikine(T1, args{:});
q2 = opt.ikine(T2, args{:});
jt = jtraj(q1, q2, t);
end
function dyn(r, j)
%SerialLink.dyn Print inertial properties
%
% R.dyn() displays the inertial properties of the SerialLink object in a multi-line
% format. The properties shown are mass, centre of mass, inertia, gear ratio,
% motor inertia and motor friction.
%
% R.dyn(J) as above but display parameters for joint J only.
%
% See also Link.dyn.
if nargin == 2
r.links(j).dyn()
else
r.links.dyn();
end
end
function sr = sym(r)
sr = SerialLink(r);
for i=1:r.n
sr.links(i) = r.links(i).sym;
end
end
function p = isprismatic(robot)
%SerialLink.isprismatic identify prismatic joints
%
% X = R.isprismatic is a list of logical variables, one per joint, true if
% the corresponding joint is prismatic, otherwise false.
%
% See also Link.isprismatic, SerialLink.isrevolute.
p = robot.links.isprismatic();
end
function p = isrevolute(robot)
%SerialLink.isrevolute identify revolute joints
%
% X = R.isrevolute is a list of logical variables, one per joint, true if
% the corresponding joint is revolute, otherwise false.
%
% See also Link.isrevolute, SerialLink.isprismatic.
p = robot.links.isrevolute();
end
function qdeg = todegrees(robot, q)
%SerialLink.todegrees Convert joint angles to degrees
%
% Q2 = R.todegrees(Q) is a vector of joint coordinates where those elements
% corresponding to revolute joints are converted from radians to degrees.
% Elements corresponding to prismatic joints are copied unchanged.
%
% See also SerialiLink.toradians.
k = robot.isrevolute;
qdeg = q;
qdeg(:,k) = qdeg(:,k) * 180/pi;
end
function qrad = toradians(robot, q)
%SerialLink.toradians Convert joint angles to radians
%
% Q2 = R.toradians(Q) is a vector of joint coordinates where those elements
% corresponding to revolute joints are converted from degrees to radians.
% Elements corresponding to prismatic joints are copied unchanged.
%
% See also SerialiLink.todegrees.
k = robot.isrevolute;
qrad = q;
qrad(:,k) = qrad(:,k) * pi/180;
end
function J = jacobn(robot, varargin)
warning('RTB:SerialLink:deprecated', 'Use jacobe instead of jacobn');
J = robot.jacobe(varargin{:});
end
function rmdh = MDH(r)
%SerialLink.MDH Convert standard DH model to modified
%
% rmdh = R.MDH() is a SerialLink object that represents the same kinematics
% as R but expressed using modified DH parameters.
%
% Notes::
% - can only be applied to a model expressed with standard DH parameters.
%
% See also: DH
assert(isdh(r), 'RTB:SerialLink:badmodel', 'this method can only be applied to a model with standard DH parameters');
% first joint
switch r.config(1)
case 'R'
link(1) = Link('modified', 'revolute', ...
'd', r.links(1).d, ...
'offset', r.links(1).offset, ...
'qlim', r.links(1).qlim );
case 'P'
link(1) = Link('modified', 'prismatic', ...
'theta', r.links(1).theta, ...
'offset', r.links(1).offset, ...
'qlim', r.links(1).qlim );
end
% middle joints
for i=2:r.n
switch r.config(i)
case 'R'
link(i) = Link('modified', 'revolute', ...
'a', r.links(i-1).a, ...
'alpha', r.links(i-1).alpha, ...
'd', r.links(i).d, ...
'offset', r.links(i).offset, ...
'qlim', r.links(i).qlim );
case 'P'
link(i) = Link('modified', 'prismatic', ...
'a', r.links(i-1).a, ...
'alpha', r.links(i-1).alpha, ...
'theta', r.links(i).theta, ...
'offset', r.links(i).offset, ...
'qlim', r.links(i).qlim );
end
end
% last joint
tool = SE3(r.links(r.n).a, 0, 0) * SE3.Rx(r.links(r.n).alpha) * r.tool;
rmdh = SerialLink(link, 'base', r.base, 'tool', tool);
end
function rdh = DH(r)
%SerialLink.DH Convert modified DH model to standard
%
% rmdh = R.DH() is a SerialLink object that represents the same kinematics
% as R but expressed using standard DH parameters.
%
% Notes::
% - can only be applied to a model expressed with modified DH parameters.
%
% See also: MDH
assert(ismdh(r), 'RTB:SerialLink:badmodel', 'this method can only be applied to a model with modified DH parameters');
base = r.base * SE3(r.links(1).a, 0, 0) * SE3.Rx(r.links(1).alpha);
% middle joints
for i=1:r.n-1
switch r.config(i)
case 'R'
link(i) = Link('standard', 'revolute', ...
'a', r.links(i+1).a, ...
'alpha', r.links(i+1).alpha, ...
'd', r.links(i).d, ...
'offset', r.links(i).offset, ...
'qlim', r.links(i).qlim );
case 'P'
link(i) = Link('standard', 'prismatic', ...
'a', r.links(i+1).a, ...
'alpha', r.links(i+1).alpha, ...
'theta', r.links(i).theta, ...
'offset', r.links(i).offset, ...
'qlim', r.links(i).qlim );
end
end
% last joint
switch r.config(r.n)
case 'R'
link(r.n) = Link('standard', 'revolute', ...
'd', r.links(r.n).d, ...
'offset', r.links(r.n).offset, ...
'qlim', r.links(r.n).qlim );
case 'P'
link(r.n) = Link('standard', 'prismatic', ...
'theta', r.links(r.n).theta, ...
'offset', r.links(r.n).offset, ...
'qlim', r.links(r.n).qlim );
end
rdh = SerialLink(link, 'base', base, 'tool', r.tool);
end
function [tw,T0] = twists(r, q)
%SerialLink.twists Joint axis twists
%
% [TW,T0] = R.twists(Q) is a vector of Twist objects (1xN) that represent
% the axes of the joints for the robot with joint coordinates Q (1xN). T0
% is an SE3 object representing the pose of the tool.
%
% [TW,T0] = R.twists() as above but the joint coordinates are taken to be
% zero.
%
% Notes::
% - [TW,T0] is the product of exponential representation of the robot's
% forward kinematics: prod( [TW.exp(Q) T0] )
%
% See also Twist.
if nargin < 2
q = zeros(1, r.n);
end
[Tn,T] = r.fkine( q );
if r.isdh
% DH case
for i=1:r.n
if i == 1
tw(i) = Twist( r.links(i).type, [0 0 1], [0 0 0]);
else
tw(i) = Twist( r.links(i).type, T(i-1).a, T(i-1).t);
end
end
else
% MDH case
for i=1:r.n
tw(i) = Twist( r.links(i).type, T(i).a, T(i).t);
end
end
if nargout > 1
T0 = Tn;
end
end
function v = ismdh(r)
%SerialLink.ismdh Test if SerialLink object has a modified DH model
%
% v = R.ismdh() is true if the SerialLink manipulator R has a modified DH model
%
% See also: isdh
v = logical(r.mdh);
end
function v = isdh(r)
%SerialLink.isdh Test if SerialLink object has a standard DH model
%
% v = R.isdh() is true if the SerialLink manipulator R has a standard DH model
%
% See also: ismdh
v = ~r.mdh;
end
end % methods
end % classdef
% utility function
function s = mat2str(m)
if isa(m, 'sym')
% turn a symbolic matrix into a string (it shouldnt be so hard)
ss = cell(size(m)); colwidth = zeros(1, numcols(m));
for j=1:numcols(m)
for i=1:numrows(m)
ss{i,j} = char(m(i,j));
colwidth(j) = max( colwidth(j), length(ss{i,j}));
end
end
s = '';
for i=1:numrows(m)
line = '';
for j=1:numcols(m)
% append the element with a blank
line = [line ' ' ss{i,j}];
% pad it out to column width
for k=0:colwidth(j)-length(ss{i,j})
line = [line ' '];
end
end
s = strvcat(s, line);
end
else
m(abs(m)<eps) = 0;
s = num2str(m);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
issym.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/issym.m
| 1,043 |
utf_8
|
1d11b932d09bfdcc039ecd115b9cd438
|
%SerialLink.issym Test if SerialLink object is a symbolic model
%
% res = R.issym() is true if the SerialLink manipulator R has symbolic parameters
%
%
% Authors::
% Joern Malzahn, ([email protected])
% Copyright (C) 1993-2015, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function res = issym(l)
res = issym(l.links(1));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
jacobe.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/jacobe.m
| 2,961 |
utf_8
|
afda232f238c1e331b26793f937144fa
|
%SerialLink.JACOBE Jacobian in end-effector frame
%
% JE = R.jacobe(Q, options) is the Jacobian matrix (6xN) for the robot in
% pose Q, and N is the number of robot joints. The manipulator Jacobian
% matrix maps joint velocity to end-effector spatial velocity V = JE*QD in
% the end-effector frame.
%
% Options::
% 'trans' Return translational submatrix of Jacobian
% 'rot' Return rotational submatrix of Jacobian
%
% Notes::
% - Was joacobn() is earlier version of the Toolbox.
% - This Jacobian accounts for a tool transform if one is set.
% - This Jacobian is often referred to as the geometric Jacobian.
% - Prior to release 10 this function was named jacobn.
%
% References::
% - Differential Kinematic Control Equations for Simple Manipulators,
% Paul, Shimano, Mayer,
% IEEE SMC 11(6) 1981,
% pp. 456-460
%
% See also SerialLink.jacob0, jsingu, delta2tr, tr2delta.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function J = jacobe(robot, q, varargin)
opt.trans = false;
opt.rot = false;
opt.deg = false;
opt = tb_optparse(opt, varargin);
if opt.deg
% in degrees mode, scale the columns corresponding to revolute axes
q = robot.toradians(q);
end
n = robot.n;
L = robot.links; % get the links
J = zeros(6, robot.n);
if isa(q, 'sym')
J = sym(J);
end
U = robot.tool;
for j=n:-1:1
if robot.mdh == 0
% standard DH convention
U = L(j).A(q(j)) * U;
end
UT = U.T;
if L(j).isrevolute
% revolute axis
d = [ -UT(1,1)*UT(2,4)+UT(2,1)*UT(1,4)
-UT(1,2)*UT(2,4)+UT(2,2)*UT(1,4)
-UT(1,3)*UT(2,4)+UT(2,3)*UT(1,4)];
delta = UT(3,1:3)'; % nz oz az
else
% prismatic axis
d = UT(3,1:3)'; % nz oz az
delta = zeros(3,1); % 0 0 0
end
J(:,j) = [d; delta];
if robot.mdh ~= 0
% modified DH convention
U = L(j).A(q(j)) * U;
end
end
if opt.trans
J = J(1:3,:);
elseif opt.rot
J = J(4:6,:);
end
if isa(J, 'sym')
J = simplify(J);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikunc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikunc.m
| 4,719 |
utf_8
|
1d82a041e3a282450a9a5b724446273a
|
%SerialLink.IKUNC Inverse manipulator by optimization without joint limits
%
% Q = R.ikunc(T, OPTIONS) are the joint coordinates (1xN) corresponding to
% the robot end-effector pose T which is an SE3 object or homogenenous
% transform matrix (4x4), and N is the number of robot joints. OPTIONS is
% an optional list of name/value pairs than can be passed to fminunc.
%
% Q = robot.ikunc(T, Q0, OPTIONS) as above but specify the
% initial joint coordinates Q0 used for the minimisation.
%
% [Q,ERR] = robot.ikunc(T,...) as above but also returns ERR which is the
% scalar final value of the objective function.
%
% [Q,ERR,EXITFLAG] = robot.ikunc(T,...) as above but also returns the
% status EXITFLAG from fminunc.
%
% [Q,ERR,EXITFLAG,OUTPUT] = robot.ikunc(T,...) as above but also returns the
% structure OUTPUT from fminunc which contains details about the optimization.
%
% Trajectory operation::
%
% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous transform
% sequence (4x4xM) then returns the joint coordinates corresponding to
% each of the transforms in the sequence. Q is MxN where N is the number
% of robot joints. The initial estimate of Q for each time step is taken as
% the solution from the previous time step.
%
% ERR and EXITFLAG are also Mx1 and indicate the results of optimisation
% for the corresponding trajectory step.
%
% Notes::
% - Requires fminunc from the MATLAB Optimization Toolbox.
% - Joint limits are not considered in this solution.
% - Can be used for robots with arbitrary degrees of freedom.
% - In the case of multiple feasible solutions, the solution returned
% depends on the initial choice of Q0
% - Works by minimizing the error between the forward kinematics of the
% joint angle solution and the end-effector frame as an optimisation.
% The objective function (error) is described as:
% sumsqr( (inv(T)*robot.fkine(q) - eye(4)) * omega )
% Where omega is some gain matrix, currently not modifiable.
%
% Author::
% Bryan Moutrie
%
% See also SerialLink.ikcon, fmincon, SerialLink.ikine, SerialLink.fkine.
% Copyright (C) Bryan Moutrie, 2013-2015
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with pHRIWARE. If not, see <http://www.gnu.org/licenses/>.
function [qstar, error, exitflag, output] = ikunc(robot, T, varargin)
% check if Optimization Toolbox exists, we need it
assert( exist('fminunc', 'file')>0, 'rtb:ikunc:nosupport', 'Optimization Toolbox required');
if isa(T, 'SE3')
T = T.T;
end
% create output variables
T_sz = size(T,3);
qstar = zeros(T_sz,robot.n);
error = zeros(T_sz,1);
exitflag = zeros(T_sz,1);
problem.solver = 'fminunc';
problem.x0 = zeros(1, robot.n);
problem.options = optimoptions('fminunc', ...
'Algorithm', 'quasi-newton', ...
'Display', 'off'); % default options for ikunc
if nargin > 2
% check if there is a q0 passed
if isnumeric(varargin{1}) && length(varargin{1}) == robot.n
problem.x0 = varargin{1};
varargin = varargin(2:end);
end
end
if ~isempty(varargin)
% if given, add optional argument to the list of optimiser options
problem.options = optimoptions(problem.options, varargin{:});
end
reach = sum(abs([robot.a, robot.d]));
omega = diag([1 1 1 3/reach]);
for t = 1:T_sz
problem.objective = ...
@(x) sumsqr(((T(:,:,t) \ robot.fkine(x).T) - eye(4)) * omega);
[q_t, err_t, ef_t, out_t] = fminunc(problem);
if ef_t ~= 1
if T_sz > 1
warning('step %d: errflag = %d, err = %f\n', t, ef_t, err_t);
else
warning('errflag = %d, err = %f\n', ef_t, err_t);
out_t
end
end
qstar(t,:) = q_t;
error(t) = err_t;
exitflag(t) = ef_t;
output(t) = out_t;
problem.x0 = q_t;
end
end
function s = sumsqr(A)
s = sum(A(:).^2);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plot.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/plot.m
| 18,142 |
utf_8
|
c8c9bbc9fb1aa83eea142f7ad9341924
|
%SerialLink.plot Graphical display and animation
%
% R.plot(Q, options) displays a graphical animation of a robot based on
% the kinematic model. A stick figure polyline joins the origins of
% the link coordinate frames. The robot is displayed at the joint angle Q (1xN), or
% if a matrix (MxN) it is animated as the robot moves along the M-point trajectory.
%
% Options::
% 'workspace', W Size of robot 3D workspace, W = [xmn, xmx ymn ymx zmn zmx]
% 'floorlevel',L Z-coordinate of floor (default -1)
%-
% 'delay',D Delay betwen frames for animation (s)
% 'fps',fps Number of frames per second for display, inverse of 'delay' option
% '[no]loop' Loop over the trajectory forever
% '[no]raise' Autoraise the figure
% 'movie',M Save an animation to the movie M
% 'trail',L Draw a line recording the tip path, with line style L.
% L can be a cell array, eg. {'r', 'LineWidth', 2}
%-
% 'scale',S Annotation scale factor
% 'zoom',Z Reduce size of auto-computed workspace by Z, makes
% robot look bigger
% 'ortho' Orthographic view
% 'perspective' Perspective view (default)
% 'view',V Specify view V='x', 'y', 'top' or [az el] for side elevations,
% plan view, or general view by azimuth and elevation
% angle.
% 'top' View from the top.
%-
% '[no]shading' Enable Gouraud shading (default true)
% 'lightpos',L Position of the light source (default [0 0 20])
% '[no]name' Display the robot's name
%-
% '[no]wrist' Enable display of wrist coordinate frame
% 'xyz' Wrist axis label is XYZ
% 'noa' Wrist axis label is NOA
% '[no]arrow' Display wrist frame with 3D arrows
%-
% '[no]tiles' Enable tiled floor (default true)
% 'tilesize',S Side length of square tiles on the floor
% 'tile1color',C Color of even tiles [r g b] (default [0.5 1 0.5] light green)
% 'tile2color',C Color of odd tiles [r g b] (default [1 1 1] white)
%-
% '[no]shadow' Enable display of shadow (default true)
% 'shadowcolor',C Colorspec of shadow, [r g b]
% 'shadowwidth',W Width of shadow line (default 6)
%-
% '[no]jaxes' Enable display of joint axes (default false)
% '[no]jvec' Enable display of joint axis vectors (default false)
% '[no]joints' Enable display of joints
% 'jointcolor',C Colorspec for joint cylinders (default [0.7 0 0])
% 'pjointcolor',C Colorspec for prismatic joint boxes (default [0.4 1 .03])
% 'jointdiam',D Diameter of joint cylinder in scale units (default 5)
%-
% 'linkcolor',C Colorspec of links (default 'b')
%-
% '[no]base' Enable display of base 'pedestal'
% 'basecolor',C Color of base (default 'k')
% 'basewidth',W Width of base (default 3)
%
% The options come from 3 sources and are processed in order:
% - Cell array of options returned by the function PLOTBOTOPT (if it exists)
% - Cell array of options given by the 'plotopt' option when creating the
% SerialLink object.
% - List of arguments in the command line.
%
% Many boolean options can be enabled or disabled with the 'no' prefix. The
% various option sources can toggle an option, the last value encountered is used.
%
% Graphical annotations and options::
%
% The robot is displayed as a basic stick figure robot with annotations
% such as:
% - shadow on the floor
% - XYZ wrist axes and labels
% - joint cylinders and axes
% which are controlled by options.
%
% The size of the annotations is determined using a simple heuristic from
% the workspace dimensions. This dimension can be changed by setting the
% multiplicative scale factor using the 'mag' option.
%
% Figure behaviour::
%
% - If no figure exists one will be created and the robot drawn in it.
% - If no robot of this name is currently displayed then a robot will
% be drawn in the current figure. If hold is enabled (hold on) then the
% robot will be added to the current figure.
% - If the robot already exists then that graphical model will be found
% and moved.
%
% Multiple views of the same robot::
%
% If one or more plots of this robot already exist then these will all
% be moved according to the argument Q. All robots in all windows with
% the same name will be moved.
%
% Create a robot in figure 1
% figure(1)
% p560.plot(qz);
% Create a robot in figure 2
% figure(2)
% p560.plot(qz);
% Now move both robots
% p560.plot(qn)
%
% Multiple robots in the same figure::
%
% Multiple robots can be displayed in the same plot, by using "hold on"
% before calls to robot.plot().
%
% Create a robot in figure 1
% figure(1)
% p560.plot(qz);
% Make a clone of the robot named bob
% bob = SerialLink(p560, 'name', 'bob');
% Draw bob in this figure
% hold on
% bob.plot(qn)
%
% To animate both robots so they move together:
% qtg = jtraj(qr, qz, 100);
% for q=qtg'
% p560.plot(q');
% bob.plot(q');
% end
%
% Making an animation::
%
% The 'movie' options saves the animation as a movie file or separate frames in a folder
% - 'movie','file.mp4' saves as an MP4 movie called file.mp4
% - 'movie','folder' saves as files NNNN.png into the specified folder
% - The specified folder will be created
% - NNNN are consecutive numbers: 0000, 0001, 0002 etc.
% - To convert frames to a movie use a command like:
% ffmpeg -r 10 -i %04d.png out.avi
%
% Notes::
% - The options are processed when the figure is first drawn, to make different options come
% into effect it is neccessary to clear the figure.
% - The link segments do not neccessarily represent the links of the robot, they are a pipe
% network that joins the origins of successive link coordinate frames.
% - Delay betwen frames can be eliminated by setting option 'delay', 0 or
% 'fps', Inf.
% - By default a quite detailed plot is generated, but turning off labels,
% axes, shadows etc. will speed things up.
% - Each graphical robot object is tagged by the robot's name and has UserData
% that holds graphical handles and the handle of the robot object.
% - The graphical state holds the last joint configuration
% - The size of the plot volume is determined by a heuristic for an all-revolute
% robot. If a prismatic joint is present the 'workspace' option is
% required. The 'zoom' option can reduce the size of this workspace.
%
% See also SerialLink.plot3d, plotbotopt, SerialLink.animate, SerialLink.teach.
% HANDLES:
%
% A robot comprises a bunch of individual graphical elements and these are
% kept in a structure:
%
% h.link the graphical elements that comprise each joint/link
% h.wrist the coordinate frame marking the wrist frame
% h.shadow the robot's shadow
% h.floorlevel the z-coordinate of the tiled floor
% h.robot pointer to the robot object
% h.opt the final options structure
%
% The h.link graphical element is tagged with the robot's name and has this
% struct as its UserData.
%
% h.links -> h -> robot
%
% This enables us to find all robots with a given name, in all figures,
% and update them.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% TODO
% deal with base transform and tool
% more consistent option names, scale, mag etc.
function plot(robot, qq, varargin)
% check the joint angle data matches the robot
n = robot.n;
assert(numcols(qq) == n, 'RTB:SerialLink:plot:badarg', 'Insufficient columns in q')
% process options, these come from:
% - passed arguments
% - the robot object itself
% - the file plotopt.m
opt = RTBPlot.plot_options(robot, varargin);
% logic to handle where the plot is drawn, are old figures updated or
% replaced?
% calls create_floor() and create_robot() as required.
if strcmp(get(gca,'Tag'), 'RTB.plot')
% this axis is an RTB plot window
rhandles = findobj('Tag', robot.name);
if isempty(rhandles)
% this robot doesnt exist here, create it or add it
if ishold
% hold is on, add the robot, don't change the floor
handle = create_robot(robot, opt);
% tag one of the graphical handles with the robot name and hang
% the handle structure off it
% set(handle.joint(1), 'Tag', robot.name);
% set(handle.joint(1), 'UserData', handle);
else
% create the robot and floor
newplot();
RTBPlot.create_floor(opt);
handle = create_robot(robot, opt);
set(gca, 'Tag', 'RTB.plot');
end
end
else
% this axis never had a robot drawn in it before, let's use it
RTBPlot.create_floor(opt);
handle = create_robot(robot, opt);
set(gca, 'Tag', 'RTB.plot');
set(gcf, 'Units', 'Normalized');
pf = get(gcf, 'Position');
% if strcmp( get(gcf, 'WindowStyle'), 'docked') == 0
% set(gcf, 'Position', [0.1 1-pf(4) pf(3) pf(4)]);
% end
end
% deal with a few options that need to be stashed in the SerialLink object
% movie mode has not already been flagged
if opt.movie
robot.movie = Animate(opt.movie);
end
robot.delay = opt.delay;
robot.loop = opt.loop;
if opt.raise
% note this is a very time consuming operation
figure(gcf);
end
if strcmp(opt.projection, 'perspective')
set(gca, 'Projection', 'perspective');
end
if isstr(opt.view)
switch opt.view
case 'top'
view(0, 90);
set(gca, 'OuterPosition', [-0.8 -0.8 2.5 2.5]);
case 'x'
view(0, 0);
case 'y'
view(90, 0)
otherwise
error('rtb:plot:badarg', 'view must be: x, y, top')
end
elseif isnumeric(opt.view) && length(opt.view) == 2
view(opt.view)
end
% enable mouse-based 3D rotation
rotate3d on
robot.trail = []; % clear the previous trail
robot.animate(qq);
if opt.movie
robot.movie.close();
end
end
% Create a new graphical robot in the current figure.
% Returns a structure of handles that describe the various graphical entities in the robot model
% Make extensive use of hgtransform, all entities are defined at the origin, then moved to their
% proper pose
%
% The graphical hiearchy is:
% hggroup: Tag = robot name
% hgtransform: Tag = 'link#'
%
% The top-level group has user data which is the handle structure.
function h = create_robot(robot, opt)
%disp('creating new robot');
links = robot.links;
s = opt.scale;
% create an axis
ish = ishold();
if ~ishold
% if hold is off, set the axis dimensions
axis(opt.workspace);
hold on
end
N = robot.n;
% create the base
if opt.base
bt = robot.base.t;
bt = [bt'; bt'];
bt(1,3) = opt.floorlevel;
line(bt(:,1), bt(:,2), bt(:,3), 'LineWidth', opt.basewidth, 'Color', opt.basecolor);
end
view(3)
% add the robot's name
if opt.name
b = robot.base.t;
bz = 0;
if opt.base
bz = 0.5*opt.floorlevel;
end
text(b(1), b(2)-s, bz, [' ' robot.name], 'FontAngle', 'italic', 'FontWeight', 'bold')
end
group = hggroup('Tag', robot.name);
h.group = group;
% create the graphical joint and link elements
for L=1:N
if opt.debug
fprintf('create graphics for joint %d\n', L);
end
% create the transform for displaying this element (joint cylinder + link)
h.link(L) = hgtransform('Tag', sprintf('link%d', L), 'Parent', group);
% create a joint cylinder
if opt.joints
% create the body of the joint
if links(L).isrevolute
RTBPlot.cyl('z', opt.jointdiam*s, opt.jointlen*s*[-1 1], opt.jointcolor, [], 'Parent', h.link(L));
else
% create an additional hgtransform for positioning and scaling the prismatic
% element. The element is created with unit length.
h.pjoint(L) = hgtransform('Tag', 'prismatic', 'Parent', h.link(L));
if links(L).mdh
% make the box extend in negative z-dir because scaling factor in animate
% must be positive
RTBPlot.box('z', s, [0 -1], opt.jointcolor, [], 'Parent', h.pjoint(L));
else
RTBPlot.box('z', s, [0 1], opt.jointcolor, [], 'Parent', h.pjoint(L));
end
end
end
% create the body of the link
% create elements to represent translation between joint frames, ie. the link itself.
% This is drawn to resemble orthogonal plumbing.
if robot.mdh
% modified DH convention
if L < N
A = links(L+1).A(0);
t = transl(A);
if t(1) ~= 0
RTBPlot.cyl('x', s, [s t(1)], opt.linkcolor, [], 'Parent', h.link(L));
end
if t(2) ~= 0
RTBPlot.cyl('y', s, [s t(2)], opt.linkcolor, [t(1) 0 0], 'Parent', h.link(L));
end
if t(3) ~= 0
RTBPlot.cyl('z', s, [s t(3)], opt.linkcolor, [t(1) t(2) 0], 'Parent', h.link(L));
end
end
else
% standard DH convention
if L > 1
Ainv = inv(links(L-1).A(0));
t = Ainv.t;
if t(1) ~= 0
RTBPlot.cyl('x', s, [0 t(1)], opt.linkcolor, [], 'Parent', h.link(L));
end
if t(2) ~= 0
RTBPlot.cyl('y', s, [s t(2)], opt.linkcolor, [t(1) 0 0], 'Parent', h.link(L));
end
if t(3) ~= 0
RTBPlot.cyl('z', s, [s t(3)], opt.linkcolor, [t(1) t(2) 0], 'Parent', h.link(L));
end
%line([0 t(1)]', [0 t(2)]', [0 t(3)]', 'Parent', h.link(L));
end
end
assert( ~(opt.jaxes && opt.jvec), 'RTB:plot:badopt', 'Can''t specify ''jaxes'' and ''jvec''')
% create the joint axis line
if opt.jaxes
line('XData', [0 0], ...
'YData', [0 0], ...
'ZData', 14*s*[-1 1], ...
'LineStyle', ':', 'Parent', h.link(L));
% create the joint axis label
text(0, 0, 14*s, sprintf('q%d', L), 'Parent', h.link(L))
end
% create the joint axis vector
if opt.jvec
daspect([1 1 1]);
ha = arrow3([0 0 -12*s], [0 0 15*s], 'c');
set(ha, 'Parent', h.link(L));
% create the joint axis label
text(0, 0, 20*s, sprintf(' q%d', L), 'Parent', h.link(L))
end
end
if opt.debug
fprintf('create graphics for tool\n');
end
% display the tool transform if it exists
h.link(N+1) = hgtransform('Tag', sprintf('link%d', N+1), 'Parent', group);
tool = SE3();
if ~robot.mdh
tool = links(L).A(0);
end
if ~isempty(robot.tool)
tool = tool * robot.tool;
end
Tinv = inv(tool);
t = Tinv.t;
if t(1) ~= 0
RTBPlot.cyl('x', s, [0 t(1)], 'r', [], 'Parent', h.link(N+1));
end
if t(2) ~= 0
RTBPlot.cyl('y', s, [s t(2)], 'r', [t(1) 0 0], 'Parent', h.link(N+1));
end
if t(3) ~= 0
RTBPlot.cyl('z', s, [s t(3)], 'r', [t(1) t(2) 0], 'Parent', h.link(N+1));
end
% display the wrist coordinate frame
if opt.wrist
if opt.arrow
% compute arrow3 scale factor...
ax = gca; d = [ax.XLim ax.YLim ax.ZLim];
d = norm( d(4:6)-d(1:3) ) / 72;
extra = {'arrow', 'width', 1.5*s/d};
else
extra = {};
end
h.wrist = trplot(eye(4,4), 'labels', upper(opt.wristlabel), ...
'rgb', 'length', opt.wristlen*s, extra{:});
else
h.wrist = [];
end
% display a shadow on the floor
if opt.shadow
% create the polyline which is the shadow on the floor
h.shadow = line('LineWidth', opt.shadowwidth, 'Color', opt.shadowcolor);
end
if ~isempty(opt.trail)
if iscell(opt.trail)
h.trail = plot(0, 0, opt.trail{:});
else
h.trail = plot(0, 0, opt.trail);
end
robot.trail = [];
end
% deal with some display options
if opt.shading
lighting gouraud
light('position', opt.lightpos)
end
xlabel('X')
ylabel('Y')
zlabel('Z')
grid on
% restore hold setting
if ~ish
hold off
end
h.floorlevel = opt.floorlevel;
h.robot = robot;
h.opt = opt;
% attach the handle structure to the top graphical element
set(group, 'UserData', h);
end
% draw a cylinder of radius r in the direction specified by ax, with an
% extent from extent(1) to extent(2)
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikine_sym.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikine_sym.m
| 16,660 |
utf_8
|
437cd4e4973950c9bd45c54904a8210f
|
%IKINE_SYM Symbolic inverse kinematics
%
% Q = R.IKINE_SYM(K, OPTIONS) is a cell array (Cx1) of inverse kinematic
% solutions of the SerialLink object ROBOT. The cells of Q represent the
% solutions for each joint, ie. Q{1} is the solution for joint 1. A
% cell may contain an array of solutions. The solution is expressed in terms
% of other joint angles and elements of the desired end-point pose which is
% represented by the symbolic matrix (3x4) with elements
% nx ox ax tx
% ny oy ay ty
% nz oz az tz
% where the first three columns specify orientation and the last column
% specifies translation.
%
% K <= N is the number of joint angles solved for.
%
% Options::
%
% 'file',F Write the solution to an m-file named F
% 'Tpost',T Add a symbolic 4x4 matrix T to the end of the chain
%
% Example::
%
% mdl_planar2
% sol = p2.ikine_sym(2);
% length(sol)
%
% q1 = sol{1} % are the solution for joint 1
% q2 = sol{2} % is the solution for joint 2
% length(q1)
% ans =
% 2 % there are 2 solutions for this joint
% q1(1) % one solution for q1
% q1(2); % the other solution for q1
%
% Notes::
% - ignores tool and base transforms.
%
% References::
% - Robot manipulators: mathematics, programming and control
% Richard Paul, MIT Press, 1981.
% - The kinematics of manipulators under computer control,
% D.L. Pieper, Stanford report AI 72, October 1968.
%
% Notes::
% - Requires the MATLAB Symbolic Math Toolbox.
% - This code is experimental and has a lot of diagnostic prints.
% - Based on the classical approach using Pieper's method.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function out = ikine_sym(robot, N, varargin)
%
% Given a robot model the following steps are performed:
% 1. Convert model to symbolic form
% 2. Find relevant trig equations and solve them for joint angles
% 3. Write an M-file to implement the solution
% xikine(T)
% xikine(T, S) where S is a 3 vector with elements 1 or 2 to select
% the first or second solution for the corresponding joint.
%
% TODO:
% - handle the wrist joints, only first 3 joints so far
% - handle base and tool transforms
% - allow 3DOF solution which is rotation, ie. wrist
opt.file = [];
opt.Tpost = [];
opt.all = false;
opt = tb_optparse(opt, varargin);
% make a symbolic representation of the passed robot
srobot = SerialLink(robot); % make a deep copy
srobot = sym(srobot); % convert to symbolic
q = srobot.gencoords();
% define symbolic elements of the homogeneous transform
syms nx ox ax tx real
syms ny oy ay ty real
syms nz oz az tz real
syms d4 real
% inits
Q = {};
trigsubOld = [];
trigsubNew = [];
% loop over each joint variable
for j=1:N
fprintf('----- solving for joint %d\n', j);
% create some equations to sift through
[left,right] = pieper(srobot, j, 'left', opt.Tpost);
% decide which equations to look at
if j <= 3
% for first three joints only focus on translational part
left = left(1:3, 4); left = left(:);
right = right(1:3, 4); right = right(:);
else
% for last three joints only focus on rotational part
left = left(1:3, 1:3); left = left(:);
right = right(1:3, 1:3); right = right(:);
end
% substitute sin/cos for preceding joint as Sj/Cj, essentially removes
% the joint variables from the equations and treats them as constants.
if ~isempty(trigsubOld)
left = rsubs(left, trigsubOld, trigsubNew);
right = rsubs(right, trigsubOld, trigsubNew);
end
% then simplify the LHS
% do it after the substitution to prevent sum of angle terms being introduced
left = simplify(left);
% search for a solveable equation:
% function of current joint variable on the LHS
% constant element on the RHS
k = NaN;
for i=1:length(left)
fprintf('%d: %s\n', i, char(left(i) == right(i)));
if hasonly(left(i), j) && isconstant(right(i))
k = i;
end
end
eq = [];
if ~isnan(k)
% create the equation to solve: LHS-RHS == 0
fprintf('choosing equation %d\n', k);
eq = left(k) - right(k);
else
% ok, we weren't lucky, try another strategy
% find all equations:
% function of current joint variable on the LHS
k = [];
for i=1:length(left)
% has qj on the left
if hasonly(left(i), j)
k = [k i];
end
end
% hopefully we found at least two of them
if length(k) < 2
continue;
end
% we did, lets see if the sum square RHS is constant
for kk = nchoosek(k, 2)'
fprintf('No simple equation, let''s square and add RHS %d %d\n', kk);
rhs = simplify(right(kk(1))^2 + right(kk(2))^2); % was simple
if isconstant( rhs )
eq = simplify( expand( left(kk(1))^2 + left(kk(2))^2 ) ) - rhs;
break
end
end
if isempty(eq)
fprintf('** can''t solve this equation, out of options');
k
left(k)==right(k)
error('can''t solve this equation');
end
% ensure that S^2+C^2=1 substitutions are made
eq = subs(eq, trigsubOld, trigsubNew);
disp(eq)
end
% expand the list of joint variable subsitutions
fprintf('subs sin/cos q%d for S/C\n', j);
trigsubOld = [trigsubOld mvar('sin(q%d)', j)^2+mvar('cos(q%d)', j)^2 mvar('sin(q%d)', j) mvar('cos(q%d)', j) ];
trigsubNew = [trigsubNew 1 mvar('S%d', j) mvar('C%d', j) ];
% now solve the equation
if srobot.links(j).isrevolute()
% for revolute joint it will be a trig equation, do we know how to solve it?
Q{j} = solve_joint(eq, j );
if isempty(Q)
warning('RTB:ikine_sym', 'can''t solve this kind of equation');
end
else
fprintf('prismatic case\n')
q = mvar('q%d', j);
Q{j} = solve( eq == 0, q);
end
end
% final simplification
% get rid of C^2+S^2 and C^4, S^4 terms
fprintf('**final simplification pass\n')
trigsubOld = [];
trigsubNew = [];
for j=1:N
trigsubOld = [trigsubOld mvar('S%d', j) mvar('C%d', j) ];
trigsubNew = [trigsubNew mvar('sin(q%d)', j) mvar('cos(q%d)', j) ];
end
Q = simplify_powers(Q, N, trigsubOld, trigsubNew);
% Q is a cell array of equations for joint variables
if nargout > 0
out = Q;
end
if ~isempty(opt.file)
fprintf('**generate MATLAB code\n')
gencode(Q);
end
end
%PIEPER Return a set of equations using Pieper's method
%
% [L,R] = pieper(robot, n, which)
%
% If robot has link matrix A1 A2 A3 A4 then returns 12 equations from equating the coefficients of
%
% A1' T = A2 A3 A4 n=1, which='left'
% A2' A1' T = A3 A4 n=2, which='left'
% A3' A2' A1' T = A4 n=3, which='left'
%
% T A4' = A1 A2 A3 n=1, which='right'
% T A4' A3' = A1 A2 n=2, which='right'
% T A4' A3' A2' = A1 n=3, which='right'
%
% A' denotes inversion not transposition
%
% Judicious choice of the equations can lead to joint solutions
function [L,R] = pieper(robot, n, which, Tpost)
if nargin < 3
which = 'left';
end
if nargin < 4 || isempty(Tpost)
Tpost = transl(zeros(robot.n, 3));
end
assert(n <= robot.n, 'RTB:ikine_sym:badarg', 'N is greater than number of joints');
syms nx ox ax tx real
syms ny oy ay ty real
syms nz oz az tz real
T = [nx ox ax tx
ny oy ay ty
nx oz az tz
0 0 0 1 ];
T = inv(robot.base.T) * T * inv(robot.tool.T);
q = robot.gencoords();
% Create the symbolic A matrices
for j=1:robot.n
A{j} = robot.links(j).A(q(j)).T * Tpost(:,:,j);
end
switch which
case 'left'
left = T;
for j=1:n
left = inv(A{j}) * left ;
end
right = eye(4,4);
for j=n+1:robot.n
right = right * A{j};
end
case 'right'
left = T;
for j=1:n
left = left * inv(A{robot.n-j+1});
end
right = eye(4,4);
for j=1:(robot.n-n)
right = right * A{j};
end
end
% left = simple(left);
% right = simple(right);
if nargout == 0
left == right
elseif nargout == 1
L = left;
elseif nargout == 2
L = left;
R = right;
end
end
%SOLVE_JOINT Solve a trigonometric equation
%
% S = SOLVE_JOINT(EQ, J) solves the equation EQ=0 for the joint variable qJ.
% The result is a vector of symbolic solutions.
%
% The equations must be of the form:
% A cos(qJ) + B sin(qJ) = 0
% A cos(qJ) + B sin(qJ) = C
%
% where A, B, C are arbitrarily complex expressions. qJ can be the only
% joint variable in the expression.
%
% Notes::
% - In general there are two solutions, but if A^2+B^2-C^2 = 0, then only one
% solution is returned.
% - The one solution case may not be detected symbolically, in which case
% the two returned solutions will have the same value after numerical
% substitution
% - The symbolic solution may not be evaluteable numerically with
% certain parameter values, ie. if A^2+B^2-C^2 < 0
function s = solve_joint(eq, j)
% see http://petercorke.com/wordpress/solving-trigonometric-equations
sinj = mvar('sin(q%d)', j);
cosj = mvar('cos(q%d)', j);
A = getcoef(eq, cosj);
B = getcoef(eq, sinj);
if isempty(A) || isempty(B)
warning('don''t know how to solve this kind of equation');
end
C = -simplify(eq - A*cosj - B*sinj);
A = simplify_sumsq(A, j);
B = simplify_sumsq(B, j);
C = simplify_sumsq(C, j);
fprintf('A = %s\n', char(A));
fprintf('B = %s\n', char(B));
fprintf('C = %s\n', char(C));
if C == 0
fprintf('Solve for C == 0\n');
% A cos(q) + B sin(q) = 0
s(1) = atan2(A, -B);
s(2) = atan2(-A, B);
else
fprintf('Solve for C != 0\n');
% A cos(q) + B sin(q) = C
% r = sqrt(A^2 + B^2 - C^2);
% % phi = atan2(A, B);
% %
% % s(2) = atan2(C, r) - phi;
% % s(1) = atan2(C, -r) - phi;
% if r == 0
% s = atan2(B*C, A*C)
% else
% s(1) = atan2(B*C + A*r, A*C - B*r);
% s(2) = atan2(B*C - A*r, A*C + B*r);
% end
d = sqrt( simplify(B^2-C^2+A^2) );
fprintf('d = %s\n', char(d));
s(1) = atan2(B*C + A*d, A*C - B*d);
s(2) = atan2(B*C - A*d, A*C + B*d);
end
% simplify( A*cos(s(1)) + B*sin(s(1)) - C )
% simplify( A*cos(s(2)) + B*sin(s(2)) - C )
if nargout == 0
try
eval(s)
catch
s
end
end
end
function Qout = simplify_sumsq(Q, N)
tsubOld = [];
tsubNew = [];
for j=1:N
tsubOld = [tsubOld mvar('S%d', j)^2+mvar('C%d', j)^2];
tsubNew = [tsubNew 1 ];
end
Q = simplify( rsubs(Q, tsubOld, tsubNew) );
Qout = simplify( rsubs(Q, tsubOld, tsubNew) );
end
function Qout = simplify_powers(Q, N, trigsubOld, trigsubNew)
% create a list of simplifications
% substitute S^2 = 1-C^2, S^4=(1-C^2)^2
fprintf('power simplification\n');
tsubOld = [];
tsubNew = [];
for j=1:N
tsubOld = [tsubOld mvar('S%d', j)^2+mvar('C%d', j)^2 mvar('S%d', j)^4];
tsubNew = [tsubNew 1 (1-mvar('C%d', j)^2)^2];
end
for j=1:length(Q)
for k=1:5
% seem to need to iterate this, not quite sure why
Q{j} = simplify( expand( subs(Q{j}, tsubOld, tsubNew) ) );
end
% subs Sx, Cx to sin(qx), cos(qx)
Qout{j} = simplify( subs(Q{j}, trigsubOld, trigsubNew) );
end
end
function out = rsubs(eq, old, new)
for i = 1:length(old)
eq = subs(eq, old(i), new(i));
end
out = eq;
end
%MVAR Create a symbolic variable
%
% V = MVAR(FMT, ARGS) is a symbolic variable created using SPRINTF
%
% eg. mvar('q%d', j)
%
% The symbolic is explicitly declared to be real.
function v = mvar(fmt, varargin)
if isempty(strfind(fmt, '('))
% not a function
v = sym( sprintf(fmt, varargin{:}), 'real' );
else
v = str2sym( sprintf(fmt, varargin{:}) );
end
end
%HASONLY Determine if an expression contains only certain joint variables
%
% S = HASONLY(E L) is true if the joint variables (q1, q2 etc.) in the expression E
% are listed in the vector L.
%
% Eg. hasonly('sin(q1)*cos(q2)*cos(q4)', [1 2 3]) -> true
% Eg. hasonly('sin(q1)*cos(q2)*cos(q4)', [1]) -> false
function s = hasonly(eq, j)
q = findq(eq);
if isempty(q)
s = false;
else
s = all(ismember(j, findq(eq)));
end
end
%ISCONSTANT Determine if an expression is free of joint variables
%
% S = ISCONSTANT(E) is true if the expression E contains no joint variables such
% q1, q2 etc.
function s = isconstant(eq)
s = isempty(findq(eq));
end
%FINDQ Find the joint variables in expression
%
% Q = FINDQ(E) returns a list of integers indicating the joint variables found
% in the expression E. For instance an instance of 'q1' would cause a 1 to be
% returned and so on.
%
% Eg. findq('sin(q1)*cos(q2)+S3') -> [1 2]
function q = findq(s)
q = [];
for var=symvar(s)
if isempty(var)
break
end
varname = char(var);
if varname(1) == 'q'
q = [q str2num(varname(2:end))];
end
end
end
function coef = getcoef(eq, trig)
z = children( collect(eq, trig) );
z = children( z(1) );
coef = z(1);
end
% Output a joint expression to a file
function s = gencode(Q, filename)
function s = G(s, fmt, varargin)
s = strvcat(s, sprintf(fmt, varargin{:}));
end
s = 'function q = xikine(T, sol)';
s = G(s, ' if nargin < 2; sol = ones(1, %d); end', length(Q));
s = G(s, ' px = T(1,4); py = T(2,4); pz = T(3,4);');
for j=1:3
Qj = Q{j}; % cast it to subclass
if length(Qj) == 1
s = G(s, ' q(%d) = %s', j, matgen2(Qj));
elseif length(Qj) == 2
s = G(s, ' if sol(%d) == 1', j);
s = G(s, ' q(%d) = %s', j, matgen2(Qj(1)));
s = G(s, ' else');
s = G(s, ' q(%d) = %s', j, matgen2(Qj(2)));
s = G(s, ' end');
end
s = G(s, ' S%d = sin(q(%d));', j, j);
s = G(s, ' C%d = cos(q(%d));', j, j);
s = G(s, ' ');
end
s = G(s, 'end');
fp = fopen(filename, 'w');
for i=1:numrows(s)
fprintf(fp, '%s\n', deblank(s(i,:)));
end
fclose(fp);
end
% Generate MATLAB code from an expression
%
% Requires a bit of a hack, a subclass of sym (sym2) to do this
function s = matgen2(e)
s = matgen(sym2(e));
k = strfind(s, '=');
s = deblank( s(k+2:end) );
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plot3d.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/plot3d.m
| 13,532 |
utf_8
|
db7ed553d5634d27afb194506cae380f
|
%SerialLink.plot3d Graphical display and animation of solid model robot
%
% R.plot3d(Q, options) displays and animates a solid model of the robot.
% The robot is displayed at the joint angle Q (1xN), or
% if a matrix (MxN) it is animated as the robot moves along the M-point trajectory.
%
% Options::
%
% 'color',C A cell array of color names, one per link. These are
% mapped to RGB using colorname(). If not given, colors
% come from the axis ColorOrder property.
% 'alpha',A Set alpha for all links, 0 is transparant, 1 is opaque
% (default 1)
% 'path',P Overide path to folder containing STL model files
% 'workspace', W Size of robot 3D workspace, W = [xmn, xmx ymn ymx zmn zmx]
% 'floorlevel',L Z-coordinate of floor (default -1)
%-
% 'delay',D Delay betwen frames for animation (s)
% 'fps',fps Number of frames per second for display, inverse of 'delay' option
% '[no]loop' Loop over the trajectory forever
% '[no]raise' Autoraise the figure
% 'movie',M Save frames as files in the folder M
% 'trail',L Draw a line recording the tip path, with line style L.
% L can be a cell array, eg. {'r', 'LineWidth', 2}
%-
% 'scale',S Annotation scale factor
% 'ortho' Orthographic view (default)
% 'perspective' Perspective view
% 'view',V Specify view V='x', 'y', 'top' or [az el] for side elevations,
% plan view, or general view by azimuth and elevation
% angle.
%-
% '[no]wrist' Enable display of wrist coordinate frame
% 'xyz' Wrist axis label is XYZ
% 'noa' Wrist axis label is NOA
% '[no]arrow' Display wrist frame with 3D arrows
%-
% '[no]tiles' Enable tiled floor (default true)
% 'tilesize',S Side length of square tiles on the floor (default 0.2)
% 'tile1color',C Color of even tiles [r g b] (default [0.5 1 0.5] light green)
% 'tile2color',C Color of odd tiles [r g b] (default [1 1 1] white)
%-
% '[no]jaxes' Enable display of joint axes (default true)
% '[no]joints' Enable display of joints
%-
% '[no]base' Enable display of base shape
%
% Notes::
% - Solid models of the robot links are required as STL files (ascii or
% binary) with extension .stl.
% - The solid models live in RVCTOOLS/robot/data/meshes.
% - Each STL model is called 'linkN'.stl where N is the link number 0 to N
% - The specific folder to use comes from the SerialLink.model3d property
% - The path of the folder containing the STL files can be overridden using
% the 'path' option
% - The height of the floor is set in decreasing priority order by:
% - 'workspace' option, the fifth element of the passed vector
% - 'floorlevel' option
% - the lowest z-coordinate in the link1.stl object
%
% Making an animation::
%
% The 'movie' options saves the animation as a movie file or separate frames in a folder
% - 'movie','file.mp4' saves as an MP4 movie called file.mp4
% - 'movie','folder' saves as files NNNN.png into the specified folder
% - The specified folder will be created
% - NNNN are consecutive numbers: 0000, 0001, 0002 etc.
% - To convert frames to a movie use a command like:
% ffmpeg -r 10 -i %04d.png out.avi
%
% Authors::
% - Peter Corke, based on existing code for plot().
% - Bryan Moutrie, demo code on the Google Group for connecting ARTE and
% RTB.
%
% Acknowledgments::
% - STL files are from ARTE: A ROBOTICS TOOLBOX FOR EDUCATION by Arturo Gil
% (https://arvc.umh.es/arte) are included, with permission.
% - The various authors of STL reading code on file exchange, see stlRead.m
%
% See also SerialLink.plot, plotbotopt3d, SerialLink.animate, SerialLink.teach, stlRead.
% Copyright (C) 1993-2015, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function plot3d(robot, q, varargin)
assert( ~robot.mdh, 'RTB:plot3d:badmodel', '3D models are defined for standard, not modified, DH parameters');
opt = plot_options(robot, varargin);
robot.movie = Animate(opt.movie);
%-- load the shape if need be
nshapes = robot.n+1;
if isempty(robot.faces)
% no 3d model defined, let's try to load one
if isempty(opt.path)
% first find the path to the models
pth = mfilename('fullpath');
pth = fileparts(pth);
% peel off the last folder
s = regexp(pth, filesep, 'split');
pth = join(s(1:end-1), filesep);
% find the path to this specific model
pth = fullfile(pth{1}, 'data/meshes', robot.model3d);
assert(exist(pth, 'dir') > 0, 'RTB:plot3d:nomodel', 'no 3D model found, install the RTB contrib zip file');
else
pth = opt.path;
end
% now load the STL files
robot.points = cell(1, robot.n+1);
robot.faces = cell(1, robot.n+1);
fprintf('Loading STL models from ARTE Robotics Toolbox for Education by Arturo Gil (http://arvc.umh.es/arte)');
for i=1:nshapes
[P,F] = stlRead( fullfile(pth, sprintf('link%d.stl', i-1)) );
robot.points{i} = P;
robot.faces{i} = F;
fprintf('.');
end
fprintf('\n');
end
% if a base is specified set the floor height to this
if isempty(opt.workspace)
% workspace not provided, fall through the options for setting floor level
if ~isempty(opt.floorlevel)
opt.ws(5) = opt.floorlevel;
elseif opt.base
mn = min( robot.points{1} );
opt.ws(5) = mn(3);
end
end
opt.floorlevel = opt.ws(5);
% TODO
% should test if the plot exists, pinch the logic from plot()
%-- set up to plot
% create an axis
ish = ishold();
if ~ishold
% if hold is off, set the axis dimensions
axis(opt.ws);
set(gca, 'ZLimMode', 'manual');
axis(opt.ws);
hold on
end
if opt.raise
% note this is a very time consuming operation
figure(gcf);
end
if strcmp(opt.projection, 'perspective')
set(gca, 'Projection', 'perspective');
end
grid on
xlabel('X'); ylabel('Y'); zlabel('Z');
%--- create floor if required
if opt.tiles
create_tiled_floor(opt);
end
%--- configure view and lighting
if isstr(opt.view)
switch opt.view
case 'top'
view(0, 90);
case 'x'
view(0, 0);
case 'y'
view(90, 0)
otherwise
error('rtb:plot3d:badarg', 'view must be: x, y, top')
end
elseif isnumeric(opt.view) && length(opt.view) == 2
view(opt.view)
else
campos([2 2 1]);
end
daspect([1 1 1]);
light('Position', [0 0 opt.reach*2]);
light('Position', [1 0.5 1]);
%-- figure the colors for each shape
if isempty(opt.color)
% if not given, use the axis color order
C = get(gca,'ColorOrder');
else
C = [];
for c=opt.color
C = [C; colorname(c{1})];
end
end
%--- create the robot
% one patch per shape, use hgtransform to animate them later
group = hggroup('Tag', robot.name);
ncolors = numrows(C);
h = [];
for link=0:robot.n
if link == 0
if ~opt.base
continue;
end
patch('Faces', robot.faces{link+1}, 'Vertices', robot.points{link+1}, ...
'FaceColor', C(mod(link,ncolors)+1,:), 'EdgeAlpha', 0, 'FaceAlpha', opt.alpha);
else
h.link(link) = hgtransform('Tag', sprintf('link%d', link), 'Parent', group);
patch('Faces', robot.faces{link+1}, 'Vertices', robot.points{link+1}, ...
'FaceColor', C(mod(link,ncolors)+1,:), 'EdgeAlpha', 0, 'FaceAlpha', opt.alpha, ...
'Parent', h.link(link));
end
end
% display the wrist coordinate frame
if opt.wrist
if opt.arrow
h.wrist = trplot(eye(4,4), 'labels', upper(opt.wristlabel), ...
'arrow', 'rgb', 'length', 0.4);
else
h.wrist = trplot(eye(4,4), 'labels', upper(opt.wristlabel), ...
'rgb', 'length', 0.4);
end
else
h.wrist = [];
end
if ~isempty(opt.trail)
h.trail = plot(0, 0, opt.trail{:});
robot.trail = [];
end
% enable mouse-based 3D rotation
rotate3d on
h.robot = robot;
h.link = [0 h.link];
set(group, 'UserData', h);
robot.trail = []; % clear the previous trail
robot.animate(q);
if opt.movie
robot.movie.close();
end
if ~ish
hold off
end
end
function opt = plot_options(robot, optin)
opt.color = [];
opt.path = []; % override path
opt.alpha = 1;
% timing/looping
opt.delay = 0.1;
opt.fps = [];
opt.loop = false;
opt.raise = false;
% general appearance
opt.scale = 1;
opt.trail = [];
opt.workspace = [];
opt.floorlevel = [];
opt.name = true;
opt.projection = {'ortho', 'perspective'};
opt.view = [];
% tiled floor
opt.tiles = true;
opt.tile1color = [0.5 1 0.5]; % light green
opt.tile2color = [1 1 1]; % white
opt.tilesize = 0.2;
% the base or pedestal
opt.base = true;
% wrist
opt.wrist = true;
opt.wristlabel = {'xyz', 'noa'};
opt.arrow = true;
% joint rotation axes
opt.jaxes = false;
% misc
opt.movie = [];
% build a list of options from all sources
% 1. the M-file plotbotopt if it exists
% 2. robot.plotopt
% 3. command line arguments
if exist('plotbotopt3d', 'file') == 2
options = [plotbotopt3d robot.plotopt3d optin];
else
options = [robot.plotopt3d optin];
end
% parse the options
[opt,args] = tb_optparse(opt, options);
if ~isempty(args)
error(['unknown option: ' args{1}]);
end
if ~isempty(opt.fps)
opt.delay = 1/opt.fps;
end
% figure the size of the figure
if isempty(opt.workspace)
%
% simple heuristic to figure the maximum reach of the robot
%
L = robot.links;
if any(L.isprismatic)
error('Prismatic joint(s) present: requires the ''workspace'' option');
end
reach = 0;
for i=1:robot.n
reach = reach + abs(L(i).a) + abs(L(i).d);
end
% if opt.wrist
% reach = reach + 1;
% end
% if we have a floor, quantize the reach to a tile size
if opt.tiles
reach = opt.tilesize * ceil(reach/opt.tilesize);
end
% now create a 3D volume based on this reach
opt.ws = [-reach reach -reach reach -reach reach];
% if a floorlevel has been given, ammend the 3D volume
if ~isempty(opt.floorlevel)
opt.ws(5) = opt.floorlevel;
end
else
% workspace is provided
reach = min(abs(opt.workspace));
if opt.tiles
% set xy limits to be integer multiple of tilesize
opt.ws(1:4) = opt.tilesize * round(opt.workspace(1:4)/opt.tilesize);
opt.ws(5:6) = opt.workspace(5:6);
else
opt.ws=opt.workspace;
end
end
opt.reach = reach;
% update the fundamental scale factor (given by the user as a multiplier) by a length derived from
% the overall workspace dimension
% we need that a lot when creating the robot model
opt.scale = opt.scale * reach/40;
% deal with a few options that need to be stashed in the SerialLink object
robot.delay = opt.delay;
robot.loop = opt.loop;
end
% draw a tiled floor in the current axes
function create_tiled_floor(opt)
xmin = opt.ws(1);
xmax = opt.ws(2);
ymin = opt.ws(3);
ymax = opt.ws(4);
% create a colored tiled floor
xt = xmin:opt.tilesize:xmax;
yt = ymin:opt.tilesize:ymax;
Z = opt.floorlevel*ones( numel(yt), numel(xt));
C = zeros(size(Z));
[r,c] = ind2sub(size(C), 1:numel(C));
C = bitand(r+c,1);
C = reshape(C, size(Z));
C = cat(3, opt.tile1color(1)*C+opt.tile2color(1)*(1-C), ...
opt.tile1color(2)*C+opt.tile2color(2)*(1-C), ...
opt.tile1color(3)*C+opt.tile2color(3)*(1-C));
[X,Y] = meshgrid(xt, yt);
surface(X, Y, Z, C, ...
'FaceColor','texturemap',...
'EdgeColor','none',...
'CDataMapping','direct');
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
rne_dh.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/rne_dh.m
| 6,612 |
utf_8
|
826f70e838ec9902b53100dda5d3cb90
|
%SERIALLINK.RNE_DH Compute inverse dynamics via recursive Newton-Euler formulation
%
% Recursive Newton-Euler for standard Denavit-Hartenberg notation. Is invoked by
% R.RNE().
%
% See also SERIALLINK.RNE.
%
% verified against MAPLE code, which is verified by examples
%
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [tau,wbase] = rne_dh(robot, a1, a2, a3, a4, a5)
z0 = [0;0;1];
grav = robot.gravity; % default gravity from the object
fext = zeros(6, 1);
n = robot.n;
% check that robot object has dynamic parameters for each link
for j=1:n
link = robot.links(j);
if isempty(link.r) || isempty(link.I) || isempty(link.m)
error('dynamic parameters (m, r, I) not set in link %d', j);
end
end
% Set debug to:
% 0 no messages
% 1 display results of forward and backward recursions
% 2 display print R and p*
debug = 0;
if numcols(a1) == 3*n
Q = a1(:,1:n);
Qd = a1(:,n+1:2*n);
Qdd = a1(:,2*n+1:3*n);
np = numrows(Q);
if nargin >= 3,
grav = a2(:);
end
if nargin == 4
fext = a3;
end
else
np = numrows(a1);
Q = a1;
Qd = a2;
Qdd = a3;
if numcols(a1) ~= n || numcols(Qd) ~= n || numcols(Qdd) ~= n || ...
numrows(Qd) ~= np || numrows(Qdd) ~= np
error('bad data');
end
if nargin >= 5,
grav = a4(:);
end
if nargin == 6
fext = a5;
end
end
if robot.issym || any([isa(Q,'sym'), isa(Qd,'sym'), isa(Qdd,'sym')])
tau = zeros(np,n, 'sym');
else
tau = zeros(np,n);
end
for p=1:np
q = Q(p,:).';
qd = Qd(p,:).';
qdd = Qdd(p,:).';
Fm = [];
Nm = [];
if robot.issym
pstarm = sym([]);
else
pstarm = [];
end
Rm = [];
% rotate base velocity and acceleration into L1 frame
Rb = t2r(robot.base)';
w = Rb*zeros(3,1);
wd = Rb*zeros(3,1);
vd = Rb*grav(:);
%
% init some variables, compute the link rotation matrices
%
for j=1:n
link = robot.links(j);
Tj = link.A(q(j));
switch link.type
case 'R'
d = link.d;
case 'P'
d = q(j);
end
alpha = link.alpha;
% O_{j-1} to O_j in {j}, negative inverse of link xform
pstar = [link.a; d*sin(alpha); d*cos(alpha)];
pstarm(:,j) = pstar;
Rm{j} = t2r(Tj);
if debug>1
Rm{j}
Pstarm(:,j).'
end
end
%
% the forward recursion
%
for j=1:n
link = robot.links(j);
Rt = Rm{j}.'; % transpose!!
pstar = pstarm(:,j);
r = link.r;
%
% statement order is important here
%
switch link.type
case 'R'
% revolute axis
wd = Rt*(wd + z0*qdd(j) + ...
cross(w,z0*qd(j)));
w = Rt*(w + z0*qd(j));
%v = cross(w,pstar) + Rt*v;
vd = cross(wd,pstar) + ...
cross(w, cross(w,pstar)) +Rt*vd;
case 'P'
% prismatic axis
w = Rt*w;
wd = Rt*wd;
vd = Rt*(z0*qdd(j)+vd) + ...
cross(wd,pstar) + ...
2*cross(w,Rt*z0*qd(j)) +...
cross(w, cross(w,pstar));
end
%whos
vhat = cross(wd,r.') + ...
cross(w,cross(w,r.')) + vd;
F = link.m*vhat;
N = link.I*wd + cross(w,link.I*w);
Fm = [Fm F];
Nm = [Nm N];
if debug
fprintf('w: '); disp( w)
fprintf('\nwd: '); disp( wd)
fprintf('\nvd: '); disp( vd)
fprintf('\nvdbar: '); disp( vhat)
fprintf('\n');
end
end
%
% the backward recursion
%
fext = fext(:);
f = fext(1:3); % force/moments on end of arm
nn = fext(4:6);
for j=n:-1:1
link = robot.links(j);
pstar = pstarm(:,j);
%
% order of these statements is important, since both
% nn and f are functions of previous f.
%
if j == n
R = eye(3,3);
else
R = Rm{j+1};
end
r = link.r;
nn = R*(nn + cross(R.'*pstar,f)) + ...
cross(pstar+r.',Fm(:,j)) + ...
Nm(:,j);
f = R*f + Fm(:,j);
if debug
fprintf('f: '); disp( f)
fprintf('\nn: '); disp( nn)
fprintf('\n');
end
R = Rm{j};
switch link.type
case 'R'
% revolute
t = nn.'*(R.'*z0) + ...
link.G^2 * link.Jm*qdd(j) - ...
link.friction(qd(j));
tau(p,j) = t;
case 'P'
% prismatic
t = f.'*(R.'*z0) + ...
link.G^2 * link.Jm*qdd(j) - ...
link.friction(qd(j));
tau(p,j) = t;
end
end
% this last bit needs work/testing
R = Rm{1};
nn = R*(nn);
f = R*f;
wbase = [f; nn];
end
if isa(tau, 'sym')
tau = simplify(tau);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikine6s.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikine6s.m
| 29,745 |
utf_8
|
73568086460517827592855df7980c12
|
%SerialLink.ikine6s Analytical inverse kinematics
%
% Q = R.ikine(T) are the joint coordinates (1xN) corresponding to the robot
% end-effector pose T which is an SE3 object or homogenenous transform
% matrix (4x4), and N is the number of robot joints. This is a analytic
% solution for a 6-axis robot with a spherical wrist (the most common form
% for industrial robot arms).
%
% If T represents a trajectory (4x4xM) then the inverse kinematics is
% computed for all M poses resulting in Q (MxN) with each row representing
% the joint angles at the corresponding pose.
%
% Q = R.IKINE6S(T, CONFIG) as above but specifies the configuration of the arm in
% the form of a string containing one or more of the configuration codes:
%
% 'l' arm to the left (default)
% 'r' arm to the right
% 'u' elbow up (default)
% 'd' elbow down
% 'n' wrist not flipped (default)
% 'f' wrist flipped (rotated by 180 deg)
%
% Trajectory operation::
%
% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous
% transform sequence (4x4xM) then R.ikcon() returns the joint coordinates
% corresponding to each of the transforms in the sequence.
%
% Notes::
% - Treats a number of specific cases:
% - Robot with no shoulder offset
% - Robot with a shoulder offset (has lefty/righty configuration)
% - Robot with a shoulder offset and a prismatic third joint (like Stanford arm)
% - The Puma 560 arms with shoulder and elbow offsets (4 lengths parameters)
% - The Kuka KR5 with many offsets (7 length parameters)
% - The inverse kinematics for the various cases determined using ikine_sym.
% - The inverse kinematic solution is generally not unique, and
% depends on the configuration string.
% - Joint offsets, if defined, are added to the inverse kinematics to
% generate Q.
% - Only applicable for standard Denavit-Hartenberg parameters
%
% Reference::
% - Inverse kinematics for a PUMA 560,
% Paul and Zhang,
% The International Journal of Robotics Research,
% Vol. 5, No. 2, Summer 1986, p. 32-44
%
% Author::
% - The Puma560 case: Robert Biro with Gary Von McMurray,
% GTRI/ATRP/IIMB, Georgia Institute of Technology, 2/13/95
% - Kuka KR5 case: Gautam Sinha,
% Autobirdz Systems Pvt. Ltd., SIDBI Office,
% Indian Institute of Technology Kanpur, Kanpur, Uttar Pradesh.
%
% See also SerialLink.fkine, SerialLink.ikine, SerialLink.ikine_sym.
function thetavec = ikine6s(robot, TT, varargin)
if robot.mdh ~= 0
error('RTB:ikine:notsupported','Solution only applicable for standard DH conventions');
end
if robot.n ~= 6
error('RTB:ikine:notsupported','Solution only applicable for 6-axis robot');
end
%
% % recurse over all poses in a trajectory
% if ndims(T) == 3
% theta = zeros(size(T,3),robot.n);
% for k=1:size(T,3)
% theta(k,:) = ikine6s(robot, T(:,:,k), varargin{:});
% end
% return;
% end
%
%
% if ~ishomog(T)
% error('RTB:ikine:badarg', 'T is not a homog xform');
% end
TT = SE3(TT);
L = robot.links;
if ~robot.isspherical()
error('RTB:ikine:notsupported', 'wrist is not spherical');
end
% The configuration parameter determines what n1,n2,n4 values are used
% and how many solutions are determined which have values of -1 or +1.
if nargin < 3
configuration = '';
else
configuration = lower(varargin{1});
end
% default configuration
sol = [1 1 1]; % left, up, noflip
for c=configuration
switch c
case 'l'
sol(1) = 1;
case 'r'
sol(1) = 2;
case 'u'
sol(2) = 1;
case 'd'
sol(2) = 2;
case 'n'
sol(3) = 1;
case 'f'
sol(3) = 2;
end
end
% determine the arm structure and the relevant solution to use
if isempty(robot.ikineType)
if is_simple(L)
robot.ikineType = 'nooffset';
elseif is_puma(L)
robot.ikineType = 'puma';
elseif is_offset(L)
robot.ikineType = 'offset';
elseif is_rrp(L)
robot.ikineType = 'rrp';
else
error('RTB:ikine6s:badarg', 'This kinematic structure not supported');
end
end
for k=1:length(TT)
% undo base and tool transformations
T = inv(robot.base) * TT(k) * inv(robot.tool);
% drop back to matrix form
T = T.T;
%% now solve for the first 3 joints, based on position of the spherical wrist centre
switch robot.ikineType
case 'puma'
% Puma model with shoulder and elbow offsets
%
% - Inverse kinematics for a PUMA 560,
% Paul and Zhang,
% The International Journal of Robotics Research,
% Vol. 5, No. 2, Summer 1986, p. 32-44
%
% Author::
% Robert Biro with Gary Von McMurray,
% GTRI/ATRP/IIMB,
% Georgia Institute of Technology
% 2/13/95
a2 = L(2).a;
a3 = L(3).a;
d1 = L(1).d;
d3 = L(3).d;
d4 = L(4).d;
% The following parameters are extracted from the Homogeneous
% Transformation as defined in equation 1, p. 34
Ox = T(1,2);
Oy = T(2,2);
Oz = T(3,2);
Ax = T(1,3);
Ay = T(2,3);
Az = T(3,3);
Px = T(1,4);
Py = T(2,4);
Pz = T(3,4) - d1;
%
% Solve for theta(1)
%
% r is defined in equation 38, p. 39.
% theta(1) uses equations 40 and 41, p.39,
% based on the configuration parameter n1
%
r = sqrt(Px^2 + Py^2);
if sol(1) == 1
theta(1) = atan2(Py,Px) + pi - asin(d3/r);
else
theta(1) = atan2(Py,Px) + asin(d3/r);
end
%
% Solve for theta(2)
%
% V114 is defined in equation 43, p.39.
% r is defined in equation 47, p.39.
% Psi is defined in equation 49, p.40.
% theta(2) uses equations 50 and 51, p.40, based on the configuration
% parameter n2
%
if sol(2) == 1
n2 = -1;
else
n2 = 1;
end
if sol(1) == 2
n2 = -n2;
end
V114 = Px*cos(theta(1)) + Py*sin(theta(1));
r = sqrt(V114^2 + Pz^2);
Psi = acos((a2^2-d4^2-a3^2+V114^2+Pz^2)/(2.0*a2*r));
if ~isreal(Psi)
theta = [];
else
theta(2) = atan2(Pz,V114) + n2*Psi;
%
% Solve for theta(3)
%
% theta(3) uses equation 57, p. 40.
%
num = cos(theta(2))*V114+sin(theta(2))*Pz-a2;
den = cos(theta(2))*Pz - sin(theta(2))*V114;
theta(3) = atan2(a3,d4) - atan2(num, den);
end
case 'nooffset'
a2 = L(2).a;
a3 = L(3).a;
d1 = L(1).d;
px = T(1,4); py = T(2,4); pz = T(3,4);
%%% autogenerated code
if L(1).alpha < 0
if sol(1) == 1
q(1) = angle(-px-py*1i);
else
q(1) = angle(px+py*1i);
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = -angle(a2*d1*-2.0+a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i-sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);
else
q(2) = -angle(a2*d1*-2.0+a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i+sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);
end
S2 = sin(q(2));
C2 = cos(q(2));
if sol(3) == 1
q(3) = -angle(a2*-1i+C2*d1-C2*pz+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i-sqrt((-a2+S2*d1-S2*pz+C1*C2*px+C2*S1*py)^2+(-C2*d1+C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));
else
q(3) = -angle(a2*-1i+C2*d1-C2*pz+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt((-a2+S2*d1-S2*pz+C1*C2*px+C2*S1*py)^2+(-C2*d1+C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));
end
else
if sol(1) == 1
q(1) = angle(px+py*1i);
else
q(1) = angle(-px-py*1i);
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = -angle(a2*d1*2.0-a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i-sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);
else
q(2) = -angle(a2*d1*2.0-a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i+sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);
end
S2 = sin(q(2));
C2 = cos(q(2));
if sol(3) == 1
q(3) = -angle(a2*-1i-C2*d1+C2*pz-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i-sqrt((-a2-S2*d1+S2*pz+C1*C2*px+C2*S1*py)^2+(C2*d1-C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));
else
q(3) = -angle(a2*-1i-C2*d1+C2*pz-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt((-a2-S2*d1+S2*pz+C1*C2*px+C2*S1*py)^2+(C2*d1-C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));
end
end
theta(1:3) = q;
case'offset'
% general case with 6 length parameters
a1 = L(1).a;
a2 = L(2).a;
a3 = L(3).a;
d1 = L(1).d;
d2 = L(2).d;
d3 = L(3).d;
px = T(1,4); py = T(2,4); pz = T(3,4);
%%% autogenerated code
if L(1).alpha < 0
if sol(1) == 1
q(1) = -angle(-px+py*1i)+angle(d2*1i+d3*1i-sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));
else
q(1) = angle(d2*1i+d3*1i+sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2))-angle(-px+py*1i);
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = angle(d1*pz*2.0i-sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i+d1-pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));
else
q(2) = angle(d1*pz*2.0i+sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i+d1-pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));
end
S2 = sin(q(2));
C2 = cos(q(2));
if sol(3) == 1
q(3) = angle(a3*1i-sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0-S2*a2*d1*2.0-S1*a1*py*2.0+S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0))-angle(a2*-1i-C2*a1*1i+C2*d1-C2*pz+S2*a1+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py);
else
q(3) = -angle(a2*-1i-C2*a1*1i+C2*d1-C2*pz+S2*a1+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0-S2*a2*d1*2.0-S1*a1*py*2.0+S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0));
end
else
if sol(1) == 1
q(1) = -angle(px-py*1i)+angle(d2*1i+d3*1i-sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));
else
q(1) = -angle(px-py*1i)+angle(d2*1i+d3*1i+sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = angle(d1*pz*2.0i-sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i-d1+pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));
else
q(2) = angle(d1*pz*2.0i+sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i-d1+pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));
end
S2 = sin(q(2));
C2 = cos(q(2));
if sol(3) == 1
q(3) = angle(a3*1i-sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0+S2*a2*d1*2.0-S1*a1*py*2.0-S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0))-angle(a2*-1i-C2*a1*1i-C2*d1+C2*pz+S2*a1-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py);
else
q(3) = -angle(a2*-1i-C2*a1*1i-C2*d1+C2*pz+S2*a1-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0+S2*a2*d1*2.0-S1*a1*py*2.0-S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0));
end
end
theta(1:3) = q;
case 'rrp'
% RRP (Stanford arm like)
px = T(1,4); py = T(2,4); pz = T(3,4);
d1 = L(1).d;
d2 = L(2).d;
%%% autogenerated code
if L(1).alpha < 0
if sol(1) == 1
q(1) = -angle(-px+py*1i)+angle(d2*1i-sqrt(-d2^2+px^2+py^2));
else
q(1) = angle(d2*1i+sqrt(-d2^2+px^2+py^2))-angle(-px+py*1i);
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = angle(d1-pz-C1*px*1i-S1*py*1i);
else
q(2) = angle(-d1+pz+C1*px*1i+S1*py*1i);
end
S2 = sin(q(2));
C2 = cos(q(2));
q(3) = -C2*d1+C2*pz+C1*S2*px+S1*S2*py;
else
if sol(1) == 1
q(1) = -angle(px-py*1i)+angle(d2*1i-sqrt(-d2^2+px^2+py^2));
else
q(1) = -angle(px-py*1i)+angle(d2*1i+sqrt(-d2^2+px^2+py^2));
end
S1 = sin(q(1));
C1 = cos(q(1));
if sol(2) == 1
q(2) = angle(-d1+pz-C1*px*1i-S1*py*1i);
else
q(2) = angle(d1-pz+C1*px*1i+S1*py*1i);
end
S2 = sin(q(2));
C2 = cos(q(2));
q(3) = -C2*d1+C2*pz-C1*S2*px-S1*S2*py;
end
theta(1:3) = q;
case 'kr5'
%Given function will calculate inverse kinematics for KUKA KR5 robot
% Equations are calculated and implemented by
% Gautam Sinha
% Autobirdz Systems Pvt. Ltd.
% SIDBI Office,
% Indian Institute of Technology Kanpur, Kanpur, Uttar Pradesh
% 208016
% India
%email- [email protected]
% get the a1, a2 and a3-- link lenghts for link no 1,2,3
L = robot.links;
a1 = L(1).a;
a2 = L(2).a;
a3 = L(3).a;
% Check wether wrist is spherical or not
if ~robot.isspherical()
error('wrist is not spherical')
end
% get d1,d2,d3,d4---- Link offsets for link no 1,2,3,4
d1 = L(1).d;
d2 = L(2).d;
d3 = L(3).d;
d4 = L(4).d;
% Get the parameters from transformation matrix
Ox = T(1,2);
Oy = T(2,2);
Oz = T(3,2);
Ax = T(1,3);
Ay = T(2,3);
Az = T(3,3);
Px = T(1,4);
Py = T(2,4);
Pz = T(3,4);
% Set the parameters n1, n2 and n3 to get required configuration from
% solution
n1 = -1; % 'l'
n2 = -1; % 'u'
n4 = -1; % 'n'
if ~isempty(strfind(configuration, 'l'))
n1 = -1;
end
if ~isempty(strfind(configuration, 'r'))
n1 = 1;
end
if ~isempty(strfind(configuration, 'u'))
if n1 == 1
n2 = 1;
else
n2 = -1;
end
end
if ~isempty(strfind(configuration, 'd'))
if n1 == 1
n2 = -1;
else
n2 = 1;
end
end
if ~isempty(strfind(configuration, 'n'))
n4 = 1;
end
if ~isempty(strfind(configuration, 'f'))
n4 = -1;
end
% Calculation for theta(1)
r=sqrt(Px^2+Py^2);
if (n1 == 1)
theta(1)= atan2(Py,Px) + asin((d2-d3)/r);
else
theta(1)= atan2(Py,Px)+ pi - asin((d2-d3)/r);
end
% Calculation for theta(2)
X= Px*cos(theta(1)) + Py*sin(theta(1)) - a1;
r=sqrt(X^2 + (Pz-d1)^2);
Psi = acos((a2^2-d4^2-a3^2+X^2+(Pz-d1)^2)/(2.0*a2*r));
if ~isreal(Psi)
warning('RTB:ikine6s:notreachable', 'point not reachable');
theta = [NaN NaN NaN NaN NaN NaN];
return
end
theta(2) = atan2((Pz-d1),X) + n2*Psi;
% Calculation for theta(3)
Nu = cos(theta(2))*X + sin(theta(2))*(Pz-d1) - a2;
Du = sin(theta(2))*X - cos(theta(2))*(Pz-d1);
theta(3) = atan2(a3,d4) - atan2(Nu, Du);
% Calculation for theta(4)
Y = cos(theta(1))*Ax + sin(theta(1))*Ay;
M2 = sin(theta(1))*Ax - cos(theta(1))*Ay ;
M1 = ( cos(theta(2)-theta(3)) )*Y + ( sin(theta(2)-theta(3)) )*Az;
theta(4) = atan2(n4*M2,n4*M1);
% Calculation for theta(5)
Nu = -cos(theta(4))*M1 - M2*sin(theta(4));
M3 = -Az*( cos(theta(2)-theta(3)) ) + Y*( sin(theta(2)-theta(3)) );
theta(5) = atan2(Nu,M3);
% Calculation for theta(6)
Z = cos(theta(1))*Ox + sin(theta(1))*Oy;
L2 = sin(theta(1))*Ox - cos(theta(1))*Oy;
L1 = Z*( cos(theta(2)-theta(3) )) + Oz*( sin(theta(2)-theta(3)));
L3 = Z*( sin(theta(2)-theta(3) )) - Oz*( cos(theta(2)-theta(3)));
A1 = L1*cos(theta(4)) + L2*sin(theta(4));
A3 = L1*sin(theta(4)) - L2*cos(theta(4));
Nu = -A1*cos(theta(5)) - L3*sin(theta(5));
Du = -A3;
theta(6) = atan2(Nu,Du);
otherwise
error('RTB:ikine6s:badarg', 'Unknown solution type [%s]', robot.ikineType);
end
if ~isempty(theta)
% Solve for the wrist rotation
% we need to account for some random translations between the first and last 3
% joints (d4) and also d6,a6,alpha6 in the final frame.
T13 = robot.A(1:3, theta(1:3)); % transform of first 3 joints
% T = T13 * Tz(d4) * R * Tz(d6) Tx(a5)
Td4 = SE3(0, 0, L(4).d); % Tz(d4)
Tt = SE3(L(6).a, 0, L(6).d) * SE3.Rx(L(6).alpha); % Tz(d6) Tx(a5) Rx(alpha6)
R = inv(Td4) * inv(T13) * SE3(T) * inv(Tt);
% the spherical wrist implements Euler angles
if sol(3) == 1
theta(4:6) = tr2eul(R, 'flip');
else
theta(4:6) = tr2eul(R);
end
if L(4).alpha > 0
theta(5) = -theta(5);
end
% remove the link offset angles
for j=1:robot.n %#ok<*AGROW>
theta(j) = theta(j) - L(j).offset;
end
% stack the rows
thetavec(k,:) = theta;
else
warning('RTB:ikine6s:notreachable', 'point not reachable');
thetavec(k,:) = [NaN NaN NaN NaN NaN NaN];
end
end
end
% predicates to determine which kinematic solution to use
function s = is_simple(L)
alpha = [-pi/2 0 pi/2];
s = all([L(2:3).d] == 0) && ...
(all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...
all([L(1:3).isrevolute] == 1) && ...
(L(1).a == 0);
end
function s = is_offset(L)
alpha = [-pi/2 0 pi/2];
s = (all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...
all([L(1:3).isrevolute] == 1);
end
function s = is_rrp(L)
alpha = [-pi/2 pi/2 0];
s = all([L(2:3).a] == 0) && ...
(all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...
all([L(1:3).isrevolute] == [1 1 0]);
end
function s = is_puma(L)
alpha = [pi/2 0 -pi/2];
s = (L(2).d == 0) && (L(1).a == 0) && ...
(L(3).d ~= 0) && (L(3).a ~= 0) && ...
all([L(1:3).alpha] == alpha) && ...
all([L(1:3).isrevolute] == 1);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
jacob0.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/jacob0.m
| 3,646 |
utf_8
|
cefe7b33dd972bd5a59120a2aa180511
|
%SerialLink.JACOB0 Jacobian in world coordinates
%
% J0 = R.jacob0(Q, OPTIONS) is the Jacobian matrix (6xN) for the robot in
% pose Q (1xN), and N is the number of robot joints. The manipulator
% Jacobian matrix maps joint velocity to end-effector spatial velocity V =
% J0*QD expressed in the world-coordinate frame.
%
% Options::
% 'rpy' Compute analytical Jacobian with rotation rate in terms of
% XYZ roll-pitch-yaw angles
% 'eul' Compute analytical Jacobian with rotation rates in terms of
% Euler angles
% 'exp' Compute analytical Jacobian with rotation rates in terms of
% exponential coordinates
% 'trans' Return translational submatrix of Jacobian
% 'rot' Return rotational submatrix of Jacobian
%
% Note::
% - End-effector spatial velocity is a vector (6x1): the first 3 elements
% are translational velocity, the last 3 elements are rotational velocity
% as angular velocity (default), RPY angle rate or Euler angle rate.
% - This Jacobian accounts for a base and/or tool transform if set.
% - The Jacobian is computed in the end-effector frame and transformed to
% the world frame.
% - The default Jacobian returned is often referred to as the geometric
% Jacobian.
%
% See also SerialLink.jacobe, jsingu, deltatr, tr2delta, jsingu.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function J0 = jacob0(robot, q, varargin)
opt.trans = false;
opt.rot = false;
opt.analytic = {[], 'rpy', 'eul', 'exp'};
opt.deg = false;
opt = tb_optparse(opt, varargin);
if opt.deg
% in degrees mode, scale the columns corresponding to revolute axes
q = robot.toradians(q);
end
%
% dX_tn = Jn dq
%
Jn = jacobe(robot, q); % Jacobian from joint to wrist space
%
% convert to Jacobian in base coordinates
%
Tn = fkine(robot, q); % end-effector transformation
if isa(Tn, 'SE3')
R = Tn.R;
else
R = t2r(Tn);
end
J0 = [R zeros(3,3); zeros(3,3) R] * Jn;
% convert to analytical Jacobian if required
if ~isempty(opt.analytic)
switch opt.analytic
case 'rpy'
rpy = tr2rpy(Tn);
A = rpy2jac(rpy, 'xyz');
if rcond(A) < eps
error('Representational singularity');
end
case 'eul'
eul = tr2eul(Tn);
A = eul2jac(eul);
if rcond(A) < eps
error('Representational singularity');
end
case 'exp'
[theta,v] = trlog( t2r(Tn) );
A = eye(3,3) - (1-cos(theta))/theta*skew(v) ...
+ (theta - sin(theta))/theta*skew(v)^2;
end
J0 = blkdiag( eye(3,3), inv(A) ) * J0;
end
% choose translational or rotational subblocks
if opt.trans
J0 = J0(1:3,:);
elseif opt.rot
J0 = J0(4:6,:);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
qmincon.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/qmincon.m
| 3,020 |
utf_8
|
d668a698e2a7ddc924cee8c0285574a1
|
%SerialLink.QMINCON Use redundancy to avoid joint limits
%
% QS = R.qmincon(Q) exploits null space motion and returns a set of joint
% angles QS (1xN) that result in the same end-effector pose but are away
% from the joint coordinate limits. N is the number of robot joints.
%
% [Q,ERR] = R.qmincon(Q) as above but also returns ERR which is the
% scalar final value of the objective function.
%
% [Q,ERR,EXITFLAG] = R.qmincon(Q) as above but also returns the
% status EXITFLAG from fmincon.
%
% Trajectory operation::
%
% In all cases if Q is MxN it is taken as a pose sequence and R.qmincon()
% returns the adjusted joint coordinates (MxN) corresponding to each of the
% poses in the sequence.
%
% ERR and EXITFLAG are also Mx1 and indicate the results of optimisation
% for the corresponding trajectory step.
%
% Notes::
% - Requires fmincon from the MATLAB Optimization Toolbox.
% - Robot must be redundant.
%
% Author::
% Bryan Moutrie
%
% See also SerialLink.ikcon, SerialLink.ikunc, SerialLink.jacob0.
% Copyright (C) Bryan Moutrie, 2013-2015
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with pHRIWARE. If not, see <http://www.gnu.org/licenses/>.
function [qstar, error, exitflag] = qmincon(robot, q)
% check if Optimization Toolbox exists, we need it
assert( exist('fmincon')>0, 'rtb:qmincon:nosupport', 'Optimization Toolbox required');
assert( robot.n > 6, 'rtb:qmincon:badarg', 'pHRIWARE:Robot is not redundant');
M = size(q,1);
n = robot.n;
qstar = zeros(M,n);
error = zeros(M,1);
exitflag = zeros(M,1);
opt = optimoptions('fmincon', ...
'Algorithm', 'active-set', ...
'Display', 'off');
lb = robot.qlim(:,1);
ub = robot.qlim(:,2);
x_m = 0; % Little trick for setting x0 in first iteration of loop
for m = 1:M
q_m = q(m,:);
J = robot.jacobe(q(m,:));
N = null(J);
f = @(x) sumsqr((2*(N*x + q_m') - ub - lb)./(ub-lb));
x0 = zeros(size(N,2), 1) + x_m;
A = [N; -N];
b = [ub-q_m'; q_m'-lb];
[x_m, err_m, ef_m] = fmincon(f,x0,A,b,[],[],[],[],[],opt);
qstar(m,:) = q(m,:) + (N*x_m)';
error(m) = err_m;
exitflag(m) = ef_m;
end
end
function s = sumsqr(A)
s = sum(A.^2);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
jacob_dot.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/jacob_dot.m
| 2,857 |
utf_8
|
a77ef304c00af50fae51408192670c83
|
%SerialLink.jacob_dot Derivative of Jacobian
%
% JDQ = R.jacob_dot(Q, QD) is the product (6x1) of the derivative of the
% Jacobian (in the world frame) and the joint rates.
%
% Notes::
% - This term appears in the formulation for operational space control XDD = J(Q)QDD + JDOT(Q)QD
% - Written as per the reference and not very efficient.
%
% References::
% - Fundamentals of Robotics Mechanical Systems (2nd ed)
% J. Angleles, Springer 2003.
% - A unified approach for motion and force control of robot manipulators: The operational space formulation
% O Khatib, IEEE Journal on Robotics and Automation, 1987.
%
% See also SerialLink.jacob0, diff2tr, tr2diff.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function Jdot = jacob_dot(robot, q, qd)
n = robot.n;
links = robot.links;
% Using the notation of Angeles:
% [Q,a] ~ [R,t] the per link transformation
% P ~ R the cumulative rotation t2r(Tj) in world frame
% e the last column of P, the local frame z axis in world coordinates
% w angular velocity in base frame
% ed deriv of e
% r is distance from final frame
% rd deriv of r
% ud ??
for i=1:n
T = links(i).A(q(i));
Q{i} = t2r(T);
a{i} = transl(T)';
end
P{1} = Q{1};
e{1} = [0 0 1]';
for i=2:n
P{i} = P{i-1}*Q{i};
e{i} = P{i}(:,3);
end
% step 1
w{1} = qd(1)*e{1};
for i=1:(n-1)
w{i+1} = qd(i+1)*[0 0 1]' + Q{i}'*w{i};
end
% step 2
ed{1} = [0 0 0]';
for i=2:n
ed{i} = cross(w{i}, e{i});
end
% step 3
rd{n} = cross( w{n}, a{n});
for i=(n-1):-1:1
rd{i} = cross(w{i}, a{i}) + Q{i}*rd{i+1};
end
r{n} = a{n};
for i=(n-1):-1:1
r{i} = a{i} + Q{i}*r{i+1};
end
ud{1} = cross(e{1}, rd{1});
for i=2:n
ud{i} = cross(ed{i}, r{i}) + cross(e{i}, rd{i});
end
% step 4
% swap ud and ed
v{n} = qd(n)*[ud{n}; ed{n}];
for i=(n-1):-1:1
Ui = blkdiag(Q{i}, Q{i});
v{i} = qd(i)*[ud{i}; ed{i}] + Ui*v{i+1};
end
Jdot = v{1};
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
genforces.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/genforces.m
| 1,041 |
utf_8
|
5d93fc7e2f784513c9f4877a3c9c1632
|
%SerialLink.genforces Vector of symbolic generalized forces
%
% Q = R.genforces() is a vector (1xN) of symbols [Q1 Q2 ... QN].
%
% See also SerialLink.gencoords.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function tau = genforces(r)
for j=1:r.n
tau(j) = sym( sprintf('Q%d', j), 'real' );
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gravload.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/gravload.m
| 1,702 |
utf_8
|
e69104458a273c682f92379c2b29b1a9
|
%SerialLink.gravload Gravity load on joints
%
% TAUG = R.gravload(Q) is the joint gravity loading (1xN) for the robot R
% in the joint configuration Q (1xN), where N is the number of robot
% joints. Gravitational acceleration is a property of the robot object.
%
% If Q is a matrix (MxN) each row is interpreted as a joint configuration
% vector, and the result is a matrix (MxN) each row being the corresponding
% joint torques.
%
% TAUG = R.gravload(Q, GRAV) as above but the gravitational
% acceleration vector GRAV is given explicitly.
%
% See also SerialLink.gravjac, SerialLink.rne, SerialLink.itorque, SerialLink.coriolis.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function tg = gravload(robot, q, grav)
assert(numcols(q) == robot.n, 'RTB:SerialLink:gravload:badarg', 'Insufficient columns in q');
if nargin == 2
tg = rne(robot, q, zeros(size(q)), zeros(size(q)));
elseif nargin == 3
tg = rne(robot, q, zeros(size(q)), zeros(size(q)), grav);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
vellipse.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/vellipse.m
| 3,056 |
utf_8
|
4b4838d955c054ccbbfaa3ab5dba1f31
|
%SerialLink.vellipse Velocity ellipsoid for seriallink manipulator
%
% R.vellipse(Q, OPTIONS) displays the velocity ellipsoid for the
% robot R at pose Q. The ellipsoid is centered at the tool tip position.
%
% Options::
% '2d' Ellipse for translational xy motion, for planar manipulator
% 'trans' Ellipsoid for translational motion (default)
% 'rot' Ellipsoid for rotational motion
%
% Display options as per plot_ellipse to control ellipsoid face and edge
% color and transparency.
%
% Example::
% To interactively update the velocity ellipsoid while using sliders
% to change the robot's pose:
% robot.teach('callback', @(r,q) r.vellipse(q))
%
% Notes::
% - The ellipsoid is tagged with the name of the robot prepended to
% ".vellipse".
% - Calling the function with a different pose will update the ellipsoid.
%
% See also SerialLink.jacob0, SerialLink.fellipse, plot_ellipse.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function vellipse(robot, q, varargin)
name = [robot.name '.vellipse'];
e = findobj('Tag', name);
if isempty(q)
delete(e);
return;
end
opt.mode = {'trans', 'rot', '2d'};
opt.deg = false;
[opt,args] = tb_optparse(opt, varargin);
if opt.deg
% in degrees mode, scale the columns corresponding to revolute axes
q = robot.todegrees(q);
end
if robot.n == 2
opt.mode = '2d';
end
J = robot.jacob0(q);
switch opt.mode
case'2d'
J = J(1:2,1:2);
case 'trans'
J = J(1:3,:);
case 'rot'
J = J(4:6,:);
end
N = (J*J');
if det(N) < 100*eps
warning('RTB:fellipse:badval', 'Jacobian is singular, ellipse cannot be drawn')
return
end
t = transl(robot.fkine(q));
switch opt.mode
case '2d'
if isempty(e)
h = plot_ellipse(N, t(1:2), 'edgecolor', 'r', 'Tag', name, args{:});
else
plot_ellipse(N, t(1:2), 'alter', e);
end
otherwise
if isempty(e)
h = plot_ellipse(N, t(1:3), 'edgecolor', 'k', 'fillcolor', 'r', 'alpha', 0.5, 'Tag', name, args{:});
else
plot_ellipse(N, t(1:3), 'alter', e);
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikinem.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikinem.m
| 5,810 |
utf_8
|
08dfd56edbd04dcc5e0e637cc50fc21d
|
%SerialLink.IKINEM Numerical inverse kinematics by minimization
%
% Q = R.ikinem(T) is the joint coordinates corresponding to the robot
% end-effector pose T which is a homogenenous transform.
%
% Q = R.ikinem(T, Q0, OPTIONS) specifies the initial estimate of the joint
% coordinates.
%
% In all cases if T is 4x4xM it is taken as a homogeneous transform sequence
% and R.ikinem() returns the joint coordinates corresponding to each of the
% transforms in the sequence. Q is MxN where N is the number of robot joints.
% The initial estimate of Q for each time step is taken as the solution
% from the previous time step.
%
% Options::
% 'pweight',P weighting on position error norm compared to rotation
% error (default 1)
% 'stiffness',S Stiffness used to impose a smoothness contraint on joint
% angles, useful when N is large (default 0)
% 'qlimits' Enforce joint limits
% 'ilimit',L Iteration limit (default 1000)
% 'nolm' Disable Levenberg-Marquadt
%
% Notes::
% - PROTOTYPE CODE UNDER DEVELOPMENT, intended to do numerical inverse kinematics
% with joint limits
% - The inverse kinematic solution is generally not unique, and
% depends on the initial guess Q0 (defaults to 0).
% - The function to be minimized is highly nonlinear and the solution is
% often trapped in a local minimum, adjust Q0 if this happens.
% - The default value of Q0 is zero which is a poor choice for most
% manipulators (eg. puma560, twolink) since it corresponds to a kinematic
% singularity.
% - Such a solution is completely general, though much less efficient
% than specific inverse kinematic solutions derived symbolically, like
% ikine6s or ikine3.% - Uses Levenberg-Marquadt minimizer LMFsolve if it can be found,
% if 'nolm' is not given, and 'qlimits' false
% - The error function to be minimized is computed on the norm of the error
% between current and desired tool pose. This norm is computed from distances
% and angles and 'pweight' can be used to scale the position error norm to
% be congruent with rotation error norm.
% - This approach allows a solution to obtained at a singularity, but
% the joint angles within the null space are arbitrarily assigned.
% - Joint offsets, if defined, are added to the inverse kinematics to
% generate Q.
% - Joint limits become explicit contraints if 'qlimits' is set.
%
% See also fminsearch, fmincon, SerialLink.fkine, SerialLink.ikine, tr2angvec.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function qt = ikinem(robot, tr, varargin)
opt.pweight = 1;
opt.stiffness = 0;
opt.qlimits = false;
opt.ilimit = 1000;
opt.lm = true;
opt.col = 2;
[opt,args] = tb_optparse(opt, varargin);
% check if optional argument is a valid q
q0 = args{1};
if numel(q0) ~= robot.n
error('q0 length must match number of joints in robot');
end
for i=1:size(tr,3)
T = tr(:,:,i);
if opt.qlimits
% constrained optimization to handle joint limits
options = optimset('MaxIter', opt.ilimit);
qlim = robot.qlim;
[q, ef, exflag, output] = fmincon( @(x) costfun(x, robot, T, opt), q0, ...
[], [], [], [], ...
qlim(:,1), qlim(:,2), ...
[], options);
if opt.verbose
fprintf('final error %f, %d iterations, %d evalations\n', ...
ef, output.iterations, output.funcCount);
end
else
% no joint limits, unconstrained optimization
if exist('LMFsolve') == 2 && opt.lm
[q, ef, count] = LMFsolve( @(x) costfun(x, robot, T, opt), q0, 'MaxIter', opt.ilimit);
q = q';
if opt.verbose
fprintf('final error %f, %d iterations\n', ...
ef, count);
end
else
options = optimset('MaxIter', opt.ilimit);
[q, ef, exflag, output] = fminsearch( @(x) costfun(x, robot, T, opt), q0, options);
if opt.verbose
fprintf('final error %f, %d iterations, %d evalations\n', ...
ef, output.iterations, output.funcCount);
end
end
end
qt(i,:) = q;
end
if opt.verbose
robot.fkine(qt)
end
end
% The cost function, this is the value to be minimized
function E = costfun(q, robot, T, opt)
Tq = robot.fkine(q);
% find the pose error in SE(3)
dT = transl(T) - transl(Tq);
% translation error
E = norm(dT) * opt.pweight;
% rotation error
% find dot product of
dd = dot(T(1:3,opt.col), Tq(1:3,opt.col));
%E = E + (1 - dd)^2*100000 ;
E = E + acos(dd)^2*1000 ;
if opt.stiffness > 0
% enforce a continuity constraint on joints, minimum bend
E = E + sum( diff(q).^2 ) * opt.stiffness;
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
friction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/friction.m
| 1,966 |
utf_8
|
2f63bbaee7c50862ade7f84192f16f6b
|
%SerialLink.friction Friction force
%
% TAU = R.friction(QD) is the vector of joint friction forces/torques for the
% robot moving with joint velocities QD.
%
% The friction model includes:
% - Viscous friction which is a linear function of velocity.
% - Coulomb friction which is proportional to sign(QD).
%
% Notes::
% - The friction value should be added to the motor output torque, it has a
% negative value when QD>0.
% - The returned friction value is referred to the output of the gearbox.
% - The friction parameters in the Link object are referred to the motor.
% - Motor viscous friction is scaled up by G^2.
% - Motor Coulomb friction is scaled up by G.
% - The appropriate Coulomb friction value to use in the non-symmetric case
% depends on the sign of the joint velocity, not the motor velocity.
% - The absolute value of the gear ratio is used. Negative gear ratios are
% tricky: the Puma560 has negative gear ratio for joints 1 and 3.
%
% See also Link.friction.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function tau = friction(robot, qd)
L = robot.links;
tau = zeros(1,robot.n);
if robot.issym
tau = sym(tau);
end
for j=1:robot.n
tau(j) = L(j).friction(qd(j));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
collisions.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/collisions.m
| 4,903 |
utf_8
|
3b172dbfe4909f80182d48722b7761e6
|
%SerialLink.COLLISIONS Perform collision checking
%
% C = R.collisions(Q, MODEL) is true if the SerialLink object R at
% pose Q (1xN) intersects the solid model MODEL which belongs to the
% class CollisionModel. The model comprises a number of geometric
% primitives with an associated pose.
%
% C = R.collisions(Q, MODEL, DYNMODEL, TDYN) as above but also checks
% dynamic collision model DYNMODEL whose elements are at pose TDYN.
% TDYN is an array of transformation matrices (4x4xP), where
% P = length(DYNMODEL.primitives). The P'th plane of TDYN premultiplies the
% pose of the P'th primitive of DYNMODEL.
%
% C = R.collisions(Q, MODEL, DYNMODEL) as above but assumes TDYN is the
% robot's tool frame.
%
% Trajectory operation::
%
% If Q is MxN it is taken as a pose sequence and C is Mx1 and the collision
% value applies to the pose of the corresponding row of Q. TDYN is 4x4xMxP.
%
% Notes::
% - Requires the pHRIWARE package which defines CollisionModel class.
% Available from: https://github.com/bryan91/pHRIWARE .
% - The robot is defined by a point cloud, given by its points property.
% - The function does not currently check the base of the SerialLink
% object.
% - If MODEL is [] then no static objects are assumed.
%
% Author::
% Bryan Moutrie
%
% See also CollisionModel, SerialLink.
% Copyright (C) Bryan Moutrie, 2013-2015
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with pHRIWARE. If not, see <http://www.gnu.org/licenses/>.
function c = collisions(robot, q, cmdl, dyn_cmdl, dyn_T)
if ~exist('pHRIWARE')
error('rtb:collisions:nosupport', 'You need to install pHRIWARE in order to use this functionality');
end
% VERSION WITH BASE CHECKING
% pts = robot.points;
pts = robot.points(end-robot.n+1:end);
for i = length(pts): -1: 1
numPts(i) = size(pts{i},1);
pts{i}(:,4) = 1;
pts{i} = pts{i}';
end
if isempty(cmdl), checkfuns = []; else checkfuns = cmdl.checkFuns; end
if nargin > 3
dyn_checkfuns = dyn_cmdl.checkFuns;
if nargin == 4 || isempty(dyn_T)
tool = robot.tool;
dyn_T = [];
end
else
dyn_checkfuns = [];
end
% VERSION WITH BASE CHECKING
% base = length(pts) - robot.n;
% switch base
% case 0
% % No base
% case 1
% T = robot.base;
% trPts = T * pts{1};
% points = trPts (1:3,:)';
% if any(checkfuns{1}(points(:,1),points(:,2),points(:,3)))
% C(:) = 1;
% display('Base is colliding');
% return;
% end
% otherwise
% error('robot has missing or extra points');
% end
poses = size(q,1);
c = false(poses, 1);
nan = any(isnan(q),2);
c(nan) = true;
notnan = find(~nan)';
T0 = robot.base;
for p = notnan
T = T0;
prevPts = 0;
for i = 1: robot.n;
T = T * robot.links(i).A(q(p,i));
if numPts(i) % Allows some links to be STLless
% VERSION WITH BASE CHECKING
% nextPts = prevPts+numPts(i+base);
% trPts(:,prevPts+1:nextPts) = T * pts{i+base};
nextPts = prevPts+numPts(i);
trPts(:,prevPts+1:nextPts) = T * pts{i};
prevPts = nextPts;
end
end
% Does same thing as cmdl.collision(trPoints(1:3,:)'), but
% Does not have to access object every time - quicker
for i = 1: length(checkfuns)
if any(checkfuns{i}(trPts(1,:), trPts(2,:), trPts(3,:)))
c(p) = true;
break;
end
end
% Then check the dynamic collision models, if any
for i = 1: length(dyn_checkfuns)
if isempty(dyn_T)
dyn_trPts = T*tool \ trPts;
else
dyn_trPts = dyn_T(:,:,p,i) \ trPts;
end
if any(dyn_checkfuns{i}(dyn_trPts(1,:), dyn_trPts(2,:), ...
dyn_trPts(3,:)))
c(p) = true;
break;
end
end
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikine3.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikine3.m
| 4,301 |
utf_8
|
0a1f619c4a4671a44dca93db19af5ac2
|
%SerialLink.ikine3 Inverse kinematics for 3-axis robot with no wrist
%
% Q = R.ikine3(T) is the joint coordinates (1x3) corresponding to the robot
% end-effector pose T represented by the homogenenous transform. This
% is a analytic solution for a 3-axis robot (such as the first three joints
% of a robot like the Puma 560).
%
% Q = R.ikine3(T, CONFIG) as above but specifies the configuration of the arm in
% the form of a string containing one or more of the configuration codes:
%
% 'l' arm to the left (default)
% 'r' arm to the right
% 'u' elbow up (default)
% 'd' elbow down
%
% Notes::
% - The same as IKINE6S without the wrist.
% - The inverse kinematic solution is generally not unique, and
% depends on the configuration string.
% - Joint offsets, if defined, are added to the inverse kinematics to
% generate Q.
%
% Trajectory operation::
%
% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous
% transform sequence (4x4xM) then returns the joint coordinates
% corresponding to each of the transforms in the sequence. Q is Mx3.
%
% Reference::
%
% Inverse kinematics for a PUMA 560 based on the equations by Paul and Zhang
% From The International Journal of Robotics Research
% Vol. 5, No. 2, Summer 1986, p. 32-44
%
%
% Author::
% Robert Biro with Gary Von McMurray,
% GTRI/ATRP/IIMB,
% Georgia Institute of Technology
% 2/13/95
%
% See also SerialLink.FKINE, SerialLink.IKINE.
function theta = ikine3(robot, T, varargin)
assert( strncmp(robot.config, 'RRR', 3), 'Solution only applicable for 3DOF all-revolute manipulator');
assert( robot.mdh ~= 0, 'Solution only applicable for standard DH conventions');
if isa(T, 'SE3')
T = T.T;
end
if ndims(T) == 3
theta = zeros(size(T,3),robot.n);
for k=1:size(T,3)
theta(k,:) = ikine3(robot, T(:,:,k), varargin{:});
end
return;
end
L = robot.links;
a2 = L(2).a;
a3 = L(3).a;
d3 = L(3).d;
if ~ishomog(T)
error('T is not a homog xform');
end
% undo base transformation
T = robot.base \ T;
% The following parameters are extracted from the Homogeneous
% Transformation as defined in equation 1, p. 34
Px = T(1,4);
Py = T(2,4);
Pz = T(3,4);
% The configuration parameter determines what n1,n2 values are used
% and how many solutions are determined which have values of -1 or +1.
if nargin < 3
configuration = '';
else
configuration = lower(varargin{1});
end
% default configuration
n1 = -1; % L
n2 = -1; % U
if ~isempty(strfind(configuration, 'l'))
n1 = -1;
end
if ~isempty(strfind(configuration, 'r'))
n1 = 1;
end
if ~isempty(strfind(configuration, 'u'))
if n1 == 1
n2 = 1;
else
n2 = -1;
end
end
if ~isempty(strfind(configuration, 'd'))
if n1 == 1
n2 = -1;
else
n2 = 1;
end
end
%
% Solve for theta(1)
%
% r is defined in equation 38, p. 39.
% theta(1) uses equations 40 and 41, p.39,
% based on the configuration parameter n1
%
r=sqrt(Px^2 + Py^2);
if (n1 == 1)
theta(1)= atan2(Py,Px) + asin(d3/r);
else
theta(1)= atan2(Py,Px) + pi - asin(d3/r);
end
%
% Solve for theta(2)
%
% V114 is defined in equation 43, p.39.
% r is defined in equation 47, p.39.
% Psi is defined in equation 49, p.40.
% theta(2) uses equations 50 and 51, p.40, based on the configuration
% parameter n2
%
V114= Px*cos(theta(1)) + Py*sin(theta(1));
r=sqrt(V114^2 + Pz^2);
Psi = acos((a2^2-d4^2-a3^2+V114^2+Pz^2)/(2.0*a2*r));
if ~isreal(Psi)
warning('RTB:ikine3:notreachable', 'point not reachable');
theta = [NaN NaN NaN NaN NaN NaN];
return
end
theta(2) = atan2(Pz,V114) + n2*Psi;
%
% Solve for theta(3)
%
% theta(3) uses equation 57, p. 40.
%
num = cos(theta(2))*V114+sin(theta(2))*Pz-a2;
den = cos(theta(2))*Pz - sin(theta(2))*V114;
theta(3) = atan2(a3,d4) - atan2(num, den);
% remove the link offset angles
for i=1:robot.n %#ok<*AGROW>
theta(i) = theta(i) - L(i).offset;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ikine.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/ikine.m
| 10,470 |
utf_8
|
13f34d241c03545c512d37dda5779124
|
%SerialLink.ikine Inverse kinematics by optimization without joint limits
%
% Q = R.ikine(T) are the joint coordinates (1xN) corresponding to the robot
% end-effector pose T which is an SE3 object or homogenenous transform
% matrix (4x4), and N is the number of robot joints.
%
% This method can be used for robots with any number of degrees of freedom.
%
% Options::
% 'ilimit',L maximum number of iterations (default 500)
% 'rlimit',L maximum number of consecutive step rejections (default 100)
% 'tol',T final error tolerance (default 1e-10)
% 'lambda',L initial value of lambda (default 0.1)
% 'lambdamin',M minimum allowable value of lambda (default 0)
% 'quiet' be quiet
% 'verbose' be verbose
% 'mask',M mask vector (6x1) that correspond to translation in X, Y and Z,
% and rotation about X, Y and Z respectively.
% 'q0',Q initial joint configuration (default all zeros)
% 'search' search over all configurations
% 'slimit',L maximum number of search attempts (default 100)
% 'transpose',A use Jacobian transpose with step size A, rather than
% Levenberg-Marquadt
%
% Trajectory operation::
%
% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous
% transform sequence (4x4xM) then returns the joint coordinates
% corresponding to each of the transforms in the sequence. Q is MxN where
% N is the number of robot joints. The initial estimate of Q for each time
% step is taken as the solution from the previous time step.
%
% Underactuated robots::
%
% For the case where the manipulator has fewer than 6 DOF the solution
% space has more dimensions than can be spanned by the manipulator joint
% coordinates.
%
% In this case we specify the 'mask' option where the mask
% vector (1x6) specifies the Cartesian DOF (in the wrist coordinate
% frame) that will be ignored in reaching a solution. The mask vector
% has six elements that correspond to translation in X, Y and Z, and rotation
% about X, Y and Z respectively. The value should be 0 (for ignore) or 1.
% The number of non-zero elements should equal the number of manipulator DOF.
%
% For example when using a 3 DOF manipulator rotation orientation might be
% unimportant in which case use the option: 'mask', [1 1 1 0 0 0].
%
% For robots with 4 or 5 DOF this method is very difficult to use since
% orientation is specified by T in world coordinates and the achievable
% orientations are a function of the tool position.
%
% References::
% - Robotics, Vision & Control, P. Corke, Springer 2011, Section 8.4.
%
% Notes::
% - This has been completely reimplemented in RTB 9.11
% - Does NOT require MATLAB Optimization Toolbox.
% - Solution is computed iteratively.
% - Implements a Levenberg-Marquadt variable step size solver.
% - The tolerance is computed on the norm of the error between current
% and desired tool pose. This norm is computed from distances
% and angles without any kind of weighting.
% - The inverse kinematic solution is generally not unique, and
% depends on the initial guess Q0 (defaults to 0).
% - The default value of Q0 is zero which is a poor choice for most
% manipulators (eg. puma560, twolink) since it corresponds to a kinematic
% singularity.
% - Such a solution is completely general, though much less efficient
% than specific inverse kinematic solutions derived symbolically, like
% ikine6s or ikine3.
% - This approach allows a solution to be obtained at a singularity, but
% the joint angles within the null space are arbitrarily assigned.
% - Joint offsets, if defined, are added to the inverse kinematics to
% generate Q.
% - Joint limits are not considered in this solution.
% - The 'search' option peforms a brute-force search with initial conditions
% chosen from the entire configuration space.
% - If the 'search' option is used any prismatic joint must have joint
% limits defined.
%
% See also SerialLink.ikcon, SerialLink.ikunc, SerialLink.fkine, SerialLink.ikine6s.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%TODO:
% search do a broad search from random points in configuration space
function qt = ikine(robot, tr, varargin)
n = robot.n;
TT = SE3.convert(tr);
% set default parameters for solution
opt.ilimit = 500;
opt.rlimit = 100;
opt.slimit = 100;
opt.tol = 1e-10;
opt.lambda = 0.1;
opt.lambdamin = 0;
opt.search = false;
opt.quiet = false;
opt.verbose = false;
opt.mask = [1 1 1 1 1 1];
opt.q0 = zeros(1, n);
opt.transpose = NaN;
[opt,args] = tb_optparse(opt, varargin);
if opt.search
% randomised search for a starting point
opt.search = false;
opt.quiet = true;
%args = args{2:end};
for k=1:opt.slimit
for j=1:n
qlim = robot.links(j).qlim;
if isempty(qlim)
if robot.links(j).isrevolute
q(j) = rand*2*pi - pi;
else
error('For a prismatic joint, search requires joint limits');
end
else
q(j) = rand*(qlim(2)-qlim(1)) + qlim(1);
end
end
fprintf('Trying q = %s\n', num2str(q));
q = robot.ikine(tr, q, args{:}, 'setopt', opt);
if ~isempty(q)
qt = q;
return;
end
end
error('no solution found, are you sure the point is reachable?');
qt = [];
return
end
assert(numel(opt.mask) == 6, 'RTB:ikine:badarg', 'Mask matrix should have 6 elements');
assert(n >= numel(find(opt.mask)), 'RTB:ikine:badarg', 'Number of robot DOF must be >= the same number of 1s in the mask matrix');
W = diag(opt.mask);
qt = zeros(length(TT), n); % preallocate space for results
tcount = 0; % total iteration count
rejcount = 0; % rejected step count
q = opt.q0;
failed = false;
revolutes = robot.isrevolute();
for i=1:length(TT)
T = TT(i);
lambda = opt.lambda;
iterations = 0;
if opt.debug
e = tr2delta(robot.fkine(q), T);
fprintf('Initial: |e|=%g\n', norm(W*e));
end
while true
% update the count and test against iteration limit
iterations = iterations + 1;
if iterations > opt.ilimit
if ~opt.quiet
warning('ikine: iteration limit %d exceeded (pose %d), final err %g', ...
opt.ilimit, i, nm);
end
failed = true;
break
end
e = tr2delta(robot.fkine(q), T);
% are we there yet
if norm(W*e) < opt.tol
break;
end
% compute the Jacobian
J = jacobe(robot, q);
JtJ = J'*W*J;
if ~isnan(opt.transpose)
% do the simple Jacobian transpose with constant gain
dq = opt.transpose * J' * e;
else
% do the damped inverse Gauss-Newton with Levenberg-Marquadt
dq = inv(JtJ + (lambda + opt.lambdamin) * eye(size(JtJ)) ) * J' * W * e;
% compute possible new value of
qnew = q + dq';
% and figure out the new error
enew = tr2delta(robot.fkine(qnew), T);
% was it a good update?
if norm(W*enew) < norm(W*e)
% step is accepted
if opt.debug
fprintf('ACCEPTED: |e|=%g, |dq|=%g, lambda=%g\n', norm(W*enew), norm(dq), lambda);
end
q = qnew;
e = enew;
lambda = lambda/2;
rejcount = 0;
else
% step is rejected, increase the damping and retry
if opt.debug
fprintf('rejected: |e|=%g, |dq|=%g, lambda=%g\n', norm(W*enew), norm(dq), lambda);
end
lambda = lambda*2;
rejcount = rejcount + 1;
if rejcount > opt.rlimit
if ~opt.quiet
warning('ikine: rejected-step limit %d exceeded (pose %d), final err %g', ...
opt.rlimit, i, norm(W*enew));
end
failed = true;
break;
end
continue; % try again
end
end
% wrap angles for revolute joints
k = (q > pi) & revolutes;
q(k) = q(k) - 2*pi;
k = (q < -pi) & revolutes;
q(k) = q(k) + 2*pi;
nm = norm(W*e);
end % end ikine solution for this pose
qt(i,:) = q';
tcount = tcount + iterations;
if opt.verbose && ~failed
fprintf('%d iterations\n', iterations);
end
if failed
if ~opt.quiet
warning('failed to converge: try a different initial value of joint coordinates');
end
qt = [];
end
end
if opt.verbose && length(TT) > 1
fprintf('TOTAL %d iterations\n', tcount);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
nofriction.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/nofriction.m
| 1,579 |
utf_8
|
92710a0f362f8f1fc80900ceeb4aaa7a
|
%SerialLink.nofriction Remove friction
%
% RNF = R.nofriction() is a robot object with the same parameters as R but
% with non-linear (Coulomb) friction coefficients set to zero.
%
% RNF = R.nofriction('all') as above but viscous and Coulomb friction coefficients set to zero.
%
% RNF = R.nofriction('viscous') as above but viscous friction coefficients
% are set to zero.
%
% Notes::
% - Non-linear (Coulomb) friction can cause numerical problems when integrating
% the equations of motion (R.fdyn).
% - The resulting robot object has its name string prefixed with 'NF/'.
%
% See also SerialLink.fdyn, Link.nofriction.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function r2 = nofriction(r, varargin)
r2 = SerialLink(r); % make a copy
for j=1:r2.n
r2.links(j) = r.links(j).nofriction(varargin{:});
end
r2.name = ['NF/' r.name];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
pay.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/pay.m
| 2,575 |
utf_8
|
9c930f4b5b2fda7f91379e7eabd4c522
|
%SerialLink.PAY Joint forces due to payload
%
% TAU = R.PAY(W, J) returns the generalised joint force/torques due to a
% payload wrench W (1x6) and where the manipulator Jacobian is J (6xN), and
% N is the number of robot joints.
%
% TAU = R.PAY(Q, W, F) as above but the Jacobian is calculated at pose Q
% (1xN) in the frame given by F which is '0' for world frame, 'e' for
% end-effector frame.
%
% Uses the formula TAU = J'W, where W is a wrench vector applied at the end
% effector, W = [Fx Fy Fz Mx My Mz]'.
%
% Trajectory operation::
%
% In the case Q is MxN or J is 6xNxM then TAU is MxN where each row is the
% generalised force/torque at the pose given by corresponding row of Q.
%
% Notes::
% - Wrench vector and Jacobian must be from the same reference frame.
% - Tool transforms are taken into consideration when F = 'e'.
% - Must have a constant wrench - no trajectory support for this yet.
%
% Author::
% Bryan Moutrie
%
% See also SerialLink.paycap, SerialLink.jacob0, SerialLink.jacobe.
% Copyright (C) Bryan Moutrie, 2013-2015
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with pHRIWARE. If not, see <http://www.gnu.org/licenses/>.
function tauP = pay(robot, varargin)
if length(varargin) == 2
w = varargin{1};
J = varargin{2};
n = size(J,2);
elseif length(varargin) == 3
q = varargin{1};
w = varargin{2};
f = varargin{3};
n = robot.n;
J = zeros(6,n,size(q,1));
switch f
case '0'
for i= 1: size(q,1)
J(:,:,i) = robot.jacob0(q(i,:));
end
case {'n', 'e'}
for i= 1: size(q,1)
J(:,:,i) = robot.jacobe(q(i,:));
end
end
end
if ~isequal(size(w),[6 1]), error(pHRIWARE('error', 'inputSize')); end
tauP = -reshape(J(:,:)'*w,n,[])';
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
coriolis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/@SerialLink/coriolis.m
| 3,894 |
utf_8
|
ba7c5409a3fedb513910bbd572655c64
|
%SerialLink.coriolis Coriolis matrix
%
% C = R.coriolis(Q, QD) is the Coriolis/centripetal matrix (NxN) for
% the robot in configuration Q and velocity QD, where N is the number of
% joints. The product C*QD is the vector of joint force/torque due to velocity
% coupling. The diagonal elements are due to centripetal effects and the
% off-diagonal elements are due to Coriolis effects. This matrix is also
% known as the velocity coupling matrix, since it describes the disturbance forces
% on any joint due to velocity of all other joints.
%
% If Q and QD are matrices (KxN), each row is interpretted as a joint state
% vector, and the result (NxNxK) is a 3d-matrix where each plane corresponds
% to a row of Q and QD.
%
% C = R.coriolis( QQD) as above but the matrix QQD (1x2N) is [Q QD].
%
% Notes::
% - Joint viscous friction is also a joint force proportional to velocity but it is
% eliminated in the computation of this value.
% - Computationally slow, involves N^2/2 invocations of RNE.
%
% See also SerialLink.rne.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function C = coriolis(robot, q, qd)
n = robot.n;
if nargin == 2
% coriolis( [q qd] )
assert(numcols(q) == 2*n,'RTB:coriolis:badarg', 'arg must have %d columns', 2*n);
qd = q(:,n+1:end);
q = q(:,1:n);
else
assert( numcols(q) == n, 'RTB:coriolis:badarg', 'Cq must have %d columns', n);
assert( numcols(qd) == n, 'RTB:coriolis:badarg', 'qd must have %d columns', n);
end
% we need to create a clone robot with no friction, since friction
% is also proportional to joint velocity
robot2 = robot.nofriction('all');
if numrows(q) > 1
assert( numrows(q) == numrows(qd), 'RTB:coriolis:badarg', 'for trajectory q and qd must have same number of rows');
C = [];
for i=1:numrows(q)
C = cat(3, C, robot2.coriolis(q(i,:), qd(i,:)));
end
return
end
N = robot2.n;
C = zeros(N,N);
Csq = zeros(N,N);
if isa(q, 'sym')
C = sym(C);
Csq = sym(Csq);
end
% find the torques that depend on a single finite joint speed,
% these are due to the squared (centripetal) terms
%
% set QD = [1 0 0 ...] then resulting torque is due to qd_1^2
for j=1:N
QD = zeros(1,N);
QD(j) = 1;
tau = robot2.rne(q, QD, zeros(size(q)), 'gravity', [0 0 0]);
Csq(:,j) = Csq(:,j) + tau.';
end
% find the torques that depend on a pair of finite joint speeds,
% these are due to the product (Coridolis) terms
% set QD = [1 1 0 ...] then resulting torque is due to
% qd_1 qd_2 + qd_1^2 + qd_2^2
for j=1:N
for k=j+1:N
% find a product term qd_j * qd_k
QD = zeros(1,N);
QD(j) = 1;
QD(k) = 1;
tau = robot2.rne(q, QD, zeros(size(q)), 'gravity', [0 0 0]);
C(:,k) = C(:,k) + (tau.' - Csq(:,k) - Csq(:,j)) * qd(j)/2;
C(:,j) = C(:,j) + (tau.' - Csq(:,k) - Csq(:,j)) * qd(k)/2;
end
end
C = C + Csq * diag(qd);
if isa(q, 'sym')
C = simplify(C);
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.