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
Quaternion.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/Quaternion.m
4,034
utf_8
f2afd42f26b30a934c594f8e7fb16791
%QUATERNION constructor for quaternion objects % % QUATERNION([s v1 v2 v3]) from 4 elements % QUATERNION(v, theta) from vector plus angle % QUATERNION(R) from a 3x3 or 4x4 matrix % QUATERNION(q) from another quaternion % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 q = Quaternion(a1, a2) if nargin == 0, q.s = 1; q.v = [0 0 0]; q = class (q, 'Quaternion'); elseif nargin == 1 if isa(a1, 'Quaternion') q = a1; q = class(q, 'Quaternion'); elseif isreal (a1) && size(a1) == 1 q.s = a1(1); q.v = [0,0,0]; q = class(q, 'Quaternion'); elseif isreal (a1) && all (size (a1) == [1 3]) # Quaternion (vector part) q.s = 0; q.v = a1(1:3); q = class(q, 'Quaternion'); elseif all(size(a1) == [3 3]) q = Quaternion( tr2q(a1) ); elseif all(size(a1) == [4 4]) q = Quaternion( tr2q(a1(1:3,1:3)) ); elseif all(size(a1) == [1 4]) q.s = a1(1); q.v = a1(2:4); q = class(q, 'Quaternion'); else error('unknown dimension of input'); end elseif nargin == 2 if isscalar(a1) && isvector(a2) q.s = cos(a1/2); q.v = (sin(a1/2)*unit(a2(:)')); q = class(q, 'Quaternion'); end end endfunction %TR2Q Convert homogeneous transform to a unit-quaternion % % Q = tr2q(T) % % Return a unit quaternion corresponding to the rotational part of the % homogeneous transform T. % % See also Q2TR % Ryan Steidnl based on Robotics Toolbox for MATLAB (v6 and v9) % % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 q = tr2q(t) qs = sqrt(trace(t)+1)/2.0; kx = t(3,2) - t(2,3); % Oz - Ay ky = t(1,3) - t(3,1); % Ax - Nz kz = t(2,1) - t(1,2); % Ny - Ox if (t(1,1) >= t(2,2)) & (t(1,1) >= t(3,3)) kx1 = t(1,1) - t(2,2) - t(3,3) + 1; % Nx - Oy - Az + 1 ky1 = t(2,1) + t(1,2); % Ny + Ox kz1 = t(3,1) + t(1,3); % Nz + Ax add = (kx >= 0); elseif (t(2,2) >= t(3,3)) kx1 = t(2,1) + t(1,2); % Ny + Ox ky1 = t(2,2) - t(1,1) - t(3,3) + 1; % Oy - Nx - Az + 1 kz1 = t(3,2) + t(2,3); % Oz + Ay add = (ky >= 0); else kx1 = t(3,1) + t(1,3); % Nz + Ax ky1 = t(3,2) + t(2,3); % Oz + Ay kz1 = t(3,3) - t(1,1) - t(2,2) + 1; % Az - Nx - Oy + 1 add = (kz >= 0); end if add kx = kx + kx1; ky = ky + ky1; kz = kz + kz1; else kx = kx - kx1; ky = ky - ky1; kz = kz - kz1; end nm = norm([kx ky kz]); if nm == 0, q = Quaternion([1 0 0 0]); else s = sqrt(1 - qs^2) / nm; qv = s*[kx ky kz]; q = Quaternion([qs qv]); end endfunction
github
RobinAmsters/GT_mobile_robotics-master
display.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/display.m
1,029
utf_8
5005939253bba5057986ba5e99fcc973
%DISPLAY display the value of a quaternion object % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 % Copright (C) Peter Corke 1999 function display(q) disp(' '); disp([inputname(1), ' = ']) disp(' '); disp([' ' char(q)]) disp(' ');
github
RobinAmsters/GT_mobile_robotics-master
interp.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/interp.m
2,037
utf_8
0285ce161dcea6f15ec661917ade554c
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 q = interp(Q1, Q2, r) %Quaternion.interp Interpolate rotations expressed by quaternion objects % % QI = Q1.interp(Q2, R) is a unit-quaternion that interpolates between Q1 for R=0 % to Q2 for R=1. This is a spherical linear interpolation (slerp) that can be % interpretted as interpolation along a great circle arc on a sphere. % % If R is a vector QI is a vector of quaternions, each element % corresponding to sequential elements of R. % % Notes: % - the value of r is clipped to the interval 0 to 1 % % See also ctraj, Quaternion.scale. q1 = double(Q1); q2 = double(Q2); theta = acos(q1*q2'); count = 1; % clip values of r r(r<0) = 0; r(r>1) = 1; if length(r) == 1 if theta == 0 q = Q1; else q = Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) ); end else for R=r(:)' if theta == 0 qq = Q1; else qq = Quaternion( (sin((1-R)*theta) * q1 + sin(R*theta) * q2) / sin(theta) ); end q(count) = qq; count = count + 1; end end end
github
RobinAmsters/GT_mobile_robotics-master
plot.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/plot.m
1,334
utf_8
a911420db26f46c33659a9d91a300906
%PLOT plot a quaternion object as a rotated coordinate frame % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 % Copright (C) Peter Corke 1999 function plot(Q) axis([-1 1 -1 1 -1 1]) o = [0 0 0]'; x1 = Q*[1 0 0]'; y1 = Q*[0 1 0]'; z1 = Q*[0 0 1]'; hold on plot3([0;x1(1)], [0; x1(2)], [0; x1(3)]) text(x1(1), x1(2), x1(3), 'X') plot3([0;y1(1)], [0; y1(2)], [0; y1(3)]) text(y1(1), y1(2), y1(3), 'Y') plot3([0;z1(1)], [0; z1(2)], [0; z1(3)]) text(z1(1), z1(2), z1(3), 'Z') grid on xlabel('X') ylabel('Y') zlabel('Z') hold off
github
RobinAmsters/GT_mobile_robotics-master
double.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/double.m
1,055
utf_8
3c6907b9af17b78cda4c776b0542d2fc
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 v = double(q) %Quaternion.double Convert a quaternion object to a 4-element vector % % V = Q.double() is a 4-vector comprising the quaternion % elements [s vx vy vz]. v = [q.s q.v]; endfunction
github
RobinAmsters/GT_mobile_robotics-master
scale.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/scale.m
2,018
utf_8
2adf3b3004453808797ce265b58b7659
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 q = scale(Q, r) %Quaternion.scale Interpolate rotations expressed by quaternion objects % % QI = Q.scale(R) is a unit-quaternion that interpolates between identity for R=0 % to Q for R=1. This is a spherical linear interpolation (slerp) that can % be interpretted as interpolation along a great circle arc on a sphere. % % If R is a vector QI is a cell array of quaternions, each element % corresponding to sequential elements of R. % % See also ctraj, Quaternion.interp. q2 = double(Q); if any(r<0) || (r>1) error('r out of range'); end q1 = [1 0 0 0]; % identity quaternion theta = acos(q1*q2'); if length(r) == 1 if theta == 0 q = Q; else q = unit(Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) )); end else count = 1; for R=r(:)' if theta == 0 qq = Q; else qq = Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) ).unit; end q(count) = qq; count = count + 1; end end end
github
RobinAmsters/GT_mobile_robotics-master
mrdivide.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/mrdivide.m
1,282
utf_8
a9c1b7b8b87592a33fc161d28efd23c9
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qq = mrdivide(q1, q2) %Quaternion.mrdivide Compute quaternion quotient. % % Q1/Q2 is a quaternion formed by Hamilton product of Q1 and inv(Q2) % Q/S is the element-wise division of quaternion elements by by the scalar S if isa(q2, 'Quaternion') % qq = q1 / q2 % = q1 * qinv(q2) qq = q1 * inv(q2); elseif isa(q2, 'double') qq = Quaternion( double(q1) / q2 ); end end
github
RobinAmsters/GT_mobile_robotics-master
qinterp.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/qinterp.m
1,727
utf_8
2e5be9d99ede2b9ce58a5d2b7db344fd
%QINTERP Interpolate rotations expressed by quaternion objects % % QI = qinterp(Q1, Q2, R) % % Return a unit-quaternion that interpolates between Q1 and Q2 as R moves % from 0 to 1. This is a spherical linear interpolation (slerp) that can % be interpretted as interpolation along a great circle arc on a sphere. % % If r is a vector, QI, is a cell array of quaternions. % % See also TR2Q % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 % MOD HISTORY % 2/99 convert to use of objects % Copright (C) Peter Corke 1999 function q = qinterp(Q1, Q2, r) q1 = double(Q1); q2 = double(Q2); if (r<0) | (r>1), error('R out of range'); end theta = acos(q1*q2'); q = {}; count = 1; if length(r) == 1, q = quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) ); else for R=r(:)', qq = quaternion( (sin((1-R)*theta) * q1 + sin(R*theta) * q2) / sin(theta) ); q{count} = qq; count = count + 1; end end
github
RobinAmsters/GT_mobile_robotics-master
char.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/char.m
1,040
utf_8
b71a701e2d387683b513855d663de42b
%CHAR create string representation of quaternion object % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 % Copright (C) Peter Corke 1999 function s = char(q) s = [num2str(q.s), ' <' num2str(q.v(1)) ', ' num2str(q.v(2)) ', ' num2str(q.v(3)) '>'];
github
RobinAmsters/GT_mobile_robotics-master
unit.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/unit.m
997
utf_8
4745971f54ca4b629a6e8bc55a078408
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qu = unit(q) %Quaternion.unit Unitize a quaternion % % QU = Q.unit() is a quaternion which is a unitized version of Q qu = q / norm(q); end
github
RobinAmsters/GT_mobile_robotics-master
subsref.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/subsref.m
1,930
utf_8
64b5d237e94c65cd19baefc95598c973
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 v = subsref(q, s) if (length (s)<2) if s(1).type == '.' % NOTE WELL: the following code can't use getfield() since % getfield() uses this, and Matlab will crash!! el = char(s(1).subs); switch el case 'd' v = double(q); case 's' v = q.s; case 'v' v = q.v; case 'T' v = q2tr(q); case 'R' v = q2tr(q); v = v(1:3,1:3); case 'inv' v = inv(q); case 'norm' v = norm(q); case 'unit' v = unit(q); case 'double' v = double(q); case 'plot' v = plot(q); end else error('only .field supported') end elseif (length(s) == 2 ) if s(1).type == '.' % NOTE WELL: the following code can't use getfield() since % getfield() uses this, and Matlab will crash!! el = char(s(1).subs); args = s(2).subs; switch el case 'interp' v = interp(q,args{:}); case 'scale' v = scale(q,args{:}); case 'dot' v = dot(q,args{:}); end else error('only .field supported') end else error('only .field supported') end endfunction
github
RobinAmsters/GT_mobile_robotics-master
q2tr.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/q2tr.m
1,167
utf_8
c29ddf72eec74706e77c4bda8b562bde
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 t = q2tr(q) q = double(q); s = q(1); x = q(2); y = q(3); z = q(4); r = [ 1-2*(y^2+z^2) 2*(x*y-s*z) 2*(x*z+s*y) 2*(x*y+s*z) 1-2*(x^2+z^2) 2*(y*z-s*x) 2*(x*z-s*y) 2*(y*z+s*x) 1-2*(x^2+y^2) ]; t = eye(4,4); t(1:3,1:3) = r; t(4,4) = 1; endfunction
github
RobinAmsters/GT_mobile_robotics-master
plus.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/plus.m
1,081
utf_8
b0e2a4b5d2c508c817f9a56397002779
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qp = plus(q1, q2) %PLUS Add two quaternion objects % % Q1+Q2 is the element-wise sum of quaternion elements. if isa(q1, 'Quaternion') & isa(q2, 'Quaternion') qp = Quaternion(double(q1) + double(q2)); end end
github
RobinAmsters/GT_mobile_robotics-master
mpower.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/mpower.m
1,355
utf_8
7b9a578d511f56a544e2c15d8e15dde2
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qp = mpower(q, p) %Quaternion.mpower Raise quaternion to integer power % % Q^N is quaternion Q raised to the integer power N, and computed by repeated multiplication. % check that exponent is an integer if (p - floor(p)) ~= 0 error('quaternion exponent must be integer'); end qp = q; % multiply by itself so many times for i = 2:abs(p) qp = qp * q; end % if exponent was negative, invert it if p<0 qp = inv(qp); end end
github
RobinAmsters/GT_mobile_robotics-master
mtimes.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/mtimes.m
2,478
utf_8
99b0537c96d9e7857dce59ca93da8eb1
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qp = mtimes(q1, q2) %Quaternion.mtimes Multiply a quaternion object % % Q1*Q2 is a quaternion formed by Hamilton product of two quaternions. % Q*V is the vector V rotated by the quaternion Q % Q*S is the element-wise multiplication of quaternion elements by by the scalar S if isa(q1, 'Quaternion') & isa(q2, 'Quaternion') %QQMUL Multiply unit-quaternion by unit-quaternion % % QQ = qqmul(Q1, Q2) % % Return a product of unit-quaternions. % % See also: TR2Q % decompose into scalar and vector components s1 = q1.s; v1 = q1.v; s2 = q2.s; v2 = q2.v; % form the product qp = Quaternion([s1*s2-v1*v2' s1*v2+s2*v1+cross(v1,v2)]); elseif isa(q1, 'Quaternion') & isa(q2, 'double') %QVMUL Multiply vector by unit-quaternion % % VT = qvmul(Q, V) % % Rotate the vector V by the unit-quaternion Q. % % See also: QQMUL, QINV if length(q2) == 3 qp = q1 * Quaternion([0 q2(:)']) * inv(q1); qp = qp.v(:); elseif length(q2) == 1 qp = Quaternion(double(q1)*q2); else error('quaternion-vector product: must be a 3-vector or scalar'); end elseif isa(q2, 'Quaternion') & isa(q1, 'double') if length(q1) == 3 qp = q2 * Quaternion([0 q1(:)']) * inv(q2); qp = qp.v; elseif length(q1) == 1 qp = Quaternion(double(q2)*q1); else error('quaternion-vector product: must be a 3-vector or scalar'); end end end
github
RobinAmsters/GT_mobile_robotics-master
inv.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/inv.m
1,023
utf_8
4acf75d995437c869ea1f6e806104619
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qi = inv(q) %Quaternion.inv Invert a unit-quaternion % % QI = Q.inv() is a quaternion object representing the inverse of Q. qi = Quaternion([q.s -q.v]); endfunction
github
RobinAmsters/GT_mobile_robotics-master
minus.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Quaternion/minus.m
1,106
utf_8
7844d4807b15185b86f3b9993bf72d66
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 qp = minus(q1, q2) %Quaternion.minus Subtract two quaternion objects % % Q1-Q2 is the element-wise difference of quaternion elements. if isa(q1, 'Quaternion') & isa(q2, 'Quaternion') qp = Quaternion(double(q1) - double(q2)); end end
github
RobinAmsters/GT_mobile_robotics-master
display.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/display.m
992
utf_8
1744ef8c7924b5841a47207003535695
%DISPLAY display the value of a LINK object % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 % Copright (C) Peter Corke 1999 function display(l) disp([inputname(1), ' = ']) disp( char(l) ); end
github
RobinAmsters/GT_mobile_robotics-master
show.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/show.m
1,226
utf_8
c90fb8c0e8972f93ea8c30b673633d2e
%SHOW show all parameters of LINK object % % SHOW(link) % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 show(l) llab = 6; for n =fieldnames(l)' v = getfield(l, char(n)); name = char(n); spaces = char(' '*ones(1,llab-length(name))); val = num2str(v); label = [name spaces ' = ']; if numrows(val) > 1, pad = {label; char(' '*ones(numrows(val)-1,1))}; else pad = label; end disp([char(pad) val]); end
github
RobinAmsters/GT_mobile_robotics-master
subsasgn.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/subsasgn.m
2,843
utf_8
9a4a1d65fc4137471a6bd218fbd2a960
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 this = subsasgn(this, index, value) switch index(1).type case '.' switch index(1).subs, case 'alpha', this.alpha = value; case 'a', this.a = value; case 'theta', this.theta = value; case 'd', this.d = value; case 'offset', this.offset = value; case 'sigma', if ischar(value) this.sigma = lower(value) == 'p'; else this.sigma = value; end case 'mdh', this.mdh = value; case 'G', this.G = value; case 'I', if isempty(value) return; end if all(size(value) == [3 3]) if norm(value-value') > eps error('inertia matrix must be symmetric'); end this.I = value; elseif length(value) == 3 this.I = diag(value); elseif length(value) == 6 this.I = [ value(1) value(4) value(6) value(4) value(2) value(5) value(6) value(5) value(3)]; end case 'r', if isempty(value) return; end if length(value) ~= 3 error('COG must be a 3-vector'); end this.r = value(:)'; case 'Jm', this.Jm = value; case 'B', this.B = value; case 'Tc', if isempty(value) return; end if length(value) == 1 this.Tc = [value -value]; elseif length(value) == 2 if value(1) < value(2) error('Coulomb friction is [Tc+ Tc-]'); end this.Tc = value; else error('Coulomb friction vector can have 1 (symmetric) or 2 (asymmetric) elements only') end case 'm', this.m = value; case 'qlim', if length(value) ~= 2, error('joint limit must have 2 elements'); end this.qlim = value; otherwise, error('Unknown method') end case '()' if numel(index) == 1 if isempty(this) this = value; %% this is a crude bug fix end this = builtin('subsasgn', this, index, value); else this_subset = this(index(1).subs{:}); % get the subset this_subset = subsasgn(this_subset, index(2:end), value); this(index(1).subs{:}) = this_subset; % put subset back; end end endfunction
github
RobinAmsters/GT_mobile_robotics-master
char.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/char.m
2,817
utf_8
a0694168712bc20d14a58df87d0cce09
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 s = char(links, from_robot) %Link.char String representation of parameters % % s = L.char() is a string showing link parameters in 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 from_robot if l.sigma == 1 % prismatic joint js = sprintf('|%3d|%11.4g|%11s|%11.4g|%11.4g|', ... j, l.theta, sprintf('q%d', j), l.a, l.alpha); else js = sprintf('|%3d|%11s|%11.4g|%11.4g|%11.4g|', ... j, sprintf('q%d', j), l.d, l.a, l.alpha); end else if l.sigma == 0, conv = 'R'; else conv = 'P'; end if l.mdh == 0 conv = [conv ',stdDH']; else conv = [conv ',modDH']; end if length(links) == 1 qname = 'q'; else qname = sprintf('q%d', j); end if l.sigma == 1 % prismatic joint js = sprintf(' theta=%.4g, d=%s, a=%.4g, alpha=%.4g (%s)', ... l.theta, qname, l.a, l.alpha, conv); else js = sprintf(' theta=%s, d=%.4g, a=%.4g, alpha=%.4g (%s)', ... qname, l.d, l.a, l.alpha, conv); end end s = strvcat(s, js); end end % char()
github
RobinAmsters/GT_mobile_robotics-master
friction.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/friction.m
1,399
utf_8
fd114474c00d7a5a4850ddb1f11e11af
%FRICTION compute friction torque on the LINK object % % TAU = FRICTION(LINK, QD) % % Return the friction torque on the link moving at speed QD. Depending % on fields in the LINK object viscous and/or Coulomb friction % are computed. % % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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(l, qd) %Link.friction Joint friction force % % F = L.friction(QD) is the joint friction force/torque for link velocity QD tau = 0.0; tau = l.B * qd; if qd > 0 tau = tau + l.Tc(1); elseif qd < 0 tau = tau + l.Tc(2); end tau = -tau; % friction opposes motion endfunction % friction()
github
RobinAmsters/GT_mobile_robotics-master
nofriction.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/nofriction.m
1,338
utf_8
af30540d9fe008e95184816cb1baaea8
%NOFRICTION return link object with zero friction % % LINK = NOFRICTION(LINK) % % % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 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') is a link object with the same parameters as L % except all friction parameters are zero. l2 = Link(l); if (nargin == 2) && strcmpi(only(1:3), 'all') l2.B = 0; end l2.Tc = [0 0]; end
github
RobinAmsters/GT_mobile_robotics-master
subsref.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/subsref.m
6,453
utf_8
0251a70ca1dfd3e28127b24e79472d31
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 v = subsref(l, s) switch s(1).type case '.' % NOTE WELL: the following code can't use getfield() since % getfield() uses this, and Matlab will crash!! el = char(s(1).subs); switch el, case 'alpha', v = l.alpha; case 'a', v = l.a; case 'theta', v = l.theta; case 'd', v = l.d; case 'offset', v = l.offset; case 'sigma', v = l.sigma; case 'RP', if l.sigma == 0, v = 'R'; else v = 'P'; end case 'mdh', v = l.mdh; case 'G', v = l.G; case 'I', v = l.I; case 'r', v = l.r; case 'Jm', v = l.Jm; case 'B', v = l.B; case 'Tc', v = l.Tc; case 'qlim', v = l.qlim; case 'islimit', if s(2).type ~= '()' error('expecting argument for islimit method'); end q = s(2).subs{1}; v = (q > l.qlim(2)) - (q < l.qlim(1)); case 'm', v = l.m; case 'dh', v = [l.alpha l.A l.theta l.D l.sigma]; case 'dyn', dyn(l); case 'A', if s(2).type ~= '()' error('expecting argument for A method'); else args = s(2).subs; v = A(l,args{1}); end case 'nofriction', q = s(2).subs; v = nofriction(l,q{:}); otherwise, disp('Unknown method ref') end case '()' if numel(s) == 1 v = builtin('subsref', l, s); else z = s(1).subs; % cell array k = z{1}; l = l(k); v_subset = subsref(l, s(2:end)); v = v_subset; % put subset back; end otherwise error('only .field supported') end %switch endfunction function T = A(L, q) %Link.A Link transform matrix % % T = L.A(Q) is the 4x4 link homogeneous transformation matrix corresponding % to the link variable Q which is either theta (revolute) or d (prismatic). % % 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. if L.mdh == 0 T = linktran([L.alpha L.a L.theta L.d L.sigma], ... q+L.offset); else T = mlinktran([L.alpha L.a L.theta L.d L.sigma], ... q+L.offset); end endfunction % A() function t = linktran(a, b, c, d) %LINKTRAN Compute the link transform from kinematic parameters % % LINKTRAN(alpha, an, theta, dn) % LINKTRAN(DH, q) is a homogeneous % transformation between link coordinate frames. % % alpha is the link twist angle % an is the link length % theta is the link rotation angle % dn is the link offset % sigma is 0 for a revolute joint, non-zero for prismatic % % In the second case, q is substitued for theta or dn according to sigma. % % Based on the standard Denavit and Hartenberg notation. % Copright (C) Peter Corke 1993 if nargin == 4, alpha = a; an = b; theta = c; dn = d; else if numcols(a) < 4, error('too few columns in DH matrix'); end alpha = a(1); an = a(2); if numcols(a) > 4, if a(5) == 0, % revolute theta = b; dn = a(4); else % prismatic theta = a(3); dn = b; end else theta = b; % assume revolute if sigma not given dn = a(4); end end sa = sin(alpha); ca = cos(alpha); st = sin(theta); ct = cos(theta); t = [ ct -st*ca st*sa an*ct st ct*ca -ct*sa an*st 0 sa ca dn 0 0 0 1]; endfunction %MLINKTRANS Compute the link transform from kinematic parameters % % MLINKTRANS(alpha, an, theta, dn) % MLINKTRANS(DH, q) is a homogeneous % transformation between link coordinate frames. % % alpha is the link twist angle % an is the link length % theta is the link rotation angle % dn is the link offset % sigma is 0 for a revolute joint, non-zero for prismatic % % In the second case, q is substitued for theta or dn according to sigma. % % Based on the modified Denavit and Hartenberg notation. % Copright (C) Peter Corke 1993 function t = mlinktrans(a, b, c, d) if nargin == 4, alpha = a; an = b; theta = c; dn = d; else if numcols(a) < 4, error('too few columns in DH matrix'); end alpha = a(1); an = a(2); if numcols(a) > 4, if a(5) == 0, % revolute theta = b; dn = a(4); else % prismatic theta = a(3); dn = b; end else theta = b; % assume revolute if no sigma given dn = a(4); end end sa = sin(alpha); ca = cos(alpha); st = sin(theta); ct = cos(theta); t = [ ct -st 0 an st*ca ct*ca -sa -sa*dn st*sa ct*sa ca ca*dn 0 0 0 1]; endfunction function dyn(l) %Link.dyn Display the 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 element. if length(l) > 1 for j=1:length(l) ll = l(j); fprintf('%d: %f; %f %f %f; %f %f %f\n', ... j, ll.m, ll.r, diag(ll.I)); %dyn(ll); end return; end display(l); if ~isempty(l.m) fprintf(' m = %f\n', l.m) end if ~isempty(l.r) fprintf(' r = %f %f %f\n', l.r); end if ~isempty(l.I) fprintf(' I = | %f %f %f |\n', l.I(1,:)); fprintf(' | %f %f %f |\n', l.I(2,:)); fprintf(' | %f %f %f |\n', l.I(3,:)); end if ~isempty(l.Jm) fprintf(' Jm = %f\n', l.Jm); end if ~isempty(l.B) fprintf(' Bm = %f\n', l.B); end if ~isempty(l.Tc) fprintf(' Tc = %f(+) %f(-)\n', l.Tc(1), l.Tc(2)); end if ~isempty(l.G) fprintf(' G = %f\n', l.G); end if ~isempty(l.qlim) fprintf(' qlim = %f to %f\n', l.qlim(1), l.qlim(2)); end endfunction % dyn()
github
RobinAmsters/GT_mobile_robotics-master
Link.m
.m
GT_mobile_robotics-master/common/rvctools/robot/Octave/@Link/Link.m
4,156
utf_8
39a5ccb999393609550d38e629c54d5b
%LINK create a new LINK object % % A LINK object holds all information related to a robot link such as % kinematics of the joint, rigid-body inertial parameters, motor and % transmission parameters. % % LINK % LINK(link) % % Create a default link, or a clone of the passed link. % % A = LINK(q) % % Compute the link transform matrix for the link, given the joint % variable q. % % LINK([alpha A theta D sigma]) % LINK(DH_ROW) create from row of legacy DH matrix % LINK(DYN_ROW) create from row of legacy DYN matrix % % Any of the last 3 forms can have an optional flag argument which is 0 % for standard D&H parameters and 1 for modified D&H parameters. % Handling the different kinematic conventions is now hidden within the LINK % object. % % Conceivably all sorts of stuff could live in the LINK object such as % graphical models of links and so on. % MOD HISTORY % 3/99 modify to use on a LINK object % 6/99 fix the number of fields inthe object, v5.3 doesn't let me change them % mod by Francisco Javier Blanco Rodriguez <[email protected]> % Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9) % % Copyright (C) 1993-2011, 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 l = Link(dh, convention) % legacy DH matrix % link([theta d a alpha]) % link([theta d a alpha sigma]) % link([theta d a alpha sigma offset]) if nargin == 0, l.theta = 0; l.d = 0; l.a = 0; l.alpha = 0; l.sigma = 0; l.offset = 0; l.mdh = 0; % it's a legacy DYN matrix l.m = []; l.r = []; v = []; l.I = []; l.Jm = []; l.G = []; l.B = 0; l.Tc = [0 0]; l.qlim = []; l = class(l, "Link"); elseif isa(dh, 'Link') l = dh; elseif length(dh) < 4 error('must provide params (theta d a alpha)'); elseif length(dh) <= 6 % legacy DH matrix l.theta = dh(1); l.d = dh(2); l.a = dh(3); l.alpha = dh(4); if length(dh) >= 5, l.sigma = dh(5); else l.sigma = 0; end if length(dh) >= 6 l.offset = dh(6); else l.offset = 0; end l.mdh = 0; if nargin > 1 if strncmp(convention, 'mod', 3) == 1 l.mdh = 1; elseif strncmp(convention, 'sta', 3) == 1 l.mdh = 0; else error('convention must be modified or standard'); end end % we know nothing about the dynamics l.m = []; l.r = []; v = []; l.I = []; l.Jm = []; l.G = []; l.B = 0; l.Tc = [0 0]; l.qlim = []; l = class(l, "Link"); else % legacy DYN matrix l.theta = dh(1); l.d = dh(2); l.a = dh(3); l.alpha = dh(4); if length(dh) >= 5, l.sigma = dh(5); else l.sigma = 0; end l.offset = 0; l.mdh = 0; if nargin > 1 if strncmp(convention, 'mod', 3) == 1 l.mdh = 1; elseif strncmp(convention, 'sta', 3) == 1 l.mdh = 0; else error('convention must be modified or standard'); end end % it's a legacy DYN matrix if length(dh) >= 6, l.m = [dh(6)]; else l.m = []; end if length(dh) >= 9, l.r = dh(7:9); else l.r = []; end if length(dh) >= 15, v = dh(10:15); l.I = [ v(1) v(4) v(6) v(4) v(2) v(5) v(6) v(5) v(3)]; else v = []; l.I = []; end if length(dh) >= 16, l.Jm = dh(16); else l.Jm = []; end if length(dh) >= 17, l.G = dh(17); else l.G = []; end if length(dh) >= 18, l.B = dh(18); else l.B = 0; end if length(dh) >= 20, l.Tc = dh(19:20); else l.Tc = [0 0]; end l.qlim = []; l = class(l, "Link"); end endfunction
github
qhtian/CaCLEAN-master
CICRrebuildSimp.m
.m
CaCLEAN-master/CICRrebuildSimp.m
5,741
utf_8
c5178a88615def815466088aa13c31fa
function S=CICRrebuildSimp(S,varargin) %% CleanObj=CICRrebuildSimp(CleanObj,varargin); % CICRrebuildSimp calculates the upstroke of a calcium transient from the % calculated calcium release map that is derived with CaCLEAN algorithm. % % Inputs: % CleanObj: the struct result from CaCLEAN (CICRcleanSimp) function. % Name-Value Parameters: % DecayFF0Rate: default 0.03. The program follows F = F - dF/F0*K*t. % ConsiderDiffusion: default true. % % Output: % CleanObj: the struct containing the calculated upstroke of a % calcium transient. % % Qinghai Tian % Institute for Molecular Cellbiology % Medical Facalty of University of % Saarland. % Homburg, Germany. % [email protected] %% p=inputParser; p.addParameter('DecayFF0Rate',0.03,@(x)isscalar(x) && x>=0); % In F = F - dF/F0 * K * t. p.addParameter('ConsiderDiffusion',1,@(x)isscalar(x) && x>=0); % In F = F - dF/F0 * K * t. parse(p, varargin{:}); p=p.Results; ConsiderDiffusion=p.ConsiderDiffusion; DecayFF0Rate=p.DecayFF0Rate; CPU_NumCores=feature('NumCores'); %% Apply Ca diffusion. Snumel=numel(S); for j=1:Snumel fprintf(' %0.0f / %0.0f%-34s 0%%',j,Snumel,' Calcium diffusing:'); % PSFdiffusionHalf=generatePSF([S(j).xyt_dim(1:2),S(j).xyt_dim(3)/2],S(j).CaDiffuseK); PSFdiffusionHalf=S(j).CLEANPSF; PSFdiffusionHalf=PSFdiffusionHalf/sum(PSFdiffusionHalf(:)); try PSFdiffusion=S(j).DiffusionPSF; catch PSFdiffusion=generatePSF(S.xyt_dim,S.CaDiffuseK); end CICRrebuiltStack=double(S(j).CaReleaseCounting); Isiz=size(CICRrebuiltStack); % Diffusion. for k=1:Isiz(3) if ConsiderDiffusion if k==1 CICRLastTimePieceDiffuse=ImDiffuseParallel(zeros(Isiz(1),Isiz(2)),S(j).Mask,PSFdiffusion,CPU_NumCores); else CICRLastTimePieceDiffuse=ImDiffuseParallel(CICRrebuiltStack(:,:,k-1),S(j).Mask,PSFdiffusion,CPU_NumCores); end else if k==1 CICRLastTimePieceDiffuse=zeros(Isiz(1),Isiz(2)); else CICRLastTimePieceDiffuse=CICRrebuiltStack(:,:,k-1); end end CICRCurrTimePieceDiffuse=ImDiffuseParallel(CICRrebuiltStack(:,:,k),S(j).Mask,PSFdiffusionHalf,CPU_NumCores); CICRFF0Removal=(CICRLastTimePieceDiffuse+CICRCurrTimePieceDiffuse)*DecayFF0Rate*S(j).xyt_dim(3)/2; CICRrebuiltStack(:,:,k)=CICRLastTimePieceDiffuse+CICRCurrTimePieceDiffuse-CICRFF0Removal; % CICRrebuiltStack(:,:,k)=CICRrebuiltStack(:,:,k)*S(j).PSFAmplitude; fprintf('\b\b\b\b%3.0f%%',floor(k/size(CICRrebuiltStack,3)*100)); end CICRrebuiltStack=CICRrebuiltStack*S(j).PSFAmplitude; clear('CICRLastTimePieceDiffuse','CICRCurrTimePieceDiffuse','CICRFF0Removal'); fprintf('\n'); S(j).CICRrebuilt=CICRrebuiltStack; end end % function [PSF,CaDiffuse]=generatePSF(xyt_dim,ApparentDiffusionK) % CaDiffuse=@(t,D,x,y) exp(-(x.^2+y.^2)/(4*D*t)); % CaDiffuseSize=-30:xyt_dim(1):30; % if mod(numel(CaDiffuseSize),2)==0 % CaDiffuseSize=numel(CaDiffuseSize)/2; % CaDiffuseSize=0:xyt_dim(1):xyt_dim(1)*CaDiffuseSize; % CaDiffuseSize=cat(2,-fliplr(CaDiffuseSize(2:end)),CaDiffuseSize); % end % [x,y]=ndgrid(CaDiffuseSize,CaDiffuseSize); % PSF=CaDiffuse(xyt_dim(3)/1000,ApparentDiffusionK,x,y); % PSF_bw=PSF>max(PSF(:))*0.001; % PSF_bw=sum(PSF_bw,2); % PSF_bw=ceil(sum(PSF_bw>0)/2); % PSF_siz=(size(PSF,1)+1)/2; % PSF=PSF((PSF_siz-PSF_bw):(PSF_siz+PSF_bw),(PSF_siz-PSF_bw):(PSF_siz+PSF_bw)); % PSF=PSF/sum(PSF(:)); % end function Icon=ImDiffuseParallel(I,bw,PSF,CPUCore_Num) if size(I,1)>size(I,2); I=I'; end step=floor(size(I,2)/CPUCore_Num); stepStart=1:step:size(I,2); stepEnd=stepStart+step-1; stepEnd(end)=size(I,2); Icon=zeros(size(I)); parfor k=1:numel(stepStart) Icon=Icon+ImDiffuse(I,bw,PSF,1,size(I,1),stepStart(k),stepEnd(k)); end if size(I,1)>size(I,2); Icon=Icon'; end end function Icon=ImDiffuse(I,bw,PSF,k1,k2,j1,j2) RecrdSize=size(I); Icon=zeros(RecrdSize); PSFsiz=size(PSF); for k=k1:k2 for j=j1:j2 x1=k-(PSFsiz(1)-1)/2; x2=k+(PSFsiz(1)-1)/2; x1Spark=1; x2Spark=PSFsiz(1); if x1<1 xyshift=1-x1; x1=1; x1Spark=xyshift+1; end if x2>RecrdSize(1) xyshift=x2-RecrdSize(1); x2=RecrdSize(1); x2Spark=PSFsiz(1)-xyshift; end y1=j-(PSFsiz(2)-1)/2; y2=j+(PSFsiz(2)-1)/2; y1Spark=1; y2Spark=PSFsiz(2); if y1<1 xyshift=1-y1; y1=1; y1Spark=xyshift+1; end if y2>RecrdSize(2) xyshift=y2-RecrdSize(2); y2=RecrdSize(2); y2Spark=PSFsiz(2)-xyshift; end currPSF=PSF(x1Spark:x2Spark,y1Spark:y2Spark).*bw(x1:x2,y1:y2); currPSF_sum=sum(currPSF(:)); if currPSF_sum==0; continue; else currPSF=currPSF/currPSF_sum; end currPSF=currPSF*I(k,j); Icon(x1:x2,y1:y2)=Icon(x1:x2,y1:y2)+currPSF; end end end
github
qhtian/CaCLEAN-master
CICRsimulation.m
.m
CaCLEAN-master/CICRsimulation.m
17,643
utf_8
d15e0655e0bd3b2d6552a9633d87ba78
function varargout=CICRsimulation(varargin) %% varargout=CICRsimulation(varargin); % CICRsimulation simulates confocal recordings of cardiac calcium transient. % % Name-Value parameters: % Please check the parameter defininaitons in the first section of % the program body. % Output: % SparkWithNoise: Spark recordings with noise. % SparkNoiseFree: Spark recordings without noise. % SparkPosition: (1)ID (2)xc (3)yc (4)t_onset (5)Bgr (6)dF/F0 % (7)FWHM/2 (8)Decay. % Qinghai Tian % Institute for Molecular Cellbiology % Medical Facalty of University of % Saarland. % Homburg, Germany. % [email protected] %% Input. CPU_NumCores=feature('NumCores'); p=inputParser; p.addParameter('LaserIntensity',30,@(x)isscalar(x) && x>0 && x<=100); % Percentage. p.addParameter('DetectorOffset',400,@(x)isscalar(x) && x>0); % a.u. p.addParameter('DetectorGain',2.7,@(x)isscalar(x) && x>0); p.addParameter('DetectorGaussNoise',6.2,@(x)isscalar(x) && x>0); % a.u. p.addParameter('xyt_dim',[0.215,0.215,6.85],@(x)numel(x)==3); % In micrometer. p.addParameter('CaReleaseSigma',1,@(x)isscalar(x) && x>0); % In millisecond. p.addParameter('CaReleaseTau', 3,@(x)isscalar(x) && x>0); % In millisecond. p.addParameter('CaReleaseFWHMMax',0.2,@(x)isscalar(x) && x>0); % In micrometer. p.addParameter('CaReleaseTauFWHM',1,@(x)isscalar(x) && x>0); % In millisecond. p.addParameter('CaReleaseDurationSD',3,@(x)isscalar(x) && x>0); p.addParameter('Xdim',[],@(x)isscalar(x) && x>0); % In pixel. p.addParameter('Ydim',[],@(x)isscalar(x) && x>0); % In pixel. p.addParameter('Tdim',600,@(x)isscalar(x) && x>0); % In ms. p.addParameter('ReleaseAmplitude',[],@(x)isempty(x) || (isscalar(x) && x>0)); p.addParameter('ApparentDiffusionK',50,@(x)isscalar(x) && x>0); % In millisecond. p.addParameter('DecayFF0Rate',0.03,@(x)isscalar(x) && x>0); % In F = F - dF/F0 * K * t. p.addParameter('CaReleaseNum',35000,@(x)isscalar(x) && x>=0); p.addParameter('ExpAmp', false, @(x)islogical(x)); % Distribution. p.addParameter('RampAmp',false, @(x)islogical(x)); % Distribution. p.addParameter('CaReleaseAmp',1.0,@(x)isscalar(x) && x>0); % In dF/F0. p.addParameter('CPUNumCores',CPU_NumCores,@(x)isscalar(x) && x>0 && x<CPU_NumCores); % Parameters for the FWHM function. parse(p, varargin{:}); p=p.Results; clear('varargin') %% Parameters and sample Ca release. Gain=p.DetectorGain; xyt_dim=p.xyt_dim; Xdim=p.Xdim; Ydim=p.Ydim; Tdim=ceil(p.Tdim/xyt_dim(3)); ReleaseTrigger=Tdim*0.3; LaserIntensity=p.LaserIntensity; CaReleaseAmp=p.CaReleaseAmp; CaReleaseDurationSD=p.CaReleaseDurationSD; CaReleaseNum=p.CaReleaseNum; CaReleaseSigma=p.CaReleaseSigma; CaReleaseTau=p.CaReleaseTau; CaReleaseFWHMMax=p.CaReleaseFWHMMax; CaReleaseTauFWHM=p.CaReleaseTauFWHM; ApparentDiffusionK=p.ApparentDiffusionK; DetectorOffset=p.DetectorOffset; DetectorGaussNoise=p.DetectorGaussNoise; ReleaseAmplitude=p.ReleaseAmplitude; DecayFF0Rate=p.DecayFF0Rate; SampleCaReleaseSpark=SparkDsptSimAllInOneV1_2('Mu',xyt_dim(3),'SpR',xyt_dim(1),'TpR',xyt_dim(3),... 'FWHMMax',CaReleaseFWHMMax,'TauFWHM',CaReleaseTauFWHM,... 'Sigma',CaReleaseSigma,'Tau',CaReleaseTau); clear('CaReleaseFWHMMax','CaReleaseTauFWHM','CaReleaseSigma','CaReleaseTau'); %% Load sample bgr. if isempty(Xdim) S=SampleCell; Xdim=size(S.Bgr,1); Ydim=size(S.Bgr,2); else S=SampleCell([Xdim,Ydim]); end Bgr=single(S.Bgr); Bgr=Bgr/S.LaserIntensity*LaserIntensity; BgrBW=S.BgrBW; clear('S'); %% Pararmeters. fprintf(' ==================================================================\n') fprintf(' Spark movie settings:\n') fprintf(' %-38s%0.2f um X %0.2f um, %0.1f ms\n','Resolution (x,y,t):',xyt_dim(1),xyt_dim(2),xyt_dim(3)); fprintf(' %-38s%0.0f%%\n','Laser Intensity:',LaserIntensity); fprintf(' %-38s%0.2f\n','Device Gain:',Gain); fprintf(' %-38s%0.0f\n','CaR Number:',CaReleaseNum); fprintf(' %-38s%0.3f\n','Spark amplitude (dF/F0):',CaReleaseAmp); fprintf(' %-38s%0.3f\n','Apparent diffusion K (um^2/s):',ApparentDiffusionK); fprintf(' %-38s%0.2f / %0.2f a.u.\n','Detector offset/noise:',DetectorOffset,DetectorGaussNoise); if p.ExpAmp fprintf(' %-38sExponential, center = %0.2f\n','Amplitude distribution:',CaReleaseAmp); elseif p.RampAmp fprintf(' %-38sRamp from 0 to %0.2f\n','Amplitude distribution:',CaReleaseAmp); else fprintf(' %-38sConstant, center = %0.2f\n','Amplitude distribution:',CaReleaseAmp); end fprintf(' ==================================================================\n') %% coordinates template. fprintf(' %-38s','Generating coordinates:'); P=generateCaReleaseProbabilityMap(Xdim,1.075/xyt_dim(1),Ydim,1.935/xyt_dim(1)); [xPos,yPos]=generateCaReleaseProbabilityReleasePos(P,CaReleaseNum); CaReleaseNum=numel(xPos); tPos=round((randn(CaReleaseNum,1)*CaReleaseDurationSD)/xyt_dim(3)+ReleaseTrigger); xytTemplate=cat(2,xPos,yPos,tPos); clear('tPos','xPos','yPos','P') fprintf('done\n %-38s%0.0f\n','CaR Number New:',CaReleaseNum); %fprintf('done\n'); %% Amplitude distribution. if p.ExpAmp AmpDistribution=exprnd(CaReleaseAmp,[CaReleaseNum,1]); elseif p.RampAmp AmpDistribution=rand(CaReleaseNum,1)*CaReleaseAmp; else AmpDistribution=ones(CaReleaseNum,1)*CaReleaseAmp; end %% Ca release recording coordinates. xyt=round(rand(CaReleaseNum,1)*size(xytTemplate,1)); for k=1:numel(xyt) if xyt(k)==0 continue; end if ~BgrBW(xytTemplate(xyt(k),1),xytTemplate(xyt(k),2)); xyt(k)=0; end end while min(xyt)<=0 bw=xyt<=0; xytTemp=round(rand(sum(bw(:)),1)*size(xytTemplate,1)); xyt(bw)=xytTemp; for k=1:numel(xyt) if xyt(k)==0; continue; end if ~BgrBW(xytTemplate(xyt(k),1),xytTemplate(xyt(k),2)); xyt(k)=0; continue; end end end xyt=xytTemplate(xyt,:); clear('xytTemplate','bw','k'); %% Ca release recording. Put sparks in. CICRNoiseFree=zeros(Xdim,Ydim,Tdim,'single'); SparkPosition=zeros(CaReleaseNum,6); fprintf('%-38s 0%%',' Putting in Ca Release:'); CurrSarkSize=[size(SampleCaReleaseSpark,1),size(SampleCaReleaseSpark,2),size(SampleCaReleaseSpark,3)]; for k=1:CaReleaseNum % Define x positions to put in. x1=round(xyt(k,1)-CurrSarkSize(1)/2); x2=x1+CurrSarkSize(1)-1; x1Spark=1; x2Spark=CurrSarkSize(1); if x1<1 xyshift=1-x1; x1=1; x1Spark=xyshift+1; end if x2>Xdim xyshift=x2-Xdim; x2=Xdim; x2Spark=CurrSarkSize(1)-xyshift; end % Define y positions to put in. y1=round(xyt(k,2)-CurrSarkSize(2)/2); y2=y1+CurrSarkSize(2)-1; y1Spark=1; y2Spark=CurrSarkSize(2); if y1<1 xyshift=1-y1; y1=1; y1Spark=xyshift+1; end if y2>Ydim xyshift=y2-Ydim; y2=Ydim; y2Spark=CurrSarkSize(2)-xyshift; end % Define t positions to put in. t1=xyt(k,3); t2=t1+CurrSarkSize(3)-1; t1Spark=1; t2Spark=CurrSarkSize(3); if t1<1 xyshift=1-t1; t1=1; t1Spark=xyshift+1; end if t2>Tdim xyshift=t2-Tdim; t2=Tdim; t2Spark=CurrSarkSize(3)-xyshift; end % Calculate Bgr CurrBgr=Bgr(x1:x2,y1:y2); CurrBgr=median(CurrBgr(:)); CurSparkTemp=SampleCaReleaseSpark*AmpDistribution(k)*CurrBgr; CICRNoiseFree(x1:x2,y1:y2,t1:t2)=CICRNoiseFree(x1:x2,y1:y2,t1:t2)+... CurSparkTemp(x1Spark:x2Spark,y1Spark:y2Spark,t1Spark:t2Spark); SparkPosition(k,:)=[k,xyt(k,1),xyt(k,2),xyt(k,3),CurrBgr,... AmpDistribution(k)]; fprintf('\b\b\b\b%3.0f%%',floor(k/CaReleaseNum*100)); end clear('j','t1','t2','x1','x2','y1','y2','xyt','CurrBgr','CurrSarkSize','SampleSpark','xytTemplate') fprintf('\n'); %% Check the amplitude. if ~isempty(ReleaseAmplitude) fprintf(' %-38s','Adjusting amplitude:'); dFF0=sum(sum(sum(CICRNoiseFree,3),2),1); dFF0=dFF0/sum(Bgr(BgrBW)); FF0Ratio=max(dFF0)/ReleaseAmplitude; CICRNoiseFree=CICRNoiseFree/FF0Ratio; fprintf('done\n'); else FF0Ratio=1; end %% Apply Ca diffusion. fprintf('%-38s 0%%',' Calcium diffusing:'); p.PSFdiffusion=generatePSF(xyt_dim,ApparentDiffusionK); PSFdiffusion=p.PSFdiffusion; p.PSFdiffusionHalf=generatePSF([xyt_dim(1:2),xyt_dim(3)/2],ApparentDiffusionK); PSFdiffusionHalf=p.PSFdiffusionHalf; CICRBeforeDiffusion=CICRNoiseFree; BgrBW=imfill(BgrBW,'holes'); for k=2:Tdim % Diffusion. CICRLastTimePieceDiffuse=ImDiffuseParallel(CICRNoiseFree(:,:,k-1),BgrBW,PSFdiffusion,CPU_NumCores); CICRCurrTimePieceDiffuse=ImDiffuseParallel(CICRNoiseFree(:,:,k),BgrBW,PSFdiffusionHalf,CPU_NumCores); CICRFF0Removal=(CICRLastTimePieceDiffuse+CICRCurrTimePieceDiffuse)*DecayFF0Rate*xyt_dim(3)/2; CICRNoiseFree(:,:,k)=CICRLastTimePieceDiffuse+CICRCurrTimePieceDiffuse-CICRFF0Removal; fprintf('\b\b\b\b%3.0f%%',floor(k/Tdim*100)); end clear('CICRLastTimePieceDiffuse','CICRCurrTimePieceDiffuse','CICRFF0Removal'); fprintf('\n'); %% Record the Release Ca Pos. SparkPositionMovie=zeros(size(CICRNoiseFree),'single'); for k=1:size(SparkPosition,1) SparkPosition(k,6)=SparkPosition(k,6)/FF0Ratio; SparkPositionMovie(SparkPosition(k,2),SparkPosition(k,3),SparkPosition(k,4))=... SparkPositionMovie(SparkPosition(k,2),SparkPosition(k,3),SparkPosition(k,4))+SparkPosition(k,6); end %% Add Poissonian noise. fprintf(' %-38s','Generating noise:'); SparkOnCellWithPoissonNoise=zeros(size(CICRNoiseFree),'single'); parfor k=1:size(CICRNoiseFree,3) SparkOnCellWithPoissonNoise(:,:,k)=Gain*poissrnd((CICRNoiseFree(:,:,k)+Bgr)/Gain); end % Final movie. CICRRecording=SparkOnCellWithPoissonNoise + DetectorOffset+randn(size(SparkOnCellWithPoissonNoise))*DetectorGaussNoise; fprintf('done\n') %% Output if nargout==1 output.CaRelease=CICRBeforeDiffusion; output.CaT=CICRRecording; output.CaTNoiseFree=CICRNoiseFree; output.CaReleasePos=SparkPositionMovie; output.CaReleaseInfo=SparkPosition; output.CaReleaseInfoFormat='(1)ID (2)dF/F0 (3)Bgr (4)xc (5)yc (6)t_onset'; output.SampleCaRelease=SampleCaReleaseSpark; output.Bgr=Bgr; output.BgrBW=BgrBW; output.InputParameter=p; varargout{1}=output; end end function Icon=ImDiffuseParallel(I,bw,PSF,CPUCore_Num) if size(I,1)>size(I,2); I=I'; end step=floor(size(I,2)/CPUCore_Num); stepStart=1:step:size(I,2); stepEnd=stepStart+step-1; stepEnd(end)=size(I,2); Icon=zeros(size(I)); parfor k=1:numel(stepStart) Icon=Icon+ImDiffuse(I,bw,PSF,1,size(I,1),stepStart(k),stepEnd(k)); end if size(I,1)>size(I,2); Icon=Icon'; end end function Icon=ImDiffuse(I,bw,PSF,k1,k2,j1,j2) Xdim=size(I,1); Ydim=size(I,2); Icon=zeros([Xdim,Ydim]); PSFsiz=size(PSF); for k=k1:k2 for j=j1:j2 x1=k-(PSFsiz(1)-1)/2; x2=k+(PSFsiz(1)-1)/2; x1Spark=1; x2Spark=PSFsiz(1); if x1<1 xyshift=1-x1; x1=1; x1Spark=xyshift+1; end if x2>Xdim xyshift=x2-Xdim; x2=Xdim; x2Spark=PSFsiz(1)-xyshift; end y1=j-(PSFsiz(2)-1)/2; y2=j+(PSFsiz(2)-1)/2; y1Spark=1; y2Spark=PSFsiz(2); if y1<1 xyshift=1-y1; y1=1; y1Spark=xyshift+1; end if y2>Ydim xyshift=y2-Ydim; y2=Ydim; y2Spark=PSFsiz(2)-xyshift; end currPSF=PSF(x1Spark:x2Spark,y1Spark:y2Spark).*bw(x1:x2,y1:y2); currPSF_sum=sum(currPSF(:)); if currPSF_sum==0; continue; else currPSF=currPSF/currPSF_sum; end currPSF=currPSF*I(k,j); Icon(x1:x2,y1:y2)=Icon(x1:x2,y1:y2)+currPSF; end end end function varargout=SparkDsptSimAllInOneV1_2(varargin) %% Spark simulation with decriptive model. %% Input. p=inputParser; % Parameters for the HillExp function. p.addParameter('Mu',30,@(x)isscalar(x)); % In millisecond. p.addParameter('Sigma',6,@(x)isscalar(x)); % In millisecond. p.addParameter('Tau',40,@(x)isscalar(x)); % In millisecond. % Parameters for the FWHM function. p.addParameter('FWHMMax',0.56,@(x)isscalar(x)); % In micrometer. p.addParameter('TauFWHM',15,@(x)isscalar(x)); % In millisecond. p.addParameter('SpR',0.28,@(x)isscalar(x)); % In micrometer. p.addParameter('TpR',1,@(x)isscalar(x)); % In millisecond. p.addParameter('DecayLimit',0.001,@(x)isscalar(x) && x<=0.01 && x>0); parse(p, varargin{:}); p=p.Results; clear('varargin') %% 2D Gaussian surface on X and Y, and ExpExp on temporal dimension. % p(1), amplitude; p(2), mu; p(3), exponential tau; p(4), gaussian sigma. GauConvExpFWHM=@(FWHMMax,T,Mu,TauFWHM) FWHMMax*(1-exp((-(T-Mu)./TauFWHM))).*((1-exp((... -(T-Mu)./TauFWHM)))>0)+1e-9; GauConvExp=@(x,AmpMax,Mu,Tau,Sigma) AmpMax/2.*exp((Sigma^2+2*Tau*(Mu-x))/2/Tau^2).*(1-(Sigma^2+... Tau*(Mu-x))./abs(Sigma^2+Tau*(Mu-x)).*erf(abs(Sigma^2+Tau*(Mu-x))/sqrt(2)/Sigma/Tau)); GauConvExpSpark=@(X,Y,T,FWHMMax,Mu,TauFWHM,AmpMax,Tau,Sigma) exp(-(X.^2+Y.^2)/2./(... GauConvExpFWHM(FWHMMax,T,Mu,TauFWHM)).^2).*GauConvExp(T,AmpMax,Mu+Sigma*2,Tau,Sigma); %% Dimensions. tlen=-p.Tau*log(p.DecayLimit)+round(p.Mu); T=0:p.TpR:tlen; PositivePart=0:p.SpR:p.FWHMMax*3; NegativePart=sort(PositivePart(2:end),'descend')*(-1); XYrange=[NegativePart PositivePart]; [X,Y,T]=ndgrid(XYrange,XYrange,T); clear('tlen','PositivePart','NegativePart','XYrange') %% Generate spark. spark=GauConvExpSpark(X,Y,T,p.FWHMMax,p.Mu,p.TauFWHM,1,p.Tau,p.Sigma); clear('X','Y','T','HillexpampSpark','Amp','FWHM') %% Normalization. spark=spark/max(spark(:)); %% Remove zeros in the matrix / Shrink the matrix. spark_positive_index=find(spark>0); [spark_x,spark_y,spark_t]=ind2sub(size(spark),spark_positive_index); spark=spark(min(spark_x):max(spark_x),min(spark_y):max(spark_y),min(spark_t):max(spark_t)); %% Output. if nargout==1 varargout(1) = {spark}; end if nargout==2 varargout(1) = {spark}; varargout(2) = {linescan}; end end function I=generateCaReleaseProbabilityMap(Xdim,xspace,Ydim,yspace) sizsigma=0.5; % pixel; 0.107um. Gau2D=@(x,y,x0,y0,sigma) exp(-((x-x0).^2+(y-y0).^2)/2/sigma^2); I=zeros(Xdim,Ydim); [x,y]=ndgrid(1:Xdim,1:Ydim); x0=1:xspace:Xdim; y0=1:yspace:Ydim; for k=1:numel(x0) for j=1:numel(y0) I=I+Gau2D(x,y,x0(k),y0(j),sizsigma); end end I=I/max(I(:)); end function [xPos,yPos]=generateCaReleaseProbabilityReleasePos(P,NumCaR) [x,y]=ndgrid(1:size(P,1),1:size(P,2)); P=round(P*NumCaR/sum(P(:))); xPos=[]; yPos=[]; for k=1:size(P,1) for j=1:size(P,2) if P(k,j)>0 currX=ones(P(k,j),1)*x(k,j); xPos=cat(1,xPos,currX); currY=ones(P(k,j),1)*y(k,j); yPos=cat(1,yPos,currY); end end end end function [PSF,CaDiffuse]=generatePSF(xyt_dim,ApparentDiffusionK) CaDiffuse=@(t,D,x,y) exp(-(x.^2+y.^2)/(4*D*t)); CaDiffuseSize=-30:xyt_dim(1):30; if mod(numel(CaDiffuseSize),2)==0 CaDiffuseSize=numel(CaDiffuseSize)/2; CaDiffuseSize=0:xyt_dim(1):xyt_dim(1)*CaDiffuseSize; CaDiffuseSize=cat(2,-fliplr(CaDiffuseSize(2:end)),CaDiffuseSize); end [x,y]=ndgrid(CaDiffuseSize,CaDiffuseSize); PSF=CaDiffuse(xyt_dim(3)/1000,ApparentDiffusionK,x,y); PSF_bw=PSF>max(PSF(:))*0.001; PSF_bw=sum(PSF_bw,2); PSF_bw=ceil(sum(PSF_bw>0)/2); PSF_siz=(size(PSF,1)+1)/2; PSF=PSF((PSF_siz-PSF_bw):(PSF_siz+PSF_bw),(PSF_siz-PSF_bw):(PSF_siz+PSF_bw)); PSF=PSF/sum(PSF(:)); end
github
qhtian/CaCLEAN-master
CRUProps.m
.m
CaCLEAN-master/CRUProps.m
4,738
utf_8
a2eda4c85d87bd1571b297501878765c
function CleanObj=CRUProps(CleanObj) %% CleanObj=CRUProps(CleanObj); % CRUProps segments the calcium release map and calculates the % properties of single Calcium Release Units (CRU). % % Qinghai Tian % Institute for Molecular Cellbiology % Medical Facalty of University of % Saarland. % Homburg, Germany. % [email protected] %% Some parameters. xyt_dim=CleanObj(1).xyt_dim; % Some temporary parameters; minimumPixelNumPerCluster=0.2/xyt_dim(1)/xyt_dim(2); % um^2, 2.8 Pixels clusterTerritoryRadius=ceil(0.5/xyt_dim(1)); % 1.5 um. localThrsholdNormalizedToLocalMax=0.05; %% Calculation start here. hLocalMax=fspecial('disk',clusterTerritoryRadius); hLocalMax=hLocalMax==max(hLocalMax(:)); for k=1:numel(CleanObj) % Calculate the dF/F0 currMask=CleanObj(k).Mask; I=double(CleanObj(k).CaRelease2D)./double(CleanObj(k).DataBgr); I=I.*(I>0).*currMask; I(isnan(I))=0; I=I.*(I>CleanObj(k).CaCleanThreshold/mean(CleanObj(k).DataBgr(CleanObj(k).Mask))); % Just to remove values close to zero. % Local max mask. localMaxMask=imlocalmax2d(I,hLocalMax); localMaxMask=(I>(localMaxMask*localThrsholdNormalizedToLocalMax)); % Watershed CRULabel=watershed(-I); CRULabel=single(CRULabel).*currMask.*localMaxMask; CRULabelProps=regionprops(CRULabel,I,'BoundingBox','WeightedCentroid','Area'); CRUnum=numel(CRULabelProps); FWHM=nan(numel(CRULabelProps),1); Amp=nan(numel(CRULabelProps),1); Isiz=size(I); parfor j=1:CRUnum if CRULabelProps(j).Area<minimumPixelNumPerCluster; continue; end currProps=CRULabelProps(j).BoundingBox; x1=ceil(currProps(2)); if x1<1; x1=1; end x2=floor(x1+currProps(4)); if x2>Isiz(1);x2=Isiz(1); end %#ok<PFBNS> y1=ceil(currProps(1)); if y1<1; y1=1; end y2=floor(y1+currProps(3)); if y2>Isiz(2);y2=Isiz(2); end currBW=CRULabel(x1:x2,y1:y2)==j; %#ok<PFBNS> currCRU=I(x1:x2,y1:y2); %#ok<PFBNS> currCRU=currCRU.*currBW; [FWHM(j),Amp(j)]=PeakFitting(currCRU,currBW); end for j=CRUnum:-1:1 if isnan(FWHM(j)) CRULabel(CRULabel==j)=0; CRULabelProps(j)=[]; Amp(j)=[]; FWHM(j)=[]; else CRULabelProps(j).FWHM=FWHM(j)*xyt_dim(1); CRULabelProps(j).Amp=Amp(j); end end CleanObj(k).CaRelease2D_dFF0=I; CleanObj(k).CRUProps=CRULabelProps; CleanObj(k).CRULabel=CRULabel; CleanObj(k).CV_IntraCaTClusterFiring=std(Amp)/mean(Amp)*100; fprintf('\t%d\tNumCluster=%0.0f\n',k,numel(CRULabelProps)); end CV_InterCaTClusterFiring=calculateCVinterCaT(cat(3,CleanObj.CRULabel),cat(3,CleanObj.CaRelease2D_dFF0)); for k=1:numel(CleanObj) CleanObj(k).CV_InterCaTClusterFiring=CV_InterCaTClusterFiring(k); end end function [FWHM,Amp]=PeakFitting(I,mask) I=double(I); [sizey,sizex] = size(I); %% Get center of mass, amplitude, and sigma. [X,Y]=ndgrid(1:sizey,1:sizex); bwMaxLoc=(I==max(I(:))); cx=X(bwMaxLoc); if numel(cx)>1; cx=cx(1); end cy=Y(bwMaxLoc); if numel(cy)>1; cy=cy(1); end distance=sqrt((X-cx).^2+(Y-cy).^2); sigma=sqrt(sum(mask(:))/pi)/2; distance=distance(mask); I=I(mask); I_max=max(I); Dis_max=max(distance); %% Do a Gaussian fitting with mu=0 and Bgr=0. Gau=@(x,p)p(1)*exp(-x.^2/2/p(2)^2); fun_dev=@(x,y,p)sum((Gau(x,p)-y).^2); options=optimset('MaxIter',100000000,'Display','off'); p=fminsearchbnd(@(p)fun_dev(distance,I,p),[I_max sigma],... [I_max/10 sigma/10], [I_max*20 Dis_max*3],options); FWHM=p(2)*2; Amp=p(1); end function CV=calculateCVinterCaT(ClusterLabel,I) Isiz=size(ClusterLabel,3); CV=nan(Isiz,1); bw=ClusterLabel>0; for k=1:Isiz currBW=bw(:,:,k); ImProps=regionprops(currBW,I(:,:,k),'Area','MeanIntensity'); ImProps=[ImProps(:).MeanIntensity]'.*[ImProps(:).Area]'; ImProps=repmat(ImProps,[1,Isiz]); for j=1:Isiz if j==k; continue; end currImProps=regionprops(currBW,I(:,:,j),'Area','MeanIntensity'); currImProps=[currImProps(:).MeanIntensity]'.*[currImProps(:).Area]'; ImProps(:,j)=currImProps; end currCV=std(ImProps,0,2)./mean(ImProps,2)*100; CV(k)=mean(currCV); end end
github
thisjunjiang/Differential_Privacy-master
AddLapNoise.m
.m
Differential_Privacy-master/AddLapNoise.m
359
utf_8
23a58f6a506b0a3129a36ffbfd6d0969
% This function adds noise directly to the probability. % sens is sensitivity. epsilon is the privacy parameter. % what should the sens be? function Pij_hat = AddLapNoise(Pij,sens,epsilon) [m,n]=size(Pij); lambda = sens/epsilon; Delta_ij = laprnd(0,lambda,m,n); Pij_hat = Pij + Delta_ij; Pij_hat(Pij_hat<0)=0; Pij_hat(Pij_hat>1)=1; end
github
thisjunjiang/Differential_Privacy-master
cdf_poibin.m
.m
Differential_Privacy-master/cdf_poibin.m
1,248
utf_8
da7ac8bdb397026095cc495e86240ca9
% This function calculates the pmf and cdf of the poisson binomial % distribution. This function has been verified with the library provided % by Yili Hong in R. % function [a,b,pmf,cdf]=cdf_poibin(Pij,sens,epsilon) % Pij_hat = AddLapNoise(Pij,sens,epsilon) function [a,b,pmf,cdf]=cdf_poibin(Pij_hat) i = sqrt(-1); %[m,n] = size(Pij_hat); Pj = Pij_hat(:); %num = m*n; num = length(Pj); omega = 2*pi/(num + 1); Z = zeros(num,num); for l = 1:num Z(:,l)=cos(omega*l)+i*sin(omega*l); end Z = bsxfun(@plus,(1-Pj),bsxfun(@times,Pj,Z)); Z_modu = abs(Z); Z_arg = atan2(imag(Z),real(Z)); %Z_arg = angle(Z); d = exp(sum(log(Z_modu))); Z_argtemp = sum(Z_arg); a = d.*cos(Z_argtemp); b = d.*sin(Z_argtemp); x = a + i*b; x = [1,x]; xx = x/(num+1); pmf = real(fft(xx)); cdf = zeros(1,num+1); for k = 1:num+1 cdf(1,k)= sum(pmf(1:k)); end % generate a count according to the cdf count = Generate(cdf); end % This function generates a count of events according to the input cdf. function count = Generate(cdf) temp = rand(1); cdf_temp = temp - cdf; count_temp = find(cdf_temp<=0); count = count_temp(1)-1; end
github
thisjunjiang/Differential_Privacy-master
CGenerate.m
.m
Differential_Privacy-master/CGenerate.m
837
utf_8
502570713b69ea5fb6c30994d93c6393
% This function generates a count of events using counts function count = CGenerate(x1,y1,x2,y2) counts = getCounts(x1,y1,x2,y2); % min_count = min(counts); % max_count = max(counts); % num_bins = max_count - min_count + 1; % h = histogram(counts, num_bins); % hvalues = h.Values; % % length = sum(hvalues~=0); % hcounts = zeros(length,2); [hcounts(:,2),hcounts(:,1)] = hist(counts, unique(counts)); len = length(hcounts); hprobs = zeros(len,1); hprobs(2:len,1) = AddLapNoise2(hcounts(2:len,2),1,0.5); if sum(hprobs)<1 hprobs(1,1) = 1-sum(hprobs); else hprobs(1,1) = 0; end counts_cdf = cumsum(hprobs(:,1)); temp = rand(1); cdf_temp = temp - counts_cdf; count_temp = find(cdf_temp<=0); count = hcounts(count_temp(1),1); end
github
thisjunjiang/Differential_Privacy-master
MapGenerate2.m
.m
Differential_Privacy-master/MapGenerate2.m
366
utf_8
e57411f6b83cbfdd5c7dd4b2ffe39926
% This funciton generates a map using counts. function map = MapGenerate2(x_start, y_start, M, N, medium) map = zeros(M,N); for i = 1:M x1 = x_start+medium*(i-1); x2 = x1+medium-1; for j = 1:N y1 = y_start+medium*(j-1); y2 = y1+medium-1; map(i,j) = CGenerate(x1,y1,x2,y2); end end end
github
thisjunjiang/Differential_Privacy-master
getCounts.m
.m
Differential_Privacy-master/getCounts.m
881
utf_8
44370df0336cfc38845edf9dd835dff5
% This function gets event counts for this area for each time interval. % x1, y1, x2, y2 are all coordinates in the map matrix, i.e starting from 1. function counts = getCounts(x1, y1, x2, y2) global m; global total_intervals; global x_min; global y_max; global data; counts = zeros(1, total_intervals); curr_interval = 1; for k = 1:m x_temp = y_max-data(k,3)+1; y_temp = data(k,2)-x_min+1; if x_temp >= x1 && x_temp <= x2 && y_temp >= y1 && y_temp <= y2 if data(k,1) == curr_interval counts(1,curr_interval) = counts(1,curr_interval)+1; else curr_interval = curr_interval+1; counts(1,curr_interval) = counts(1,curr_interval)+1; end end end end % With the counts, you can fit a distribution. Refer histfit() in MATLAB.
github
thisjunjiang/Differential_Privacy-master
AddLapNoise2.m
.m
Differential_Privacy-master/AddLapNoise2.m
1,878
utf_8
a7140fcdbde5098ebc5a2b91d588dbb4
% This function adds noise to the counts. % Nij is the count of each cell. M is the total intervals. % sens here should be 1 function Pij_hat = AddLapNoise2(Nij,sens,epsilon) global total_intervals; [m,n]=size(Nij); lambda = sens/epsilon; Delta_ij = laprnd(0,lambda,m,n); Nij_hat = Nij + Delta_ij; Pij_hat = Nij_hat/total_intervals; Pij_hat(Pij_hat<0)=0; Pij_hat(Pij_hat>1)=1; end % The Gaussian mechanism with parameter sigma adds noise scaled to % N(0,sigma^2) to each of the d components. % R = normrnd(MU,SIGMA,m,n) % MU--mena, SIGMA--standard variance % This function adds Gaussian noise to the probabilities. function Pij_hat = AddGauNoise(Pij,sens2,epsilon,delta) % epsilon (0,1), delta should be small % c^2 > 2ln(1.25/delta) c = sqrt(2*log(1.25/delta)); % sigma >= c*sens2/epsilon sigma = c*sens2/epsilon; [m,n]=size(Nij); Delta_ij = normrnd(0,sigma,m,n); Pij_hat = Pij + Delta_ij; Pij_hat(Pij_hat<0)=0; Pij_hat(Pij_hat>1)=1; end % This function adds Gaussian noise to the counts. function Pij_hat = AddGauNoise2(Nij,M,sens2,epsilon) % epsilon (0,1) % c^2 > 2ln(1.25/delta) c = sqrt(2*log(1.25/delta)); % sigma >= c*sens/epsilon sigma = c*sens2/epsilon; [m,n]=size(Nij); Delta_ij = normrnd(0,sigma,m,n); Nij_hat = Nij + Delta_ij; Pij_hat = Nij_hat/M; Pij_hat(Pij_hat<0)=0; Pij_hat(Pij_hat>1)=1; end % This function generates m*n laplace noise. function x = laprnd(mu,lambda,m,n) % mu is mean, sigma >= 0 is standard deviation, lambda is a scale parameter. % m and n represent the number of rows and columns of the generated random % matrix % sigma = sqrt(2)*b; % lambda = sigma/sqrt(2); u = rand(m,n)-0.5; x = mu - lambda*sign(u).*log(1-2*abs(u)); end % test laplace distribution % x = laprnd(0,1,1,10000); mean(x); std(x); hist(x,100)
github
thisjunjiang/Differential_Privacy-master
MapGenerate1.m
.m
Differential_Privacy-master/MapGenerate1.m
388
utf_8
c56c8583444cd8b238f92484385e33e4
% This funciton generates a map using the model of poisson binomial. function map = MapGenerate1(x_start, y_start, M, N, medium) map = zeros(M,N); for i = 1:M x1 = x_start+medium*(i-1); x2 = x1+medium-1; for j = 1:N y1 = y_start+medium*(j-1); y2 = y1+medium-1; map(i,j) = PBGenerate(x1,y1,x2,y2); end end end
github
thisjunjiang/Differential_Privacy-master
BGenerate.m
.m
Differential_Privacy-master/BGenerate.m
409
utf_8
11b420035623e282b4995c397d88cea1
% This function generates a count of events using bernoulli distribution function count = BGenerate(x1,y1,x2,y2) count = 0; [count_cells, ~] = getProb(x1, y1, x2, y2); Pij_hat = AddLapNoise2(count_cells,1,0.5); %laplacian noise added Pj = Pij_hat(:); num = length(Pj); for i = 1:num temp = rand(1); if(temp <= Pj(i)) count = count+1; end end end
github
thisjunjiang/Differential_Privacy-master
PBGenerate.m
.m
Differential_Privacy-master/PBGenerate.m
391
utf_8
af971d679e3a7ef717bafd6ef86d79d3
% This function generates a count of events according to poison binomial function count = PBGenerate(x1,y1,x2,y2) [count_cells, ~] = getProb(x1, y1, x2, y2); Pij_hat = AddLapNoise2(count_cells,1,0.5); %laplacian noise added [~,~,~,cdf] = cdf_poibin(Pij_hat); temp = rand(1); cdf_temp = temp - cdf; count_temp = find(cdf_temp<=0); count = count_temp(1)-1; end
github
thisjunjiang/Differential_Privacy-master
pmf_poibin.m
.m
Differential_Privacy-master/pmf_poibin.m
1,347
utf_8
e1828fe0509a80d671a1a96d8966f0cf
function [a,b,pmf]=cdf_poibin(Pij_hat) i = sqrt(-1); %[m,n] = size(Pij_hat); Pj = Pij_hat(:); %num = m*n; num = length(Pj); omega = 2*pi/(num + 1); Z = zeros(num,num); for l = 1:num Z(:,l)=cos(omega*l)+i*sin(omega*l) end Z = bsxfun(@plus,(1-Pj),bsxfun(@times,Pj,Z)); Z_modu = abs(Z); Z_arg = atan2(imag(Z),real(Z)); %Z_arg = angle(Z); d = exp(sum(log(Z_modu))); Z_argtemp = sum(Z_arg); a = d.*cos(Z_argtemp); b = d.*sin(Z_argtemp); x = a + i*b; x = [1,x]; xx = x/(num+1); pmf = fft(xx); end % The function adds noise directly to the probability. function Pij_hat = AddNoise(Pij,sens,epsilon) [m,n]=size(Pij); lambda = sens/epsilon; Delta_ij = laprnd(0,lambda,m,n); Pij_hat = Pij + Delta_ij; Pij_hat(Pij_hat<0)=0; Pij_hat(Pij_hat>1)=1; end % The function adds noise to the counts. function AddNoise2(Nij,M,sens,epsilon) end function x = laprnd(mu,lambda,m,n) %mu is mean, sigma >= 0 is standard deviation, lambda is a scale parameter. % m and n represent the number of rows and columns of the generated random % matrix % sigma = sqrt(2)*b; % lambda = sigma/sqrt(2); u = rand(m,n)-0.5; x = mu - lambda*sign(u).*log(1-2*abs(u)); end %test laplace distribution %x = laprnd(0,1,1,10000); mean(x); std(x); hist(x,100)
github
thisjunjiang/Differential_Privacy-master
MapGenerate3.m
.m
Differential_Privacy-master/MapGenerate3.m
398
utf_8
5b0982a6ac8ea8f77f8787d6f4a7b924
% This funciton generates a map based on bernoulli distribution of each cell. function map = MapGenerate3(x_start, y_start, M, N, medium) map = zeros(M,N); for i = 1:M x1 = x_start+medium*(i-1); x2 = x1+medium-1; for j = 1:N y1 = y_start+medium*(j-1); y2 = y1+medium-1; map(i,j) = BGenerate(x1,y1,x2,y2); end end end
github
HanyangLiu/BCLS-master
BalanceEvl.m
.m
BCLS-master/BalanceEvl.m
623
utf_8
168b5e79f43097e1e018048dde2d7844
%% Normalized Entropy % Evaluate the balance of the distribution of the clustering function [entro, stDev, RME] = BalanceEvl(k, N_cluster) aa = []; bb = []; for i=1:k N = sum(N_cluster); Ni = N_cluster(i)+eps; a = Ni/N * log(Ni/N); aa(i) = a; b = (Ni-N/k)^2; bb(i) = b; end entro = -1/(log(k)) * sum(aa); % Entropy of the cluster distribution; (0,1) stDev = (1/(k-1)*sum(bb))^(1/2); % Standard deviation in cluster size (SDCS) RME = (min(N_cluster))/(N/k); % ratio of minimum to expected (RME); (0,1) end
github
HanyangLiu/BCLS-master
BCLS_ALM.m
.m
BCLS-master/BCLS_ALM.m
1,455
utf_8
2a844bb16dc96d459a84fd2bcf2cba46
% function [ID, Y, Obj] = BCLS_ALM(X, Y, gamma, lam, mu) % BCLS_ALM % min_Y,W,b ||X'W+1b'-Y||^2 + gamma*||W||^2 + lam*Tr(Z'11'Z) + mu/2*||Y-Z + 1/mu*Lambda||^2 % INPUT: % X: data matrix (d by n), already processed by PCA with 80%~90% information preserved % Y: randomly initialized label matrix (n by c) % Parameters: gamma and lam are the parameters respectively corresponding to Eq.(13) in the paper % OUTPUT: % ID: indicator vector (n by 1) % Y: generated label matrix (b by c) ITER = 1200; [dim, n] = size(X); H = eye(n) - 1/n*ones(n); X = X*H; c = size(Y,2); % number of clusters Lambda = zeros(n,c); rho = 1.005; P = eye(dim)/(X*X'+gamma*eye(dim)); for iter = 1:ITER display(['Solving alternatively...',num2str(iter)]); % Solve W and b W = P*(X*Y); b = mean(Y)'; E = X'*W + ones(n,1)*b' - Y; % Solve Z % Z = (mu*eye(n)+2*lam*ones(n))\(mu*Y + Lambda); % original solution - O(n^3) Z = (-2*lam*ones(n)+(mu+2*n*lam)*eye(n))/(mu^2+2*n*lam*mu)*(mu*Y+Lambda); % new solution - O(n^2) % Solve Y V = 1/(2+mu)*(2*X'*W + 2*ones(n,1)*b' + mu*Z - Lambda); [~, ind] = max(V,[],2); Y = zeros(n,c); Y((1:n)' + n*(ind-1)) = 1; % Update Lambda and mu according to ALM Lambda = Lambda + mu*(Y-Z); mu = min(mu*rho, 10^5); % Objective value Obj(iter) = trace(E'*E) + gamma*trace(W'*W) + lam*trace(Y'*ones(n)*Y); end; [~,ID] = max(Y,[],2); end
github
AlokD123/Hybrid-Storage_Project-master
DesignMtx.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/DesignMtx.m
12,483
utf_8
271b07e5f2563a4faf351acba24474c4
function Phi = DesignMtx(indepvar,depvar,modelterms) % DesigMtx creates a general polynomial regression design matrix % (n-th order polynomial fit, ALL terms included) % % Adapted from Polyfitn... Refer to license at end % Source: https://www.mathworks.com/matlabcentral/fileexchange/34765-polyfitn % Date: June 1, 2018 % % Polyfitn fits a polynomial regression model of one or more % independent variables, of the general form: % % z = f(x,y,...) + error % % arguments: (input) % indepvar - (n x p) array of independent variables as columns % n is the number of data points % p is the dimension of the independent variable space % % IF n == 1, then I will assume there is only a % single independent variable. % % depvar - (n x 1 or 1 x n) vector - dependent variable % length(depvar) must be n. % % Only 1 dependent variable is allowed, since I also % return statistics on the model. % % modelterms - defines the terms used in the model itself % % IF modelterms is a scalar integer, then it designates % the overall order of the model. All possible terms % up to that order will be employed. Thus, if order % is 2 and p == 2 (i.e., there are two variables) then % the terms selected will be: % % {constant, x, x^2, y, x*y, y^2} % % Beware the consequences of high order polynomial % models. % % IF modelterms is a (k x p) numeric array, then each % row of this array designates the exponents of one % term in the model. Thus to designate a model with % the above list of terms, we would define modelterms as % % modelterms = [0 0;1 0;2 0;0 1;1 1;0 2] % % If modelterms is a character string, then it will be % parsed as a list of terms in the regression model. % The terms will be assume to be separated by a comma % or by blanks. The variable names used must be legal % matlab variable names. Exponents in the model may % may be any real number, positive or negative. % % For example, 'constant, x, y, x*y, x^2, x*y*y' % will be parsed as a model specification as if you % had supplied: % modelterms = [0 0;1 0;0 1;1 1;2 0;1 2] % % The word 'constant' is a keyword, and will denote a % constant terms in the model. Variable names will be % sorted in alphabetical order as defined by sort. % This order will assign them to columns of the % independent array. Note that 'xy' will be parsed as % a single variable name, not as the product of x and y. % % If modelterms is a cell array, then it will be taken % to be a list of character terms. Similarly, % % {'constant', 'x', 'y', 'x*y', 'x^2', 'x*y^-1'} % % will be parsed as a model specification as if you % had supplied: % % modelterms = [0 0;1 0;0 1;1 1;2 0;1 -1] % % Arguments: (output) % polymodel - A structure containing the regression model % polymodel.ModelTerms = list of terms in the model % polymodel.Coefficients = regression coefficients % polymodel.ParameterVar = variances of model coefficients % polymodel.ParameterStd = standard deviation of model coefficients % polymodel.DoF = Degrees of freedom remaining % polymodel.p = double sided t-probability, as a test against zero % polymodel.R2 = R^2 for the regression model % polymodel.AdjustedR2 = Adjusted R^2 for the regression model % polymodel.RMSE = Root mean squared error % polymodel.VarNames = Cell array of variable names % as parsed from a char based model specification. % % Note 1: Because the terms in a general polynomial % model can be arbitrarily chosen by the user, I must % package the erms and coefficients together into a % structure. This also forces use of a special evaluation % tool: polyvaln. % % Note 2: A polymodel can be evaluated for any set % of values with the function polyvaln. However, if % you wish to manipulate the result symbolically using % my own sympoly tools, this structure can be converted % to a sympoly using the function polyn2sympoly. There % is also a polyn2sym tool, for those who prefer the % symbolic TB. % % Note 3: When no constant term is included in the model, % the traditional R^2 can be negative. This case is % identified, and then a more appropriate computation % for R^2 is then used. % % Note 4: Adjusted R^2 accounts for changing degrees of % freedom in the model. It CAN be negative, and will always % be less than the traditional R^2 values. % % Note 5: DoF is just the number of data points minus the number of % terms to estimate. % % Note 6: p is effectively a 2-sided t-test against the % corresponding coefficient being zero. So p should be % near zero. % % Example: % mdl = polyfitn(rand(1000,1),rand(1000,1),4) % mdl = % ModelTerms: [5x1 double] % Coefficients: [0.95506 -2.2363 1.6668 -0.45408 0.55207] % ParameterVar: [3.7645 15.461 6.9479 0.42831 0.0022732] % ParameterStd: [1.9402 3.9321 2.6359 0.65446 0.047678] % DoF: 995 % p: [0.62266 0.56966 0.5273 0.48796 3.5389e-29] % R2: 0.0021445 % AdjustedR2: -0.001867 % RMSE: 0.2884 % VarNames: {'X1'} % % Only the constant term should be significantly different from zero % in this model. In fact, if we looked at a rough confidence interval % on that coefficient, we would get % % mdl.Coefficients(5) + 2*[-1 1]*mdl.ParameterStd(5) % ans = % 0.45672 0.64743 % % This interval should contain 0.5, as it does. % % Find my sympoly toolbox here: % http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=9577&objectType=FILE % % See also: polyvaln, polyfit, polyval, polyn2sympoly, sympoly % % Author: John D'Errico % Release: 2.0 % Release date: 2/19/06 if nargin<1 help polyfitn return end % get sizes, test for consistency [n,p] = size(indepvar); if n == 1 indepvar = indepvar'; [n,p] = size(indepvar); end [m,q] = size(depvar); if m == 1 depvar = depvar'; [m,q] = size(depvar); end % only 1 dependent variable allowed at a time if q~=1 error 'Only 1 dependent variable allowed at a time.' end if n~=m error 'indepvar and depvar are of inconsistent sizes.' end % check for and remove nans in data nandata = isnan(depvar) | any(isnan(indepvar),2); if any(nandata) depvar(nandata,:) = []; indepvar(nandata,:) = []; n = size(indepvar,1); end indepvar_s=indepvar; % do we need to parse a supplied model? if iscell(modelterms) || ischar(modelterms) [modelterms,varlist] = parsemodel(modelterms,p); if size(modelterms,2) < p modelterms = [modelterms, zeros(size(modelterms,1),p - size(modelterms,2))]; end elseif length(modelterms) == 1 % do we need to generate a set of modelterms? [modelterms,varlist] = buildcompletemodel(modelterms,p); elseif size(modelterms,2) ~= p error 'ModelTerms must be a scalar or have the same # of columns as indepvar' else varlist = repmat({''},1,p); end nt = size(modelterms,1); % check for replicate terms if nt>1 mtu = unique(modelterms,'rows'); if size(mtu,1)<nt warning 'Replicate terms identified in the model.' end end % build the design matrix M = ones(n,nt); scalefact = ones(1,nt); for i = 1:nt for j = 1:p M(:,i) = M(:,i).*indepvar_s(:,j).^modelterms(i,j); end end % Return design matrix Phi=M; % ================================================== % =============== begin subfunctions =============== % ================================================== function [modelterms,varlist] = buildcompletemodel(order,p) % % arguments: (input) % order - scalar integer, defines the total (maximum) order % % p - scalar integer - defines the dimension of the % independent variable space % % arguments: (output) % modelterms - exponent array for the model % % varlist - cell array of character variable names % build the exponent array recursively if p == 0 % terminal case modelterms = []; elseif (order == 0) % terminal case modelterms = zeros(1,p); elseif (p==1) % terminal case modelterms = (order:-1:0)'; else % general recursive case modelterms = zeros(0,p); for k = order:-1:0 t = buildcompletemodel(order-k,p-1); nt = size(t,1); modelterms = [modelterms;[repmat(k,nt,1),t]]; end end % create a list of variable names for the variables on the fly varlist = cell(1,p); for i = 1:p varlist{i} = ['X',num2str(i)]; end % ================================================== function [modelterms,varlist] = parsemodel(model,p); % % arguments: (input) % model - character string or cell array of strings % % p - number of independent variables in the model % % arguments: (output) % modelterms - exponent array for the model modelterms = zeros(0,p); if ischar(model) model = deblank(model); end varlist = {}; while ~isempty(model) if iscellstr(model) term = model{1}; model(1) = []; else [term,model] = strtok(model,' ,'); end % We've stripped off a model term. Now parse it. % Is it the reserved keyword 'constant'? if strcmpi(term,'constant') modelterms(end+1,:) = 0; else % pick this term apart expon = zeros(1,p); while ~isempty(term) vn = strtok(term,'*/^. ,'); k = find(strncmp(vn,varlist,length(vn))); if isempty(k) % its a variable name we have not yet seen % is it a legal name? nv = length(varlist); if ismember(vn(1),'1234567890_') error(['Variable is not a valid name: ''',vn,'''']) elseif nv>=p error 'More variables in the model than columns of indepvar' end varlist{nv+1} = vn; k = nv+1; end % variable must now be in the list of vars. % drop that variable from term i = strfind(term,vn); term = term((i+length(vn)):end); % is there an exponent? eflag = false; if strncmp('^',term,1) term(1) = []; eflag = true; elseif strncmp('.^',term,2) term(1:2) = []; eflag = true; end % If there was one, get it ev = 1; if eflag ev = sscanf(term,'%f'); if isempty(ev) error 'Problem with an exponent in parsing the model' end end expon(k) = expon(k) + ev; % next monomial subterm? k1 = strfind(term,'*'); if isempty(k1) term = ''; else term(k1(1)) = ' '; end end modelterms(end+1,:) = expon; end end % Once we have compiled the list of variables and % exponents, we need to sort them in alphabetical order [varlist,tags] = sort(varlist); modelterms = modelterms(:,tags); % Copyright (c) 2016, John D'Errico % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE.
github
AlokD123/Hybrid-Storage_Project-master
optNextStateLimited.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/optNextStateLimited.m
1,140
utf_8
466fa3e5c982b80d4634ca8f4623ce44
%Calculate subsequent state accounting for no inherent storage loss when %dropping below lower bound of state function [ nextE1,nextE2 ] = optNextStateLimited( E1,E2,D1,D2,L ) % Input: state, controls, load global E_MIN; global BETA; global ALPHA_D; global ALPHA_C; newE1=StateEqn1(E1,D1,BETA(1),ALPHA_D(1)); if(newE1<E_MIN(1)) %If below lower bound... if(StateEqn1(E1,D1,1,ALPHA_D(1))>=E_MIN(1)) %If would not be if with no inherent loss, ASSUME lossless nextE1=E_MIN(1); %In this case, will drop to lower bound else nextE1=newE1; %Else, doesn't matter end else nextE1=newE1; end %Repeat for second storage newE2=StateEqn2(E2,D1,D2,L,BETA(2),ALPHA_C(2),ALPHA_D(2)); if(newE2<E_MIN(2)) if(StateEqn2(E2,D1,D2,L,1,ALPHA_C(2),ALPHA_D(2))>=E_MIN(2)) nextE2=E_MIN(2); % elseif(StateEqn2(E2,D1,D2,L,1,1,1)>=E_MIN(2))&&E2<=2 nextE2=E_MIN(2); %} else nextE2=newE2; end else nextE2=newE2; end end
github
AlokD123/Hybrid-Storage_Project-master
fitStateExpr.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/fitStateExpr.m
165
utf_8
2f7a36491ae3640dc359636cfe073e0c
%Expression that is constant for a given state aggregation. Hand-engineered; can be modified here function [fitExpr] = fitStateExpr(E1,E2,L) fitExpr=L-E2; end
github
AlokD123/Hybrid-Storage_Project-master
LimitCtrls.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/LimitCtrls.m
2,686
utf_8
7d18067d7e1790b22ce44f979a22b9c0
%To limit control (discharge), if would lead to a state out of bounds function [ D1Opt,D2Opt ] = LimitCtrls( E1,E2,D1Opt,D2Opt,t ) % Input: states, and controls (before saturation), at time t global MAX_DISCHARGE; global E_MAX; global E_MIN; global expL_State; %For D1 control... if(StateEqn1(E1,D1Opt)>E_MAX(1)) %If next state index would be higher than index of MAX_STATE... (should NOT be possible) D1Opt=0; %%% NEED TO CHECK!!! %Set control so index of next state is maximum state's index elseif(StateEqn1(E1,D1Opt)<E_MIN(1)||D1Opt>MAX_DISCHARGE(1)) %If next state index would be lower than index of MIN_STATE -or- discharge too high D1Opt=min( GetCtrl1_CurrNextState(E1,E_MIN(1)), MAX_DISCHARGE(1)); %Set control so index of next state is minimum state's index, or discharge is limited end %Repeated for D2 control... if(StateEqn2(E2,D1Opt,D2Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t))>E_MAX(2)) D2Opt=GetCtrl2_CurrNextState(E2,E_MAX(2),D1Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t)); %Set control so index of next state is maximum state's index <------------ %%% NEED TO CHECK that D2>=0 !!!!! elseif(StateEqn2(E2,D1Opt,D2Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t))<E_MIN(2)||D2Opt>MAX_DISCHARGE(2)) D2=min( GetCtrl2_CurrNextState(E2,E_MIN(2),D1Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t)), MAX_DISCHARGE(2)); %Set control so index of next state is minimum state's index, or discharge is limited %If still leads to out of bounds, increase nextE2 up to E_MAX(2)-1, and then decrease D1 down to 0 % (IN THAT ORDER, to minimize cost) if( StateEqn2(E2,D1Opt,D2,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t))>E_MAX(2) ) nextE2=E_MIN(2); while(nextE2<=(E_MAX(2)-1) && GetCtrl2_CurrNextState(E2,nextE2,D1Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t))>MAX_DISCHARGE(2)) nextE2=nextE2+1; end D1=D1Opt; while(D1>=1 && GetCtrl2_CurrNextState(E2,nextE2,D1,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t))>MAX_DISCHARGE(2) && StateEqn1(E1,D1)<E_MAX(1)) if( GetCtrl2_CurrNextState(E2,nextE2,D1-1,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t)) >=0) %If discharging remains positive, decrease D1=D1-1; else if(GetCtrl2_CurrNextState(E2,nextE2-1,D1Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t)) < MAX_DISCHARGE(2)) nextE2=nextE2-1; end break; end end D1Opt=D1; D2Opt=GetCtrl2_CurrNextState(E2,nextE2,D1Opt,expL_State(E1-E_MIN(1)+1,E2-E_MIN(2)+1,t)); else D2Opt=D2; end end end
github
AlokD123/Hybrid-Storage_Project-master
optNextStateLimited_v2.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/optNextStateLimited_v2.m
1,266
utf_8
231806c780862cf556c4dc91ebea80f8
%Calculate subsequent state accounting for no inherent storage loss when dropping below lower bound of state. %V2: added regenerative braking function [ nextE1,nextE2 ] = optNextStateLimited_v2( E1,E2,D1,D2,C2,L ) % Input: state, controls, load global E_MIN; global BETA; global ALPHA_C; global ALPHA_D; newE1=StateEqn1_wRegenBraking(E1,D1,D2,C2,L,BETA(1)); if(newE1<E_MIN(1)) %If below lower bound... if(StateEqn1_wRegenBraking(E1,D1,D2,C2,L,1)>=E_MIN(1)) %If would not be if with no inherent loss, ASSUME lossless nextE1=E_MIN(1); %In this case, will drop to lower bound else nextE1=newE1; %Else, doesn't matter end else nextE1=newE1; end %Repeat for second storage newE2=StateEqn2_wRegenBraking(E2,D2,C2,BETA(2),ALPHA_C(2),ALPHA_D(2)); if(newE2<E_MIN(2)) if(StateEqn2_wRegenBraking(E2,D2,C2,1,ALPHA_C(2),ALPHA_D(2))>=E_MIN(2)) nextE2=E_MIN(2); %{ elseif(StateEqn2(E2,D1,D2,L,1,1,1)>=E_MIN(2))&&E2<=2 nextE2=E_MIN(2); %} else nextE2=newE2; end else nextE2=newE2; end end
github
AlokD123/Hybrid-Storage_Project-master
Cuboid.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/Cuboid.m
727
utf_8
7fc2a5c64dbf4a9dc4c425819014b110
% - B.I SOLID POINT CLOUD CUBOID function [xp,yp,zp]=Cuboid(x,y,z) % - Generates coordinates for a solid cuboid composed of points a=length(x);b=length(y);c=length(z); % assigning for coding simplicity % B.I.1. Finding all x coordinates xp=zeros(1,a*b*c); % preallocating for nx=1:a if nx==1,xp(1:c*b)=(repmat(x(nx),1,c*b)); else xp(((nx-1)*c*b)+1:nx*c*b)=repmat(x(nx),1,c*b);end end % B.I.2. Finding all y coordinates yp=zeros(1,b*c); % preallocating for ny=1:b if ny==1,yp(1:c)=repmat(y(ny),1,c); else yp(((ny-1)*c)+1:ny*c)=repmat(y(ny),1,c); end end yp=repmat(yp,1,a); % B.I.3. Finding all z coordinates zp=repmat(z,1,b*a); % B.I.4. Coordinates of the cuboid generated. %P=[xp;yp;zp]; end % To Optimize
github
AlokD123/Hybrid-Storage_Project-master
optNextStateLimited_v3.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/optNextStateLimited_v3.m
1,253
utf_8
86d7bab16babedb57764b1a74fa0755e
%Calculate subsequent state accounting for no inherent storage loss when dropping below lower bound of state. %V3: single control, with regenerative braking function [ nextE1,nextE2 ] = optNextStateLimited_v3( E1,E2,U1,L ) % Input: state, control, load global E_MIN; global BETA; global ALPHA_C; global ALPHA_D; newE1=StateEqn1_wRegenBraking_v2(E1,U1,BETA(1)); if(newE1<E_MIN(1)) %If below lower bound... if(StateEqn1_wRegenBraking_v2(E1,U1,1)>=E_MIN(1)) %If would not be if with no inherent loss, ASSUME lossless nextE1=E_MIN(1); %In this case, will drop to lower bound else nextE1=newE1; %Else, doesn't matter end else nextE1=newE1; end %Repeat for second storage newE2=StateEqn2_wRegenBraking_v2(E2,U1,L,BETA(2),ALPHA_C(2),ALPHA_D(2)); if(newE2<E_MIN(2)) if(StateEqn2_wRegenBraking_v2(E2,U1,L,1,ALPHA_C(2),ALPHA_D(2))>=E_MIN(2)) nextE2=E_MIN(2); %{ elseif(StateEqn2(E2,U1,L,1,1,1)>=E_MIN(2))&&E2<=2 nextE2=E_MIN(2); %} else nextE2=newE2; end else nextE2=newE2; end end
github
AlokD123/Hybrid-Storage_Project-master
GetCtrl1_CurrNextState.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/GetCtrl1_CurrNextState.m
450
utf_8
aabfe9276d9d39f326dacdfc78e0c12f
%Finds the control value D1 leading to next state E1 from current E1, if BOTH known %For NO regenerative braking case (uncombined controls) %Input: E1(t), E1(t+1) function [ D1Opt_State ] = GetCtrl1_CurrNextState( E1,nextE1 ) global ALPHA_D; global BETA; D1=round(-ALPHA_D(1)*(nextE1-BETA(1)*E1)); %Allow for rounding -0.5->0 up to 0 (to REDUCE discretization issues) if D1<0 disp("Error, D1<0\n"); end D1Opt_State=D1; end
github
AlokD123/Hybrid-Storage_Project-master
GetCtrl2_CurrNextState.m
.m
Hybrid-Storage_Project-master/Numerical_Solutions/GetCtrl2_CurrNextState.m
596
utf_8
a2e4a271690f2ca4b4ba92b2d8ebd40e
%Finds the control value D1 leading to next state E2 from current E2, if BOTH known %For NO regenerative braking case (uncombined controls) %Input: E2(t), E2(t+1), D1 (found from D1Opt_State), and L (particular load for which opt control) function [ D2Opt_State ] = GetCtrl2_CurrNextState( E2,nextE2,D1Opt_State,L ) global ALPHA_D;global ALPHA_C; global BETA; D2=round((nextE2-BETA(2)*E2-ALPHA_C(2)*(D1Opt_State-L))/(ALPHA_C(2)-1/ALPHA_D(2))); %Allow for rounding -0.5->0 up to 0 (to REDUCE discretization issues) if D2<0 disp("Error, D2<0\n"); end D2Opt_State=D2; end
github
koobonil/Boss2D-master
readDetection.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_processing/transient/test/readDetection.m
927
utf_8
f6af5020971d028a50a4d19a31b33bcb
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [d, t] = readDetection(file, fs, chunkSize) %[d, t] = readDetection(file, fs, chunkSize) % %Reads a detection signal from a DAT file. % %d: The detection signal. %t: The respective time vector. % %file: The DAT file where the detection signal is stored in float format. %fs: The signal sample rate in Hertz. %chunkSize: The chunk size used for the detection in seconds. fid = fopen(file); d = fread(fid, inf, 'float'); fclose(fid); t = 0:(1 / fs):(length(d) * chunkSize - 1 / fs); d = d(floor(t / chunkSize) + 1);
github
koobonil/Boss2D-master
readPCM.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_processing/transient/test/readPCM.m
821
utf_8
76b2955e65258ada1c1e549a4fc9bf79
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [x, t] = readPCM(file, fs) %[x, t] = readPCM(file, fs) % %Reads a signal from a PCM file. % %x: The read signal after normalization. %t: The respective time vector. % %file: The PCM file where the signal is stored in int16 format. %fs: The signal sample rate in Hertz. fid = fopen(file); x = fread(fid, inf, 'int16'); fclose(fid); x = x - mean(x); x = x / max(abs(x)); t = 0:(1 / fs):((length(x) - 1) / fs);
github
koobonil/Boss2D-master
plotDetection.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_processing/transient/test/plotDetection.m
923
utf_8
e8113bdaf5dcfe4f50200a3ca29c3846
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [] = plotDetection(PCMfile, DATfile, fs, chunkSize) %[] = plotDetection(PCMfile, DATfile, fs, chunkSize) % %Plots the signal alongside the detection values. % %PCMfile: The file of the input signal in PCM format. %DATfile: The file containing the detection values in binary float format. %fs: The sample rate of the signal in Hertz. %chunkSize: The chunk size used to compute the detection values in seconds. [x, tx] = readPCM(PCMfile, fs); [d, td] = readDetection(DATfile, fs, chunkSize); plot(tx, x, td, d);
github
koobonil/Boss2D-master
apmtest.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_processing/test/apmtest.m
9,874
utf_8
17ad6af59f6daa758d983dd419e46ff0
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function apmtest(task, testname, filepath, casenumber, legacy) %APMTEST is a tool to process APM file sets and easily display the output. % APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs: % 'test' Processes the files to produce test output. % 'list' Prints a list of cases in the test set, preceded by their % CASENUMBERs. % 'show' Uses spclab to show the test case specified by the % CASENUMBER parameter. % % using a set of test files determined by TESTNAME: % 'all' All tests. % 'apm' The standard APM test set (default). % 'apmm' The mobile APM test set. % 'aec' The AEC test set. % 'aecm' The AECM test set. % 'agc' The AGC test set. % 'ns' The NS test set. % 'vad' The VAD test set. % % FILEPATH specifies the path to the test data files. % % CASENUMBER can be used to select a single test case. Omit CASENUMBER, % or set to zero, to use all test cases. % if nargin < 5 || isempty(legacy) % Set to true to run old VQE recordings. legacy = false; end if nargin < 4 || isempty(casenumber) casenumber = 0; end if nargin < 3 || isempty(filepath) filepath = 'data/'; end if nargin < 2 || isempty(testname) testname = 'all'; end if nargin < 1 || isempty(task) task = 'test'; end if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show') error(['TASK ' task ' is not recognized']); end if casenumber == 0 && strcmp(task, 'show') error(['CASENUMBER must be specified for TASK ' task]); end inpath = [filepath 'input/']; outpath = [filepath 'output/']; refpath = [filepath 'reference/']; if strcmp(testname, 'all') tests = {'apm','apmm','aec','aecm','agc','ns','vad'}; else tests = {testname}; end if legacy progname = './test'; else progname = './process_test'; end global farFile; global nearFile; global eventFile; global delayFile; global driftFile; if legacy farFile = 'vqeFar.pcm'; nearFile = 'vqeNear.pcm'; eventFile = 'vqeEvent.dat'; delayFile = 'vqeBuf.dat'; driftFile = 'vqeDrift.dat'; else farFile = 'apm_far.pcm'; nearFile = 'apm_near.pcm'; eventFile = 'apm_event.dat'; delayFile = 'apm_delay.dat'; driftFile = 'apm_drift.dat'; end simulateMode = false; nErr = 0; nCases = 0; for i=1:length(tests) simulateMode = false; if strcmp(tests{i}, 'apm') testdir = ['apm/']; outfile = ['out']; if legacy opt = ['-ec 1 -agc 2 -nc 2 -vad 3']; else opt = ['--no_progress -hpf' ... ' -aec --drift_compensation -agc --fixed_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apm-swb') simulateMode = true; testdir = ['apm-swb/']; outfile = ['out']; if legacy opt = ['-fs 32000 -ec 1 -agc 2 -nc 2']; else opt = ['--no_progress -fs 32000 -hpf' ... ' -aec --drift_compensation -agc --adaptive_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apmm') testdir = ['apmm/']; outfile = ['out']; opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ... '--ns_moderate']; else error(['TESTNAME ' tests{i} ' is not recognized']); end inpathtest = [inpath testdir]; outpathtest = [outpath testdir]; refpathtest = [refpath testdir]; if ~exist(inpathtest,'dir') error(['Input directory ' inpathtest ' does not exist']); end if ~exist(refpathtest,'dir') warning(['Reference directory ' refpathtest ' does not exist']); end [status, errMsg] = mkdir(outpathtest); if (status == 0) error(errMsg); end [nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ... progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy); if strcmp(task, 'test') || strcmp(task, 'show') system(['rm ' farFile]); system(['rm ' nearFile]); if simulateMode == false system(['rm ' eventFile]); system(['rm ' delayFile]); system(['rm ' driftFile]); end end end if ~strcmp(task, 'list') if nErr == 0 fprintf(1, '\nAll files are bit-exact to reference\n', nErr); else fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr); end end function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ... outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ... legacy) global farFile; global nearFile; global eventFile; global delayFile; global driftFile; dirs = dir(inpath); nDirs = 0; nErrOut = nErr; for i=3:length(dirs) % skip . and .. nDirs = nDirs + dirs(i).isdir; end if nDirs == 0 nCases = nCases + 1; if casenumber == nCases || casenumber == 0 if strcmp(task, 'list') fprintf([num2str(nCases) '. ' outfile '\n']) else vadoutfile = ['vad_' outfile '.dat']; outfile = [outfile '.pcm']; % Check for VAD test vadTest = 0; if ~isempty(findstr(opt, '-vad')) vadTest = 1; if legacy opt = [opt ' ' outpath vadoutfile]; else opt = [opt ' --vad_out_file ' outpath vadoutfile]; end end if exist([inpath 'vqeFar.pcm']) system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]); elseif exist([inpath 'apm_far.pcm']) system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]); end if exist([inpath 'vqeNear.pcm']) system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]); elseif exist([inpath 'apm_near.pcm']) system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]); end if exist([inpath 'vqeEvent.dat']) system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]); elseif exist([inpath 'apm_event.dat']) system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]); end if exist([inpath 'vqeBuf.dat']) system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]); elseif exist([inpath 'apm_delay.dat']) system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]); end if exist([inpath 'vqeSkew.dat']) system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]); elseif exist([inpath 'vqeDrift.dat']) system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]); elseif exist([inpath 'apm_drift.dat']) system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]); end if simulateMode == false command = [progname ' -o ' outpath outfile ' ' opt]; else if legacy inputCmd = [' -in ' nearFile]; else inputCmd = [' -i ' nearFile]; end if exist([farFile]) if legacy inputCmd = [' -if ' farFile inputCmd]; else inputCmd = [' -ir ' farFile inputCmd]; end end command = [progname inputCmd ' -o ' outpath outfile ' ' opt]; end % This prevents MATLAB from using its own C libraries. shellcmd = ['bash -c "unset LD_LIBRARY_PATH;']; fprintf([command '\n']); [status, result] = system([shellcmd command '"']); fprintf(result); fprintf(['Reference file: ' refpath outfile '\n']); if vadTest == 1 equal_to_ref = are_files_equal([outpath vadoutfile], ... [refpath vadoutfile], ... 'int8'); if ~equal_to_ref nErr = nErr + 1; end end [equal_to_ref, diffvector] = are_files_equal([outpath outfile], ... [refpath outfile], ... 'int16'); if ~equal_to_ref nErr = nErr + 1; end if strcmp(task, 'show') % Assume the last init gives the sample rate of interest. str_idx = strfind(result, 'Sample rate:'); fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17)); fprintf('Using %d Hz\n', fs); if exist([farFile]) spclab(fs, farFile, nearFile, [refpath outfile], ... [outpath outfile], diffvector); %spclab(fs, diffvector); else spclab(fs, nearFile, [refpath outfile], [outpath outfile], ... diffvector); %spclab(fs, diffvector); end end end end else for i=3:length(dirs) if dirs(i).isdir [nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ... refpath,[outfile '_' dirs(i).name], progname, opt, ... simulateMode, nErr, nCases, task, casenumber, legacy); end end end nErrOut = nErr; function [are_equal, diffvector] = ... are_files_equal(newfile, reffile, precision, diffvector) are_equal = false; diffvector = 0; if ~exist(newfile,'file') warning(['Output file ' newfile ' does not exist']); return end if ~exist(reffile,'file') warning(['Reference file ' reffile ' does not exist']); return end fid = fopen(newfile,'rb'); new = fread(fid,inf,precision); fclose(fid); fid = fopen(reffile,'rb'); ref = fread(fid,inf,precision); fclose(fid); if length(new) ~= length(ref) warning('Reference is not the same length as output'); minlength = min(length(new), length(ref)); new = new(1:minlength); ref = ref(1:minlength); end diffvector = new - ref; if isequal(new, ref) fprintf([newfile ' is bit-exact to reference\n']); are_equal = true; else if isempty(new) warning([newfile ' is empty']); return end snr = snrseg(new,ref,80); fprintf('\n'); are_equal = false; end
github
koobonil/Boss2D-master
parse_delay_file.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_coding/neteq/test/delay_tool/parse_delay_file.m
6,405
utf_8
4cc70d6f90e1ca5901104f77a7e7c0b3
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function outStruct = parse_delay_file(file) fid = fopen(file, 'rb'); if fid == -1 error('Cannot open file %s', file); end textline = fgetl(fid); if ~strncmp(textline, '#!NetEQ_Delay_Logging', 21) error('Wrong file format'); end ver = sscanf(textline, '#!NetEQ_Delay_Logging%d.%d'); if ~all(ver == [2; 0]) error('Wrong version of delay logging function') end start_pos = ftell(fid); fseek(fid, -12, 'eof'); textline = fgetl(fid); if ~strncmp(textline, 'End of file', 21) error('File ending is not correct. Seems like the simulation ended abnormally.'); end fseek(fid,-12-4, 'eof'); Npackets = fread(fid, 1, 'int32'); fseek(fid, start_pos, 'bof'); rtpts = zeros(Npackets, 1); seqno = zeros(Npackets, 1); pt = zeros(Npackets, 1); plen = zeros(Npackets, 1); recin_t = nan*ones(Npackets, 1); decode_t = nan*ones(Npackets, 1); playout_delay = zeros(Npackets, 1); optbuf = zeros(Npackets, 1); fs_ix = 1; clock = 0; ts_ix = 1; ended = 0; late_packets = 0; fs_now = 8000; last_decode_k = 0; tot_expand = 0; tot_accelerate = 0; tot_preemptive = 0; while not(ended) signal = fread(fid, 1, '*int32'); switch signal case 3 % NETEQ_DELAY_LOGGING_SIGNAL_CLOCK clock = fread(fid, 1, '*float32'); % keep on reading batches of M until the signal is no longer "3" % read int32 + float32 in one go % this is to save execution time temp = [3; 0]; M = 120; while all(temp(1,:) == 3) fp = ftell(fid); temp = fread(fid, [2 M], '*int32'); end % back up to last clock event fseek(fid, fp - ftell(fid) + ... (find(temp(1,:) ~= 3, 1 ) - 2) * 2 * 4 + 4, 'cof'); % read the last clock value clock = fread(fid, 1, '*float32'); case 1 % NETEQ_DELAY_LOGGING_SIGNAL_RECIN temp_ts = fread(fid, 1, 'uint32'); if late_packets > 0 temp_ix = ts_ix - 1; while (temp_ix >= 1) && (rtpts(temp_ix) ~= temp_ts) % TODO(hlundin): use matlab vector search instead? temp_ix = temp_ix - 1; end if temp_ix >= 1 % the ts was found in the vector late_packets = late_packets - 1; else temp_ix = ts_ix; ts_ix = ts_ix + 1; end else temp_ix = ts_ix; ts_ix = ts_ix + 1; end rtpts(temp_ix) = temp_ts; seqno(temp_ix) = fread(fid, 1, 'uint16'); pt(temp_ix) = fread(fid, 1, 'int32'); plen(temp_ix) = fread(fid, 1, 'int16'); recin_t(temp_ix) = clock; case 2 % NETEQ_DELAY_LOGGING_SIGNAL_FLUSH % do nothing case 4 % NETEQ_DELAY_LOGGING_SIGNAL_EOF ended = 1; case 5 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE last_decode_ts = fread(fid, 1, 'uint32'); temp_delay = fread(fid, 1, 'uint16'); k = find(rtpts(1:(ts_ix - 1))==last_decode_ts,1,'last'); if ~isempty(k) decode_t(k) = clock; playout_delay(k) = temp_delay + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end case 6 % NETEQ_DELAY_LOGGING_SIGNAL_CHANGE_FS fsvec(fs_ix) = fread(fid, 1, 'uint16'); fschange_ts(fs_ix) = last_decode_ts; fs_now = fsvec(fs_ix); fs_ix = fs_ix + 1; case 7 % NETEQ_DELAY_LOGGING_SIGNAL_MERGE_INFO playout_delay(last_decode_k) = playout_delay(last_decode_k) ... + fread(fid, 1, 'int32'); case 8 % NETEQ_DELAY_LOGGING_SIGNAL_EXPAND_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_expand = tot_expand + temp / (fs_now / 1000); end case 9 % NETEQ_DELAY_LOGGING_SIGNAL_ACCELERATE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_accelerate = tot_accelerate + temp / (fs_now / 1000); end case 10 % NETEQ_DELAY_LOGGING_SIGNAL_PREEMPTIVE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_preemptive = tot_preemptive + temp / (fs_now / 1000); end case 11 % NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF optbuf(last_decode_k) = fread(fid, 1, 'int32'); case 12 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE_ONE_DESC last_decode_ts = fread(fid, 1, 'uint32'); k = ts_ix - 1; while (k >= 1) && (rtpts(k) ~= last_decode_ts) % TODO(hlundin): use matlab vector search instead? k = k - 1; end if k < 1 % packet not received yet k = ts_ix; rtpts(ts_ix) = last_decode_ts; late_packets = late_packets + 1; end decode_t(k) = clock; playout_delay(k) = fread(fid, 1, 'uint16') + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end end fclose(fid); outStruct = struct(... 'ts', rtpts, ... 'sn', seqno, ... 'pt', pt,... 'plen', plen,... 'arrival', recin_t,... 'decode', decode_t,... 'fs', fsvec(:),... 'fschange_ts', fschange_ts(:),... 'playout_delay', playout_delay,... 'tot_expand', tot_expand,... 'tot_accelerate', tot_accelerate,... 'tot_preemptive', tot_preemptive,... 'optbuf', optbuf);
github
koobonil/Boss2D-master
plot_neteq_delay.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m
5,967
utf_8
cce342fed6406ef0f12d567fe3ab6eef
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin) % InfoStruct = plot_neteq_delay(delayfile) % InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds) % % Henrik Lundin, 2006-11-17 % Henrik Lundin, 2011-05-17 % try s = parse_delay_file(delayfile); catch error(lasterr); end delayskip=0; noplot=0; arg_ptr=1; delaypoints=[]; s.sn=unwrap_seqno(s.sn); while arg_ptr+1 <= nargin switch lower(varargin{arg_ptr}) case {'skipdelay', 'delayskip'} % skip a number of seconds in the beginning when calculating delays delayskip = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; case 'noplot' noplot=1; arg_ptr = arg_ptr + 1; case {'get_delay', 'getdelay'} % return a vector of delay values for the points in the given vector delaypoints = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; otherwise warning('Unknown switch %s\n', varargin{arg_ptr}); arg_ptr = arg_ptr + 1; end end % find lost frames that were covered by one-descriptor decoding one_desc_ix=find(isnan(s.arrival)); for k=1:length(one_desc_ix) ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts))); s.sn(one_desc_ix(k))=s.sn(ix)+1; s.pt(one_desc_ix(k))=s.pt(ix); s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix); end % remove duplicate received frames that were never decoded (RED codec) if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts))) ix=find(isfinite(s.decode)); s.sn=s.sn(ix); s.ts=s.ts(ix); s.arrival=s.arrival(ix); s.playout_delay=s.playout_delay(ix); s.pt=s.pt(ix); s.optbuf=s.optbuf(ix); plen=plen(ix); s.decode=s.decode(ix); end % find non-unique sequence numbers [~,un_ix]=unique(s.sn); nonun_ix=setdiff(1:length(s.sn),un_ix); if ~isempty(nonun_ix) warning('RTP sequence numbers are in error'); end % sort vectors [s.sn,sort_ix]=sort(s.sn); s.ts=s.ts(sort_ix); s.arrival=s.arrival(sort_ix); s.decode=s.decode(sort_ix); s.playout_delay=s.playout_delay(sort_ix); s.pt=s.pt(sort_ix); send_t=s.ts-s.ts(1); if length(s.fs)<1 warning('No info about sample rate found in file. Using default 8000.'); s.fs(1)=8000; s.fschange_ts(1)=min(s.ts); elseif s.fschange_ts(1)>min(s.ts) s.fschange_ts(1)=min(s.ts); end end_ix=length(send_t); for k=length(s.fs):-1:1 start_ix=find(s.ts==s.fschange_ts(k)); send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000; s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000; s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000; end_ix=start_ix-1; end tot_time=max(send_t)-min(send_t); seq_ix=s.sn-min(s.sn)+1; send_t=send_t+max(min(s.arrival-send_t),0); plot_send_t=nan*ones(max(seq_ix),1); plot_send_t(seq_ix)=send_t; plot_nw_delay=nan*ones(max(seq_ix),1); plot_nw_delay(seq_ix)=s.arrival-send_t; cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID if noplot==0 h=plot(plot_send_t/1000,plot_nw_delay); set(h,'color',0.75*[1 1 1]); hold on if any(s.optbuf~=0) peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix); h1=plot(send_t(cng_ix(peak_ix))/1000,... s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),... 'r.'); h2=plot(send_t(cng_ix(no_peak_ix))/1000,... s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),... 'g.'); set([h1, h2],'markersize',1) end %h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix)); h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix)); set(h,'linew',1.5); hold off ax1=axis; axis tight ax2=axis; axis([ax2(1:3) ax1(4)]) end % calculate delays and other parameters delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 ); use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames... intersect(find(isfinite(s.decode)),... % ... that did arrive ... (delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix)); neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix)); Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1; nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack; neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack; delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,... 'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,... 'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),... 'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,... 'filename',delayfile,'units','ms','fs',unique(s.fs)); if not(isempty(delaypoints)) delayvalues=interp1(send_t(cng_ix),... s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),... delaypoints,'nearest',NaN); else delayvalues=[]; end % SUBFUNCTIONS % function y=unwrap_seqno(x) jumps=find(abs((diff(x)-1))>65000); while ~isempty(jumps) n=jumps(1); if x(n+1)-x(n) < 0 % negative jump x(n+1:end)=x(n+1:end)+65536; else % positive jump x(n+1:end)=x(n+1:end)-65536; end jumps=find(abs((diff(x(n+1:end))-1))>65000); end y=x; return;
github
koobonil/Boss2D-master
rtpAnalyze.m
.m
Boss2D-master/Boss2D/addon/webrtc-jumpingyang001_for_boss/tools_webrtc/matlab/rtpAnalyze.m
7,892
utf_8
46e63db0fa96270c14a0c205bbab42e4
function rtpAnalyze( input_file ) %RTP_ANALYZE Analyze RTP stream(s) from a txt file % The function takes the output from the command line tool rtp_analyze % and analyzes the stream(s) therein. First, process your rtpdump file % through rtp_analyze (from command line): % $ out/Debug/rtp_analyze my_file.rtp my_file.txt % Then load it with this function (in Matlab): % >> rtpAnalyze('my_file.txt') % Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. [SeqNo,TimeStamp,ArrTime,Size,PT,M,SSRC] = importfile(input_file); %% Filter out RTCP packets. % These appear as RTP packets having payload types 72 through 76. ix = not(ismember(PT, 72:76)); fprintf('Removing %i RTCP packets\n', length(SeqNo) - sum(ix)); SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); %% Find streams. [uSSRC, ~, uix] = unique(SSRC); % If there are multiple streams, select one and purge the other % streams from the data vectors. If there is only one stream, the % vectors are good to use as they are. if length(uSSRC) > 1 for i=1:length(uSSRC) uPT = unique(PT(uix == i)); fprintf('%i: %s (%d packets, pt: %i', i, uSSRC{i}, ... length(find(uix==i)), uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf(')\n'); end sel = input('Select stream number: '); if sel < 1 || sel > length(uSSRC) error('Out of range'); end ix = find(uix == sel); % This is where the data vectors are trimmed. SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); end %% Unwrap SeqNo and TimeStamp. SeqNoUW = maxUnwrap(SeqNo, 65535); TimeStampUW = maxUnwrap(TimeStamp, 4294967295); %% Generate some stats for the stream. fprintf('Statistics:\n'); fprintf('SSRC: %s\n', SSRC{1}); uPT = unique(PT); if length(uPT) > 1 warning('This tool cannot yet handle changes in codec sample rate'); end fprintf('Payload type(s): %i', uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf('\n'); fprintf('Packets: %i\n', length(SeqNo)); SortSeqNo = sort(SeqNoUW); fprintf('Missing sequence numbers: %i\n', ... length(find(diff(SortSeqNo) > 1))); fprintf('Duplicated packets: %i\n', length(find(diff(SortSeqNo) == 0))); reorderIx = findReorderedPackets(SeqNoUW); fprintf('Reordered packets: %i\n', length(reorderIx)); tsdiff = diff(TimeStampUW); tsdiff = tsdiff(diff(SeqNoUW) == 1); [utsdiff, ~, ixtsdiff] = unique(tsdiff); fprintf('Common packet sizes:\n'); for i = 1:length(utsdiff) fprintf(' %i samples (%i%%)\n', ... utsdiff(i), ... round(100 * length(find(ixtsdiff == i))/length(ixtsdiff))); end %% Trying to figure out sample rate. fs_est = (TimeStampUW(end) - TimeStampUW(1)) / (ArrTime(end) - ArrTime(1)); fs_vec = [8, 16, 32, 48]; fs = 0; for f = fs_vec if abs((fs_est-f)/f) < 0.05 % 5% margin fs = f; break; end end if fs == 0 fprintf('Cannot determine sample rate. I get it to %.2f kHz\n', ... fs_est); fs = input('Please, input a sample rate (in kHz): '); else fprintf('Sample rate estimated to %i kHz\n', fs); end SendTimeMs = (TimeStampUW - TimeStampUW(1)) / fs; fprintf('Stream duration at sender: %.1f seconds\n', ... (SendTimeMs(end) - SendTimeMs(1)) / 1000); fprintf('Stream duration at receiver: %.1f seconds\n', ... (ArrTime(end) - ArrTime(1)) / 1000); fprintf('Clock drift: %.2f%%\n', ... 100 * ((ArrTime(end) - ArrTime(1)) / ... (SendTimeMs(end) - SendTimeMs(1)) - 1)); fprintf('Sent average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (SendTimeMs(end)-SendTimeMs(1)))); fprintf('Received average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (ArrTime(end)-ArrTime(1)))); %% Plots. delay = ArrTime - SendTimeMs; delay = delay - min(delay); delayOrdered = delay; delayOrdered(reorderIx) = nan; % Set reordered packets to NaN. delayReordered = delay(reorderIx); % Pick the reordered packets. sendTimeMsReordered = SendTimeMs(reorderIx); % Sort time arrays in packet send order. [~, sortix] = sort(SeqNoUW); SendTimeMs = SendTimeMs(sortix); Size = Size(sortix); delayOrdered = delayOrdered(sortix); figure plot(SendTimeMs / 1000, delayOrdered, ... sendTimeMsReordered / 1000, delayReordered, 'r.'); xlabel('Send time [s]'); ylabel('Relative transport delay [ms]'); title(sprintf('SSRC: %s', SSRC{1})); SendBitrateKbps = 8 * Size(1:end-1) ./ diff(SendTimeMs); figure plot(SendTimeMs(1:end-1)/1000, SendBitrateKbps); xlabel('Send time [s]'); ylabel('Send bitrate [kbps]'); end %% Subfunctions. % findReorderedPackets returns the index to all packets that are considered % old compared with the largest seen sequence number. The input seqNo must % be unwrapped for this to work. function reorderIx = findReorderedPackets(seqNo) largestSeqNo = seqNo(1); reorderIx = []; for i = 2:length(seqNo) if seqNo(i) < largestSeqNo reorderIx = [reorderIx; i]; %#ok<AGROW> else largestSeqNo = seqNo(i); end end end %% Auto-generated subfunction. function [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = ... importfile(filename, startRow, endRow) %IMPORTFILE Import numeric data from a text file as column vectors. % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME) Reads % data from text file FILENAME for the default selection. % % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME, % STARTROW, ENDROW) Reads data from rows STARTROW through ENDROW of text % file FILENAME. % % Example: % [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = % importfile('rtpdump_recv.txt',2, 123); % % See also TEXTSCAN. % Auto-generated by MATLAB on 2015/05/28 09:55:50 %% Initialize variables. if nargin<=2 startRow = 2; endRow = inf; end %% Format string for each line of text: % column1: double (%f) % column2: double (%f) % column3: double (%f) % column4: double (%f) % column5: double (%f) % column6: double (%f) % column7: text (%s) % For more information, see the TEXTSCAN documentation. formatSpec = '%5f%11f%11f%6f%6f%3f%s%[^\n\r]'; %% Open the text file. fileID = fopen(filename,'r'); %% Read columns of data according to format string. % This call is based on the structure of the file used to generate this % code. If an error occurs for a different file, try regenerating the code % from the Import Tool. dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ... 'Delimiter', '', 'WhiteSpace', '', 'HeaderLines', startRow(1)-1, ... 'ReturnOnError', false); for block=2:length(startRow) frewind(fileID); dataArrayBlock = textscan(fileID, formatSpec, ... endRow(block)-startRow(block)+1, 'Delimiter', '', 'WhiteSpace', ... '', 'HeaderLines', startRow(block)-1, 'ReturnOnError', false); for col=1:length(dataArray) dataArray{col} = [dataArray{col};dataArrayBlock{col}]; end end %% Close the text file. fclose(fileID); %% Post processing for unimportable data. % No unimportable data rules were applied during the import, so no post % processing code is included. To generate code which works for % unimportable data, select unimportable cells in a file and regenerate the % script. %% Allocate imported array to column variable names SeqNo = dataArray{:, 1}; TimeStamp = dataArray{:, 2}; SendTime = dataArray{:, 3}; Size = dataArray{:, 4}; PT = dataArray{:, 5}; M = dataArray{:, 6}; SSRC = dataArray{:, 7}; end
github
koobonil/Boss2D-master
readDetection.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/test/readDetection.m
927
utf_8
f6af5020971d028a50a4d19a31b33bcb
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [d, t] = readDetection(file, fs, chunkSize) %[d, t] = readDetection(file, fs, chunkSize) % %Reads a detection signal from a DAT file. % %d: The detection signal. %t: The respective time vector. % %file: The DAT file where the detection signal is stored in float format. %fs: The signal sample rate in Hertz. %chunkSize: The chunk size used for the detection in seconds. fid = fopen(file); d = fread(fid, inf, 'float'); fclose(fid); t = 0:(1 / fs):(length(d) * chunkSize - 1 / fs); d = d(floor(t / chunkSize) + 1);
github
koobonil/Boss2D-master
readPCM.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/test/readPCM.m
821
utf_8
76b2955e65258ada1c1e549a4fc9bf79
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [x, t] = readPCM(file, fs) %[x, t] = readPCM(file, fs) % %Reads a signal from a PCM file. % %x: The read signal after normalization. %t: The respective time vector. % %file: The PCM file where the signal is stored in int16 format. %fs: The signal sample rate in Hertz. fid = fopen(file); x = fread(fid, inf, 'int16'); fclose(fid); x = x - mean(x); x = x / max(abs(x)); t = 0:(1 / fs):((length(x) - 1) / fs);
github
koobonil/Boss2D-master
plotDetection.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/test/plotDetection.m
923
utf_8
e8113bdaf5dcfe4f50200a3ca29c3846
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [] = plotDetection(PCMfile, DATfile, fs, chunkSize) %[] = plotDetection(PCMfile, DATfile, fs, chunkSize) % %Plots the signal alongside the detection values. % %PCMfile: The file of the input signal in PCM format. %DATfile: The file containing the detection values in binary float format. %fs: The sample rate of the signal in Hertz. %chunkSize: The chunk size used to compute the detection values in seconds. [x, tx] = readPCM(PCMfile, fs); [d, td] = readDetection(DATfile, fs, chunkSize); plot(tx, x, td, d);
github
koobonil/Boss2D-master
apmtest.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/test/apmtest.m
9,874
utf_8
17ad6af59f6daa758d983dd419e46ff0
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function apmtest(task, testname, filepath, casenumber, legacy) %APMTEST is a tool to process APM file sets and easily display the output. % APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs: % 'test' Processes the files to produce test output. % 'list' Prints a list of cases in the test set, preceded by their % CASENUMBERs. % 'show' Uses spclab to show the test case specified by the % CASENUMBER parameter. % % using a set of test files determined by TESTNAME: % 'all' All tests. % 'apm' The standard APM test set (default). % 'apmm' The mobile APM test set. % 'aec' The AEC test set. % 'aecm' The AECM test set. % 'agc' The AGC test set. % 'ns' The NS test set. % 'vad' The VAD test set. % % FILEPATH specifies the path to the test data files. % % CASENUMBER can be used to select a single test case. Omit CASENUMBER, % or set to zero, to use all test cases. % if nargin < 5 || isempty(legacy) % Set to true to run old VQE recordings. legacy = false; end if nargin < 4 || isempty(casenumber) casenumber = 0; end if nargin < 3 || isempty(filepath) filepath = 'data/'; end if nargin < 2 || isempty(testname) testname = 'all'; end if nargin < 1 || isempty(task) task = 'test'; end if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show') error(['TASK ' task ' is not recognized']); end if casenumber == 0 && strcmp(task, 'show') error(['CASENUMBER must be specified for TASK ' task]); end inpath = [filepath 'input/']; outpath = [filepath 'output/']; refpath = [filepath 'reference/']; if strcmp(testname, 'all') tests = {'apm','apmm','aec','aecm','agc','ns','vad'}; else tests = {testname}; end if legacy progname = './test'; else progname = './process_test'; end global farFile; global nearFile; global eventFile; global delayFile; global driftFile; if legacy farFile = 'vqeFar.pcm'; nearFile = 'vqeNear.pcm'; eventFile = 'vqeEvent.dat'; delayFile = 'vqeBuf.dat'; driftFile = 'vqeDrift.dat'; else farFile = 'apm_far.pcm'; nearFile = 'apm_near.pcm'; eventFile = 'apm_event.dat'; delayFile = 'apm_delay.dat'; driftFile = 'apm_drift.dat'; end simulateMode = false; nErr = 0; nCases = 0; for i=1:length(tests) simulateMode = false; if strcmp(tests{i}, 'apm') testdir = ['apm/']; outfile = ['out']; if legacy opt = ['-ec 1 -agc 2 -nc 2 -vad 3']; else opt = ['--no_progress -hpf' ... ' -aec --drift_compensation -agc --fixed_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apm-swb') simulateMode = true; testdir = ['apm-swb/']; outfile = ['out']; if legacy opt = ['-fs 32000 -ec 1 -agc 2 -nc 2']; else opt = ['--no_progress -fs 32000 -hpf' ... ' -aec --drift_compensation -agc --adaptive_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apmm') testdir = ['apmm/']; outfile = ['out']; opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ... '--ns_moderate']; else error(['TESTNAME ' tests{i} ' is not recognized']); end inpathtest = [inpath testdir]; outpathtest = [outpath testdir]; refpathtest = [refpath testdir]; if ~exist(inpathtest,'dir') error(['Input directory ' inpathtest ' does not exist']); end if ~exist(refpathtest,'dir') warning(['Reference directory ' refpathtest ' does not exist']); end [status, errMsg] = mkdir(outpathtest); if (status == 0) error(errMsg); end [nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ... progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy); if strcmp(task, 'test') || strcmp(task, 'show') system(['rm ' farFile]); system(['rm ' nearFile]); if simulateMode == false system(['rm ' eventFile]); system(['rm ' delayFile]); system(['rm ' driftFile]); end end end if ~strcmp(task, 'list') if nErr == 0 fprintf(1, '\nAll files are bit-exact to reference\n', nErr); else fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr); end end function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ... outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ... legacy) global farFile; global nearFile; global eventFile; global delayFile; global driftFile; dirs = dir(inpath); nDirs = 0; nErrOut = nErr; for i=3:length(dirs) % skip . and .. nDirs = nDirs + dirs(i).isdir; end if nDirs == 0 nCases = nCases + 1; if casenumber == nCases || casenumber == 0 if strcmp(task, 'list') fprintf([num2str(nCases) '. ' outfile '\n']) else vadoutfile = ['vad_' outfile '.dat']; outfile = [outfile '.pcm']; % Check for VAD test vadTest = 0; if ~isempty(findstr(opt, '-vad')) vadTest = 1; if legacy opt = [opt ' ' outpath vadoutfile]; else opt = [opt ' --vad_out_file ' outpath vadoutfile]; end end if exist([inpath 'vqeFar.pcm']) system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]); elseif exist([inpath 'apm_far.pcm']) system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]); end if exist([inpath 'vqeNear.pcm']) system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]); elseif exist([inpath 'apm_near.pcm']) system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]); end if exist([inpath 'vqeEvent.dat']) system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]); elseif exist([inpath 'apm_event.dat']) system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]); end if exist([inpath 'vqeBuf.dat']) system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]); elseif exist([inpath 'apm_delay.dat']) system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]); end if exist([inpath 'vqeSkew.dat']) system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]); elseif exist([inpath 'vqeDrift.dat']) system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]); elseif exist([inpath 'apm_drift.dat']) system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]); end if simulateMode == false command = [progname ' -o ' outpath outfile ' ' opt]; else if legacy inputCmd = [' -in ' nearFile]; else inputCmd = [' -i ' nearFile]; end if exist([farFile]) if legacy inputCmd = [' -if ' farFile inputCmd]; else inputCmd = [' -ir ' farFile inputCmd]; end end command = [progname inputCmd ' -o ' outpath outfile ' ' opt]; end % This prevents MATLAB from using its own C libraries. shellcmd = ['bash -c "unset LD_LIBRARY_PATH;']; fprintf([command '\n']); [status, result] = system([shellcmd command '"']); fprintf(result); fprintf(['Reference file: ' refpath outfile '\n']); if vadTest == 1 equal_to_ref = are_files_equal([outpath vadoutfile], ... [refpath vadoutfile], ... 'int8'); if ~equal_to_ref nErr = nErr + 1; end end [equal_to_ref, diffvector] = are_files_equal([outpath outfile], ... [refpath outfile], ... 'int16'); if ~equal_to_ref nErr = nErr + 1; end if strcmp(task, 'show') % Assume the last init gives the sample rate of interest. str_idx = strfind(result, 'Sample rate:'); fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17)); fprintf('Using %d Hz\n', fs); if exist([farFile]) spclab(fs, farFile, nearFile, [refpath outfile], ... [outpath outfile], diffvector); %spclab(fs, diffvector); else spclab(fs, nearFile, [refpath outfile], [outpath outfile], ... diffvector); %spclab(fs, diffvector); end end end end else for i=3:length(dirs) if dirs(i).isdir [nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ... refpath,[outfile '_' dirs(i).name], progname, opt, ... simulateMode, nErr, nCases, task, casenumber, legacy); end end end nErrOut = nErr; function [are_equal, diffvector] = ... are_files_equal(newfile, reffile, precision, diffvector) are_equal = false; diffvector = 0; if ~exist(newfile,'file') warning(['Output file ' newfile ' does not exist']); return end if ~exist(reffile,'file') warning(['Reference file ' reffile ' does not exist']); return end fid = fopen(newfile,'rb'); new = fread(fid,inf,precision); fclose(fid); fid = fopen(reffile,'rb'); ref = fread(fid,inf,precision); fclose(fid); if length(new) ~= length(ref) warning('Reference is not the same length as output'); minlength = min(length(new), length(ref)); new = new(1:minlength); ref = ref(1:minlength); end diffvector = new - ref; if isequal(new, ref) fprintf([newfile ' is bit-exact to reference\n']); are_equal = true; else if isempty(new) warning([newfile ' is empty']); return end snr = snrseg(new,ref,80); fprintf('\n'); are_equal = false; end
github
koobonil/Boss2D-master
parse_delay_file.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_coding/neteq/test/delay_tool/parse_delay_file.m
6,405
utf_8
4cc70d6f90e1ca5901104f77a7e7c0b3
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function outStruct = parse_delay_file(file) fid = fopen(file, 'rb'); if fid == -1 error('Cannot open file %s', file); end textline = fgetl(fid); if ~strncmp(textline, '#!NetEQ_Delay_Logging', 21) error('Wrong file format'); end ver = sscanf(textline, '#!NetEQ_Delay_Logging%d.%d'); if ~all(ver == [2; 0]) error('Wrong version of delay logging function') end start_pos = ftell(fid); fseek(fid, -12, 'eof'); textline = fgetl(fid); if ~strncmp(textline, 'End of file', 21) error('File ending is not correct. Seems like the simulation ended abnormally.'); end fseek(fid,-12-4, 'eof'); Npackets = fread(fid, 1, 'int32'); fseek(fid, start_pos, 'bof'); rtpts = zeros(Npackets, 1); seqno = zeros(Npackets, 1); pt = zeros(Npackets, 1); plen = zeros(Npackets, 1); recin_t = nan*ones(Npackets, 1); decode_t = nan*ones(Npackets, 1); playout_delay = zeros(Npackets, 1); optbuf = zeros(Npackets, 1); fs_ix = 1; clock = 0; ts_ix = 1; ended = 0; late_packets = 0; fs_now = 8000; last_decode_k = 0; tot_expand = 0; tot_accelerate = 0; tot_preemptive = 0; while not(ended) signal = fread(fid, 1, '*int32'); switch signal case 3 % NETEQ_DELAY_LOGGING_SIGNAL_CLOCK clock = fread(fid, 1, '*float32'); % keep on reading batches of M until the signal is no longer "3" % read int32 + float32 in one go % this is to save execution time temp = [3; 0]; M = 120; while all(temp(1,:) == 3) fp = ftell(fid); temp = fread(fid, [2 M], '*int32'); end % back up to last clock event fseek(fid, fp - ftell(fid) + ... (find(temp(1,:) ~= 3, 1 ) - 2) * 2 * 4 + 4, 'cof'); % read the last clock value clock = fread(fid, 1, '*float32'); case 1 % NETEQ_DELAY_LOGGING_SIGNAL_RECIN temp_ts = fread(fid, 1, 'uint32'); if late_packets > 0 temp_ix = ts_ix - 1; while (temp_ix >= 1) && (rtpts(temp_ix) ~= temp_ts) % TODO(hlundin): use matlab vector search instead? temp_ix = temp_ix - 1; end if temp_ix >= 1 % the ts was found in the vector late_packets = late_packets - 1; else temp_ix = ts_ix; ts_ix = ts_ix + 1; end else temp_ix = ts_ix; ts_ix = ts_ix + 1; end rtpts(temp_ix) = temp_ts; seqno(temp_ix) = fread(fid, 1, 'uint16'); pt(temp_ix) = fread(fid, 1, 'int32'); plen(temp_ix) = fread(fid, 1, 'int16'); recin_t(temp_ix) = clock; case 2 % NETEQ_DELAY_LOGGING_SIGNAL_FLUSH % do nothing case 4 % NETEQ_DELAY_LOGGING_SIGNAL_EOF ended = 1; case 5 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE last_decode_ts = fread(fid, 1, 'uint32'); temp_delay = fread(fid, 1, 'uint16'); k = find(rtpts(1:(ts_ix - 1))==last_decode_ts,1,'last'); if ~isempty(k) decode_t(k) = clock; playout_delay(k) = temp_delay + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end case 6 % NETEQ_DELAY_LOGGING_SIGNAL_CHANGE_FS fsvec(fs_ix) = fread(fid, 1, 'uint16'); fschange_ts(fs_ix) = last_decode_ts; fs_now = fsvec(fs_ix); fs_ix = fs_ix + 1; case 7 % NETEQ_DELAY_LOGGING_SIGNAL_MERGE_INFO playout_delay(last_decode_k) = playout_delay(last_decode_k) ... + fread(fid, 1, 'int32'); case 8 % NETEQ_DELAY_LOGGING_SIGNAL_EXPAND_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_expand = tot_expand + temp / (fs_now / 1000); end case 9 % NETEQ_DELAY_LOGGING_SIGNAL_ACCELERATE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_accelerate = tot_accelerate + temp / (fs_now / 1000); end case 10 % NETEQ_DELAY_LOGGING_SIGNAL_PREEMPTIVE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_preemptive = tot_preemptive + temp / (fs_now / 1000); end case 11 % NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF optbuf(last_decode_k) = fread(fid, 1, 'int32'); case 12 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE_ONE_DESC last_decode_ts = fread(fid, 1, 'uint32'); k = ts_ix - 1; while (k >= 1) && (rtpts(k) ~= last_decode_ts) % TODO(hlundin): use matlab vector search instead? k = k - 1; end if k < 1 % packet not received yet k = ts_ix; rtpts(ts_ix) = last_decode_ts; late_packets = late_packets + 1; end decode_t(k) = clock; playout_delay(k) = fread(fid, 1, 'uint16') + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end end fclose(fid); outStruct = struct(... 'ts', rtpts, ... 'sn', seqno, ... 'pt', pt,... 'plen', plen,... 'arrival', recin_t,... 'decode', decode_t,... 'fs', fsvec(:),... 'fschange_ts', fschange_ts(:),... 'playout_delay', playout_delay,... 'tot_expand', tot_expand,... 'tot_accelerate', tot_accelerate,... 'tot_preemptive', tot_preemptive,... 'optbuf', optbuf);
github
koobonil/Boss2D-master
plot_neteq_delay.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m
5,967
utf_8
cce342fed6406ef0f12d567fe3ab6eef
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin) % InfoStruct = plot_neteq_delay(delayfile) % InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds) % % Henrik Lundin, 2006-11-17 % Henrik Lundin, 2011-05-17 % try s = parse_delay_file(delayfile); catch error(lasterr); end delayskip=0; noplot=0; arg_ptr=1; delaypoints=[]; s.sn=unwrap_seqno(s.sn); while arg_ptr+1 <= nargin switch lower(varargin{arg_ptr}) case {'skipdelay', 'delayskip'} % skip a number of seconds in the beginning when calculating delays delayskip = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; case 'noplot' noplot=1; arg_ptr = arg_ptr + 1; case {'get_delay', 'getdelay'} % return a vector of delay values for the points in the given vector delaypoints = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; otherwise warning('Unknown switch %s\n', varargin{arg_ptr}); arg_ptr = arg_ptr + 1; end end % find lost frames that were covered by one-descriptor decoding one_desc_ix=find(isnan(s.arrival)); for k=1:length(one_desc_ix) ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts))); s.sn(one_desc_ix(k))=s.sn(ix)+1; s.pt(one_desc_ix(k))=s.pt(ix); s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix); end % remove duplicate received frames that were never decoded (RED codec) if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts))) ix=find(isfinite(s.decode)); s.sn=s.sn(ix); s.ts=s.ts(ix); s.arrival=s.arrival(ix); s.playout_delay=s.playout_delay(ix); s.pt=s.pt(ix); s.optbuf=s.optbuf(ix); plen=plen(ix); s.decode=s.decode(ix); end % find non-unique sequence numbers [~,un_ix]=unique(s.sn); nonun_ix=setdiff(1:length(s.sn),un_ix); if ~isempty(nonun_ix) warning('RTP sequence numbers are in error'); end % sort vectors [s.sn,sort_ix]=sort(s.sn); s.ts=s.ts(sort_ix); s.arrival=s.arrival(sort_ix); s.decode=s.decode(sort_ix); s.playout_delay=s.playout_delay(sort_ix); s.pt=s.pt(sort_ix); send_t=s.ts-s.ts(1); if length(s.fs)<1 warning('No info about sample rate found in file. Using default 8000.'); s.fs(1)=8000; s.fschange_ts(1)=min(s.ts); elseif s.fschange_ts(1)>min(s.ts) s.fschange_ts(1)=min(s.ts); end end_ix=length(send_t); for k=length(s.fs):-1:1 start_ix=find(s.ts==s.fschange_ts(k)); send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000; s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000; s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000; end_ix=start_ix-1; end tot_time=max(send_t)-min(send_t); seq_ix=s.sn-min(s.sn)+1; send_t=send_t+max(min(s.arrival-send_t),0); plot_send_t=nan*ones(max(seq_ix),1); plot_send_t(seq_ix)=send_t; plot_nw_delay=nan*ones(max(seq_ix),1); plot_nw_delay(seq_ix)=s.arrival-send_t; cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID if noplot==0 h=plot(plot_send_t/1000,plot_nw_delay); set(h,'color',0.75*[1 1 1]); hold on if any(s.optbuf~=0) peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix); h1=plot(send_t(cng_ix(peak_ix))/1000,... s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),... 'r.'); h2=plot(send_t(cng_ix(no_peak_ix))/1000,... s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),... 'g.'); set([h1, h2],'markersize',1) end %h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix)); h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix)); set(h,'linew',1.5); hold off ax1=axis; axis tight ax2=axis; axis([ax2(1:3) ax1(4)]) end % calculate delays and other parameters delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 ); use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames... intersect(find(isfinite(s.decode)),... % ... that did arrive ... (delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix)); neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix)); Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1; nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack; neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack; delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,... 'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,... 'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),... 'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,... 'filename',delayfile,'units','ms','fs',unique(s.fs)); if not(isempty(delaypoints)) delayvalues=interp1(send_t(cng_ix),... s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),... delaypoints,'nearest',NaN); else delayvalues=[]; end % SUBFUNCTIONS % function y=unwrap_seqno(x) jumps=find(abs((diff(x)-1))>65000); while ~isempty(jumps) n=jumps(1); if x(n+1)-x(n) < 0 % negative jump x(n+1:end)=x(n+1:end)+65536; else % positive jump x(n+1:end)=x(n+1:end)-65536; end jumps=find(abs((diff(x(n+1:end))-1))>65000); end y=x; return;
github
koobonil/Boss2D-master
rtpAnalyze.m
.m
Boss2D-master/Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/tools_webrtc/matlab/rtpAnalyze.m
7,892
utf_8
46e63db0fa96270c14a0c205bbab42e4
function rtpAnalyze( input_file ) %RTP_ANALYZE Analyze RTP stream(s) from a txt file % The function takes the output from the command line tool rtp_analyze % and analyzes the stream(s) therein. First, process your rtpdump file % through rtp_analyze (from command line): % $ out/Debug/rtp_analyze my_file.rtp my_file.txt % Then load it with this function (in Matlab): % >> rtpAnalyze('my_file.txt') % Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. [SeqNo,TimeStamp,ArrTime,Size,PT,M,SSRC] = importfile(input_file); %% Filter out RTCP packets. % These appear as RTP packets having payload types 72 through 76. ix = not(ismember(PT, 72:76)); fprintf('Removing %i RTCP packets\n', length(SeqNo) - sum(ix)); SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); %% Find streams. [uSSRC, ~, uix] = unique(SSRC); % If there are multiple streams, select one and purge the other % streams from the data vectors. If there is only one stream, the % vectors are good to use as they are. if length(uSSRC) > 1 for i=1:length(uSSRC) uPT = unique(PT(uix == i)); fprintf('%i: %s (%d packets, pt: %i', i, uSSRC{i}, ... length(find(uix==i)), uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf(')\n'); end sel = input('Select stream number: '); if sel < 1 || sel > length(uSSRC) error('Out of range'); end ix = find(uix == sel); % This is where the data vectors are trimmed. SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); end %% Unwrap SeqNo and TimeStamp. SeqNoUW = maxUnwrap(SeqNo, 65535); TimeStampUW = maxUnwrap(TimeStamp, 4294967295); %% Generate some stats for the stream. fprintf('Statistics:\n'); fprintf('SSRC: %s\n', SSRC{1}); uPT = unique(PT); if length(uPT) > 1 warning('This tool cannot yet handle changes in codec sample rate'); end fprintf('Payload type(s): %i', uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf('\n'); fprintf('Packets: %i\n', length(SeqNo)); SortSeqNo = sort(SeqNoUW); fprintf('Missing sequence numbers: %i\n', ... length(find(diff(SortSeqNo) > 1))); fprintf('Duplicated packets: %i\n', length(find(diff(SortSeqNo) == 0))); reorderIx = findReorderedPackets(SeqNoUW); fprintf('Reordered packets: %i\n', length(reorderIx)); tsdiff = diff(TimeStampUW); tsdiff = tsdiff(diff(SeqNoUW) == 1); [utsdiff, ~, ixtsdiff] = unique(tsdiff); fprintf('Common packet sizes:\n'); for i = 1:length(utsdiff) fprintf(' %i samples (%i%%)\n', ... utsdiff(i), ... round(100 * length(find(ixtsdiff == i))/length(ixtsdiff))); end %% Trying to figure out sample rate. fs_est = (TimeStampUW(end) - TimeStampUW(1)) / (ArrTime(end) - ArrTime(1)); fs_vec = [8, 16, 32, 48]; fs = 0; for f = fs_vec if abs((fs_est-f)/f) < 0.05 % 5% margin fs = f; break; end end if fs == 0 fprintf('Cannot determine sample rate. I get it to %.2f kHz\n', ... fs_est); fs = input('Please, input a sample rate (in kHz): '); else fprintf('Sample rate estimated to %i kHz\n', fs); end SendTimeMs = (TimeStampUW - TimeStampUW(1)) / fs; fprintf('Stream duration at sender: %.1f seconds\n', ... (SendTimeMs(end) - SendTimeMs(1)) / 1000); fprintf('Stream duration at receiver: %.1f seconds\n', ... (ArrTime(end) - ArrTime(1)) / 1000); fprintf('Clock drift: %.2f%%\n', ... 100 * ((ArrTime(end) - ArrTime(1)) / ... (SendTimeMs(end) - SendTimeMs(1)) - 1)); fprintf('Sent average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (SendTimeMs(end)-SendTimeMs(1)))); fprintf('Received average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (ArrTime(end)-ArrTime(1)))); %% Plots. delay = ArrTime - SendTimeMs; delay = delay - min(delay); delayOrdered = delay; delayOrdered(reorderIx) = nan; % Set reordered packets to NaN. delayReordered = delay(reorderIx); % Pick the reordered packets. sendTimeMsReordered = SendTimeMs(reorderIx); % Sort time arrays in packet send order. [~, sortix] = sort(SeqNoUW); SendTimeMs = SendTimeMs(sortix); Size = Size(sortix); delayOrdered = delayOrdered(sortix); figure plot(SendTimeMs / 1000, delayOrdered, ... sendTimeMsReordered / 1000, delayReordered, 'r.'); xlabel('Send time [s]'); ylabel('Relative transport delay [ms]'); title(sprintf('SSRC: %s', SSRC{1})); SendBitrateKbps = 8 * Size(1:end-1) ./ diff(SendTimeMs); figure plot(SendTimeMs(1:end-1)/1000, SendBitrateKbps); xlabel('Send time [s]'); ylabel('Send bitrate [kbps]'); end %% Subfunctions. % findReorderedPackets returns the index to all packets that are considered % old compared with the largest seen sequence number. The input seqNo must % be unwrapped for this to work. function reorderIx = findReorderedPackets(seqNo) largestSeqNo = seqNo(1); reorderIx = []; for i = 2:length(seqNo) if seqNo(i) < largestSeqNo reorderIx = [reorderIx; i]; %#ok<AGROW> else largestSeqNo = seqNo(i); end end end %% Auto-generated subfunction. function [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = ... importfile(filename, startRow, endRow) %IMPORTFILE Import numeric data from a text file as column vectors. % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME) Reads % data from text file FILENAME for the default selection. % % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME, % STARTROW, ENDROW) Reads data from rows STARTROW through ENDROW of text % file FILENAME. % % Example: % [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = % importfile('rtpdump_recv.txt',2, 123); % % See also TEXTSCAN. % Auto-generated by MATLAB on 2015/05/28 09:55:50 %% Initialize variables. if nargin<=2 startRow = 2; endRow = inf; end %% Format string for each line of text: % column1: double (%f) % column2: double (%f) % column3: double (%f) % column4: double (%f) % column5: double (%f) % column6: double (%f) % column7: text (%s) % For more information, see the TEXTSCAN documentation. formatSpec = '%5f%11f%11f%6f%6f%3f%s%[^\n\r]'; %% Open the text file. fileID = fopen(filename,'r'); %% Read columns of data according to format string. % This call is based on the structure of the file used to generate this % code. If an error occurs for a different file, try regenerating the code % from the Import Tool. dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ... 'Delimiter', '', 'WhiteSpace', '', 'HeaderLines', startRow(1)-1, ... 'ReturnOnError', false); for block=2:length(startRow) frewind(fileID); dataArrayBlock = textscan(fileID, formatSpec, ... endRow(block)-startRow(block)+1, 'Delimiter', '', 'WhiteSpace', ... '', 'HeaderLines', startRow(block)-1, 'ReturnOnError', false); for col=1:length(dataArray) dataArray{col} = [dataArray{col};dataArrayBlock{col}]; end end %% Close the text file. fclose(fileID); %% Post processing for unimportable data. % No unimportable data rules were applied during the import, so no post % processing code is included. To generate code which works for % unimportable data, select unimportable cells in a file and regenerate the % script. %% Allocate imported array to column variable names SeqNo = dataArray{:, 1}; TimeStamp = dataArray{:, 2}; SendTime = dataArray{:, 3}; Size = dataArray{:, 4}; PT = dataArray{:, 5}; M = dataArray{:, 6}; SSRC = dataArray{:, 7}; end
github
qian-liu/off_line_SNN-master
myOctaveVersion.m
.m
off_line_SNN-master/matlab_paf/util/myOctaveVersion.m
169
utf_8
d4603482a968c496b66a4ed4e7c72471
% return OCTAVE_VERSION or 'undefined' as a string function result = myOctaveVersion() if isOctave() result = OCTAVE_VERSION; else result = 'undefined'; end
github
qian-liu/off_line_SNN-master
isOctave.m
.m
off_line_SNN-master/matlab_paf/util/isOctave.m
108
utf_8
4695e8d7c4478e1e67733cca9903f9ef
%detects if we're running Octave function result = isOctave() result = exist('OCTAVE_VERSION') ~= 0; end
github
qian-liu/off_line_SNN-master
makeLMfilters.m
.m
off_line_SNN-master/matlab_paf/util/makeLMfilters.m
1,895
utf_8
21950924882d8a0c49ab03ef0681b618
function F=makeLMfilters % Returns the LML filter bank of size 49x49x48 in F. To convolve an % image I with the filter bank you can either use the matlab function % conv2, i.e. responses(:,:,i)=conv2(I,F(:,:,i),'valid'), or use the % Fourier transform. SUP=49; % Support of the largest filter (must be odd) SCALEX=sqrt(2).^[1:3]; % Sigma_{x} for the oriented filters NORIENT=6; % Number of orientations NROTINV=12; NBAR=length(SCALEX)*NORIENT; NEDGE=length(SCALEX)*NORIENT; NF=NBAR+NEDGE+NROTINV; F=zeros(SUP,SUP,NF); hsup=(SUP-1)/2; [x,y]=meshgrid([-hsup:hsup],[hsup:-1:-hsup]); orgpts=[x(:) y(:)]'; count=1; for scale=1:length(SCALEX), for orient=0:NORIENT-1, angle=pi*orient/NORIENT; % Not 2pi as filters have symmetry c=cos(angle);s=sin(angle); rotpts=[c -s;s c]*orgpts; F(:,:,count)=makefilter(SCALEX(scale),0,1,rotpts,SUP); F(:,:,count+NEDGE)=makefilter(SCALEX(scale),0,2,rotpts,SUP); count=count+1; end; end; count=NBAR+NEDGE+1; SCALES=sqrt(2).^[1:4]; for i=1:length(SCALES), F(:,:,count)=normalise(fspecial('gaussian',SUP,SCALES(i))); F(:,:,count+1)=normalise(fspecial('log',SUP,SCALES(i))); F(:,:,count+2)=normalise(fspecial('log',SUP,3*SCALES(i))); count=count+3; end; return function f=makefilter(scale,phasex,phasey,pts,sup) gx=gauss1d(3*scale,0,pts(1,:),phasex); gy=gauss1d(scale,0,pts(2,:),phasey); f=normalise(reshape(gx.*gy,sup,sup)); return function g=gauss1d(sigma,mean,x,ord) % Function to compute gaussian derivatives of order 0 <= ord < 3 % evaluated at x. x=x-mean;num=x.*x; variance=sigma^2; denom=2*variance; g=exp(-num/denom)/(pi*denom)^0.5; switch ord, case 1, g=-g.*(x/variance); case 2, g=g.*((num-variance)/(variance^2)); end; return function f=normalise(f), f=f-mean(f(:)); f=f/sum(abs(f(:))); return
github
xyxxmb/CVcode-master
make.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_SIFT/libsvm/make.m
940
utf_8
b8261ca58f0371965ae9b1c8ea3e9da3
% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix function make() try % This part is for OCTAVE if (exist ('OCTAVE_VERSION', 'builtin')) mex libsvmread.c mex libsvmwrite.c mex -I.. svmtrain.c ../libsvm/svm.cpp svm_model_matlab.c mex -I.. svmpredict.c ../libsvm/svm.cpp svm_model_matlab.c % This part is for MATLAB % Add -largeArrayDims on 64-bit machines of MATLAB else mex COMPFLAGS="\$COMPFLAGS -std=c99" -largeArrayDims libsvmread.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -largeArrayDims libsvmwrite.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../libsvm/svm.cpp svm_model_matlab.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../libsvm/svm.cpp svm_model_matlab.c end catch err fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line); disp(err.message); fprintf('=> Please check README for detailed instructions.\n'); end
github
xyxxmb/CVcode-master
lbp.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_SIFT/LBP/lbp.m
5,835
utf_8
e75b46f8a1e3ec7462b6bafc1c914b59
%LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkil? and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. error(nargchk(1,5,nargin)); image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end
github
xyxxmb/CVcode-master
getmapping.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_SIFT/LBP/getmapping.m
2,662
utf_8
3520760e26ca814b2eb0cecaa8891b1e
%GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkil? and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax;
github
xyxxmb/CVcode-master
make.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_HOG/libsvm/make.m
940
utf_8
b8261ca58f0371965ae9b1c8ea3e9da3
% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix function make() try % This part is for OCTAVE if (exist ('OCTAVE_VERSION', 'builtin')) mex libsvmread.c mex libsvmwrite.c mex -I.. svmtrain.c ../libsvm/svm.cpp svm_model_matlab.c mex -I.. svmpredict.c ../libsvm/svm.cpp svm_model_matlab.c % This part is for MATLAB % Add -largeArrayDims on 64-bit machines of MATLAB else mex COMPFLAGS="\$COMPFLAGS -std=c99" -largeArrayDims libsvmread.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -largeArrayDims libsvmwrite.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../libsvm/svm.cpp svm_model_matlab.c mex COMPFLAGS="\$COMPFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../libsvm/svm.cpp svm_model_matlab.c end catch err fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line); disp(err.message); fprintf('=> Please check README for detailed instructions.\n'); end
github
xyxxmb/CVcode-master
lbp.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_HOG/LBP/lbp.m
5,835
utf_8
e75b46f8a1e3ec7462b6bafc1c914b59
%LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkil? and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. error(nargchk(1,5,nargin)); image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end
github
xyxxmb/CVcode-master
getmapping.m
.m
CVcode-master/A Bayesian Hierarchical Model for Learning Natural Scene Categories/PG_BOW_DEMO_HOG/LBP/getmapping.m
2,662
utf_8
3520760e26ca814b2eb0cecaa8891b1e
%GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkil? and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax;
github
sheldona/hessianIK-master
LMFsolve.m
.m
hessianIK-master/matlab/ik/LMFsolve.m
10,348
utf_8
89bc7a366758036b07b83af3d6238091
function [xf, S, cnt] = LMFsolve(varargin) % LMFSOLVE Solve a Set of Nonlinear Equations in Least-Squares Sense. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % A solution is obtained by a shortened Fletcher version of the % Levenberg-Maquardt algoritm for minimization of a sum of squares % of equation residuals. % % [Xf, Ssq, CNT] = LMFsolve(FUN,Xo,Options) % FUN is a function handle or a function M-file name that evaluates % m-vector of equation residuals, % Xo is n-vector of initial guesses of solution, % Options is an optional set of Name/Value pairs of control parameters % of the algorithm. It may be also preset by calling: % Options = LMFsolve('default'), or by a set of Name/Value pairs: % Options = LMFsolve('Name',Value, ... ), or updating the Options % set by calling % Options = LMFsolve(Options,'Name',Value, ...). % % Name Values {default} Description % 'Display' integer Display iteration information % {0} no display % k display initial and every k-th iteration; % 'FunTol' {1e-7} norm(FUN(x),1) stopping tolerance; % 'XTol' {1e-7} norm(x-xold,1) stopping tolerance; % 'MaxIter' {100} Maximum number of iterations; % 'ScaleD' Scale control: % value D = eye(m)*value; % vector D = diag(vector); % {[]} D(k,k) = JJ(k,k) for JJ(k,k)>0, or % = 1 otherwise, % where JJ = J.'*J % Not defined fields of the Options structure are filled by default values. % % Output Arguments: % Xf final solution approximation % Ssq sum of squares of residuals % Cnt >0 count of iterations % -MaxIter, did not converge in MaxIter iterations % Example: Rosenbrock valey inside circle with unit diameter % R = @(x) sqrt(x'*x)-.5; % A distance from the radius r=0.5 % ros= @(x) [ 10*(x(2)-x(1)^2); 1-x(1); (R(x)>0)*R(x)*1000]; % [x,ssq,cnt]=LMFsolve(ros,[-1.2,1],'Display',1,'MaxIter',50) % returns x = [0.4556; 0.2059], ssq = 0.2966, cnt = 18. % % Note: Users with old MATLAB versions (<7), which have no anonymous % functions implemented, should call LMFsolve with named function for % residuals. For above example it is % [x,ssq,cnt]=LMFsolve('rosen',[-1.2,1]); % where the function rosen.m is of the form % function r = rosen(x) %% Rosenbrock valey with a constraint % R = sqrt(x(1)^2+x(2)^2)-.5; %% Residuals: % r = [ 10*(x(2)-x(1)^2) % first part % 1-x(1) % second part % (R>0)*R*1000. % penalty % ]; % % Reference: % Fletcher, R., (1971): A Modified Marquardt Subroutine for Nonlinear Least % Squares. Rpt. AERE-R 6799, Harwell % % Original code by: Miroslav Balda, [email protected] % Modified by: Sheldon Andrews, [email protected] % % 2007-07-02 v 1.0 % 2008-12-22 v 1.1 * Changed name of the function in LMFsolv % * Removed part with wrong code for use of analytical % form for assembling of Jacobian matrix % 2009-01-08 v 1.2 * Changed subfunction printit.m for better one, and % modified its calling from inside LMFsolve. % * Repaired a bug, which caused an inclination to % istability, in charge of slower convergence. % 2017-09-10 v 1.3 * Modified to accept exact Hessian and additional % options used by the IK framework. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OPTIONS %%%%%%% % Default Options if nargin==1 && strcmpi('default',varargin(1)) xf.Display = 0; % no print of iterations xf.MaxIter = 100; % maximum number of iterations allowed xf.ScaleD = 1.0; % default is unit scaling. xf.FunTol = 1e-7; % tolerace for final function value xf.XTol = 1e-4; % tolerance on difference of x-solutions xf.ExactHessian = false; % use exact Hessian xf.OutputFcn = []; % output function xf.SpecifyObjectiveGradient = true; return % Updating Options elseif isstruct(varargin{1}) % Options=LMFsolve(Options,'Name','Value',...) if ~isfield(varargin{1},'Display') error('Options Structure not correct for LMFsolve.') end xf=varargin{1}; % Options for i=2:2:nargin-1 name=varargin{i}; % Option to be updated if ~ischar(name) error('Parameter Names Must be Strings.') end name=lower(name(isletter(name))); value=varargin{i+1}; % value of the option if strncmp(name,'d',1), xf.Display = value; elseif strncmp(name,'f',1), xf.FunTol = value(1); elseif strncmp(name,'x',1), xf.XTol = value(1); elseif strncmp(name,'m',1), xf.MaxIter = value(1); elseif strncmp(name,'s',1), xf.ScaleD = value; else disp(['Unknown Parameter Name --> ' name]) end end return % Pairs of Options elseif ischar(varargin{1}) % check for Options=LMFSOLVE('Name',Value,...) Pnames=char('display','funtol','xtol','maxiter','scaled','hessian','outputfcn'); if strncmpi(varargin{1},Pnames,length(varargin{1})) xf=LMFsolve('default'); % get default values xf=LMFsolve(xf,varargin{:}); return end end % LMFSOLVE(FUN,Xo,Options) %%%%%%%%%%%%%%%%%%%%%%%% FUN=varargin{1}; % function handle if ~(isvarname(FUN) || isa(FUN,'function_handle')) error('FUN Must be a Function Handle or M-file Name.') end xc=varargin{2}; % Xo if nargin>2 % OPTIONS if isstruct(varargin{3}) options=varargin{3}; else if ~exist('options','var') options = LMFsolve('default'); end for i=3:2:size(varargin,2)-1 options=LMFsolve(options, varargin{i},varargin{i+1}); end end else if ~exist('options','var') options = LMFsolve('default'); end end x = xc(:); lx = length(x); if( options.ExactHessian ) [r,J,H] = feval(FUN,x); % Residuals, Jacobian, and Hessian at starting point H = H; else [r,J] = feval(FUN,x); H = J'*J; end %~~~~~~~~~~~~~~~~~ S = (r'*r); % compute function value epsx = options.XTol(:); epsf = options.FunTol(:); if length(epsx)<lx, epsx=epsx*ones(lx,1); end %~~~~~~~~~~~~~~~~~~~~~~~ nfJ = 2; A = H; % System matrix v = -J'*r; funccount = 1; stop = false; if (isa(options.OutputFcn,'function_handle')) optimValues.fval = r; optimValues.funccount = funccount; stop = feval(options.OutputFcn, x, optimValues, 'init'); end D = options.ScaleD; if isempty(D) D = diag(diag(A)); % automatic scaling for i = 1:lx if D(i,i)==0, D(i,i)=1; end end else if numel(D)>1 D = diag(sqrt(abs(D(1:lx)))); % vector of individual scaling else D = sqrt(abs(D))*eye(lx); % scalar of unique scaling end end Rlo = 0.25; Rhi = 0.75; l=1.0; % initial damping lc=.75; is=0; cnt = 0; ipr = options.Display; printit(ipr,-1); % Table header d = options.XTol; % vector for the first cycle maxit = options.MaxIter; % maximum permitted number of iterations % while cnt<maxit && ... % MAIN ITERATION CYCLE % any(abs(d) >= epsx) && ... %%%%%%%%%%%%%%%%%%%% % any(abs(r) >= epsf) while (~stop && cnt<maxit) % MAIN ITERATION CYCLE d = (A+l*D)\v; % negative solution increment xd = x-d; rd = feval(FUN,xd); funccount = funccount+1; % ~~~~~~~~~~~~~~~~~~~ nfJ = nfJ+1; Sd = (rd.'*rd); % value at next solution dS = d.'*(2*v-A*d); % predicted reduction R = (S-Sd)/dS; if R>Rhi % halve lambda if R too high l = l/2; % if l<lc, l=0; end elseif R<Rlo % find new nu if R too low nu = (Sd-S)/(d.'*v)+2; if nu<2 nu = 2; elseif nu>10 nu = 10; end if l==0 lc = 1/max(abs(diag(inv(A)))); l = lc; nu = nu/2; end l = nu*l; end if ipr~=0 && (rem(cnt,ipr)==0 || cnt==1) % print iteration? printit(ipr,cnt,nfJ,S,x,d,l,lc) end if Sd<S if( options.ExactHessian ) [rd,J,H] = feval(FUN,xd); % residuals, Jacobian, and Hessian at new point H = H; else [rd,J] = feval(FUN,xd); H = J'*J; end S = (rd'*rd); x = xd; r = rd; % ~~~~~~~~~~~~~~~~~~~~~~~~~ nfJ = nfJ+1; A = H; v = -J'*r; end if (isa(options.OutputFcn,'function_handle')) optimValues.fval = r; optimValues.funccount = funccount; stop = feval(options.OutputFcn, x, optimValues, 'iter'); end cnt = cnt+1; end % while xf = x; % final solution if cnt==maxit cnt = -cnt; end % maxit reached rd = feval(FUN,xf); nfJ = nfJ+1; Sd = (rd'*rd); if ipr, disp(' '), end printit(ipr,cnt,nfJ,Sd,xf,d,l,lc) function printit(ipr,cnt,res,SS,x,dx,l,lc) % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Printing of intermediate results % ipr < 0 do not print lambda columns % = 0 do not print at all % > 0 print every (ipr)th iteration % cnt = -1 print out the header % 0 print out second row of results % >0 print out first row of results if ipr~=0 if cnt<0 % table header disp('') disp(char('*'*ones(1,75))) fprintf(' itr nfJ SUM(r^2) dx'); if ipr>0 fprintf(' l '); end fprintf('\n'); disp(char('*'*ones(1,75))) disp('') else % iteration output if rem(cnt,ipr)==0 % Print iteration count, residual, sum of squares, and step size fprintf('%4.0f %4.0f %12.4e %12.4e %12.4e \n', cnt,res,SS,sqrt(dx'*dx),l); end end end
github
sheldona/hessianIK-master
runIK.m
.m
hessianIK-master/matlab/ik/runIK.m
7,838
utf_8
1e7d2f4c4105cb717d37fbf7d1f24ef3
function [x,f,history] = runIK(varargin) % Copyright (C) 2017 Sheldon Andrews % % Permission to use and modify in any way, and for any purpose, this % software, is granted by the author. Permission to redistribute % unmodified copies is also granted. Modified copies may only be % redistributed with the express written consent of: % Sheldon Andrews ([email protected]) % %RUNIK Run an IK optimization. % [x,f,history] = runIK(x0, skel, targets, method, useHessian, useBounds, ftol, maxiter, epsPCG, bPCG) %INPUTS: % x0 - Initial solution, the dofs of the skeleton including root trans. % skel - The skeleton data structure following HDM05 sepecification. % targets - The position of C3D markers. % method - 0 = trust-region method and exact Hessian, % 1 = a quasi-Newton method (BFGS) with exact gradient % 2 = Levenberg-Marquardt % useBounds - Apply joint angle box limits, in which case fmincon is used. % ftol - Stopping tolerance for the IK objective function. (Default 1e-20) % maxiter - Maximum number of iterations to use in the Newton or % quasi-Newton method. % epsPCG - Preconditioned Conjugate Gradient (PCG) stopping tolerance. % This is only used by the exact Newton algorithm with Hessian, which % is based on a reflective trust region method. (Default 0.1) % bPCG - Bandwidth of the preconditioner for PCG. (Default 24) %OUTPUTS: % x - The optimal solution, which is the degrees of freedom of the % skeleton % f - Objective function value at the optimal solution. % history - Cell array storing information about each iteration. % if( nargin < 3 ) disp('Usage: [x,f,history] = runIK(x0, skel, targets, method, useHessian, useBounds, ftol, maxiter, epsPCG, bPCG)'); return; else x0 = varargin{1}; skel = varargin{2}; targets = varargin{3}; method = 0; useHessian = false; useBounds = false; ftol = 1e-20; maxiter = 100; epsPCG = 1e-1; % Default values for epsPCG and bPCG selected based on bPCG = 8; % parameter sweep (see doParamSweep.m) end if( nargin > 3 ) method = varargin{4}; end if( nargin > 4 ) useHessian = varargin{5}; end if( nargin > 5 ) useBounds = varargin{6}; end if( nargin > 6 ) ftol = varargin{7}; end if( nargin > 7 ) maxiter = varargin{8}; end if( nargin > 8 ) epsPCG = varargin{9}; end if( nargin > 9 ) bPCG = varargin{10}; end %% Main optimization code % ndof = size(x0,1); conversion_factor = 1.; if( strcmp(skel.angleUnit,'deg') ) % conversion: degrees-to-radians conversion_factor = pi/180.; end if( method < 2 ) if( ~useBounds ) % setup unconstrained optimization options = optimoptions(@fminunc); if( useHessian ) options.Algorithm = 'trust-region'; options.HessianFcn = 'objective'; else options.Algorithm = 'quasi-newton'; options.HessianFcn = []; options.HessUpdate = 'bfgs'; end else % setup constrained optimization with joint limits options = optimoptions(@fmincon); if( useHessian ) options.Algorithm = 'trust-region-reflective'; options.HessianFcn = 'objective'; else options.Algorithm = 'interior-point'; options.HessianFcn = []; end end % % Options common to MATLAB algorithms % options.OutputFcn = @outfun; options.Display = 'iter'; options.StepTolerance = 1e-120; % Trust region options % options.MaxPCGIter = ndof*ndof; % Give cg more time to solve sub-problem. options.TolPCG = epsPCG; % Setting this too low will give poor convergence! options.PrecondBandWidth = bPCG; % Close to diagonal pre-conditioner seems to give good performance. options.FunctionTolerance= 1e-120; options.SpecifyObjectiveGradient = true; % We always specify the gradient. %options.CheckGradients = true; % Uncomment to verify the gradient. options.OptimalityTolerance = 1e-120; options.MaxIterations = maxiter; options.MaxFunctionEvaluations = 1e6; % Don't limit function evals, just max iterations. else % Use our custom LM solver % options = LMFsolve('default'); options.Display = 1; options.MaxIter = maxiter; options.ScaleD = []; options.FunTol = 1e-120; options.XTol = 1e-120; options.ExactHessian = useHessian; options.HessianFcn = 'objective'; options.OutputFcn = @outfun; options.SpecifyObjectiveGradient = true; end % Create struct to keep track of function values and % the solution at each iteration. history.fval = []; history.x = []; history.funccount = 0; % Create an empty motion struct to store the single frame % which is being optimized. We do this so that we can 'piggy back' on % the HDM05 forward kinematics functions. oneFrame = emptyMotion; oneFrame.njoints = skel.njoints; oneFrame.nframes = 1; oneFrame.jointNames = skel.jointNames; oneFrame.nameMap = skel.nameMap; oneFrame.animated = skel.animated; oneFrame.unanimated = skel.unanimated; oneFrame.angleUnit = 'rad'; if( method < 2 && ~useBounds ) % unconstrained optimization [x,f] = fminunc(@ikFunc,x0,options); elseif( method < 2 ) % constrained optimization with joint limits [x,f] = fmincon(@ikFunc,x0,[],[],[],[],skel.lb,skel.ub,[],options); else [x,f] = LMFsolve(@ikFunc,x0,options); end %% Nested function to evaluate the IK solution x. % The exact gradient and Hessian are also returned. % function [f,g,H] = ikFunc(x) oneFrame = unpackDOF(x, skel, oneFrame, 1); oneFrame = convert2quat(skel,oneFrame); [oneFrame.jointTrajectories,oneFrame.jointRotations] = forwardKinematicsQuat(skel,oneFrame); [bonePos, boneQuat] = extractBonePosQuat(skel,oneFrame,1); [f, r] = objectiveIK(skel, bonePos, boneQuat, targets); H = []; g = []; if( method < 2 ) if( nargout > 1 && options.SpecifyObjectiveGradient ) % only compute gradient if req'd. [ J ] = jacobianIK(skel, bonePos, boneQuat, x, targets); g = -J'*r; end else if( nargout > 1 && options.SpecifyObjectiveGradient ) % only compute gradient if req'd. [ J ] = jacobianIK(skel, bonePos, boneQuat, x, targets); g = J; end f = r; end if( nargout > 2 && ~isempty(options.HessianFcn) ) % only compute Hessian if req'd. [ H ] = hessianIK(skel, bonePos, boneQuat, x, targets, J); % H = nearestSPD(H); % disp(['Condition number ' num2str(cond(H)) ', rank ' num2str(rank(H))]); % if( ~check ) % y = 1; % end end end %% Nested function to collect optimization % function stop = outfun(x,optimValues,state) stop = false; switch state case 'iter' % Concatenate current point and objective function % value with history. x must be a row vector. if( isfield(optimValues, 'fval') ) [m,n] = size(optimValues.fval); if( m > 1 ), fval = 0.5*optimValues.fval'*optimValues.fval; else fval = optimValues.fval; end elseif( isfield(optimValues, 'residual') ) fval = 0.5*optimValues.residual'*optimValues.residual; end history.fval = [history.fval; fval]; history.x = [history.x; x]; history.funccount = history.funccount + optimValues.funccount; if( fval < ftol ) stop = true; end otherwise end end end
github
sheldona/hessianIK-master
scaleSkelMot.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/scaleSkelMot.m
1,327
utf_8
adfc3ca5991b4d42619f4af9d67e53bb
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [skel,mot] = scaleSkelMot(skel,mot,S) % [skel,mot] = scaleSkelMot(skel,mot,S) % S is the downscale factor for k=1:length(skel.nodes) skel.nodes(k).length = skel.nodes(k).length/S; skel.nodes(k).offset = skel.nodes(k).offset/S; end mot.rootTranslation = mot.rootTranslation/S; mot.jointTrajectories = forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot); s = sprintf('Motion scaled using "scaleSkelMot" with factor %f',S); mot.documentation = vertcat(mot.documentation,{s});
github
sheldona/hessianIK-master
trajectoryID.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/trajectoryID.m
1,111
utf_8
930b62e1d6b4f5a64b70c64a8f333ebe
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function ID = trajectoryID(skel,jointname) i = strmatch(upper(jointname),upper(skel.nameMap(:,1)),'exact'); if (isempty(i)) error(['Unknown standard joint name "' jointname '"!']); end if (length(i)>1) error(['Ambiguous standard joint name "' jointname '"!']); end ID = skel.nameMap{i,3};
github
sheldona/hessianIK-master
eatWhitespace.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/eatWhitespace.m
1,101
utf_8
b72fc9f0488ce8f7a64dc7be3c1492d8
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function l_out = eatWhitespace(l_in) % fast forward in file, skipping whitespace n = 1; for i = 1:size(l_in,2) c = double(l_in(i)); if (c == 9) | (c == 10) | (c == 13) | (c == 32) % TAB, CR, LF, SPC n = n+1; else break; end end l_out = l_in(n:size(l_in,2));
github
sheldona/hessianIK-master
forwardKinematicsQuat.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/forwardKinematicsQuat.m
1,419
utf_8
5429b3ff27b5cf1797d3feaee1b6606e
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [jointTrajectories,jointRotations] = forwardKinematicsQuat(skel,mot) [jointTrajectories,jointRotations] = recursive_forwardKinematicsQuat(skel,... mot,... 1,... mot.rootTranslation + repmat(skel.nodes(1).offset,1,mot.nframes),... quatmult(repmat(skel.rootRotationalOffsetQuat,1,mot.nframes),mot.rotationQuat{1}),... mot.jointTrajectories, mot.jointRotations);
github
sheldona/hessianIK-master
recursive_forwardKinematicsEuler.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/recursive_forwardKinematicsEuler.m
3,643
utf_8
7d328b56ae42bdc58cbecd6b4639bf36
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [trajectories,rotations] = recursive_forwardKinematicsEuler(skel, mot, node_id, current_position, current_rotation, trajectories, rotations) % trajectories = recursive_forwardKinematicsEuler(skel, mot, node_id, current_position, current_rotation, trajectories) % % skel: skeleton % mot: motion % node_id: index of current node in node array % current_position: for all frames: current local coordinate offsets from world origin (3xnframes sequence of vectors) % current_rotation: for all frames: current local coordinate rotations against world coordinate frame (4xnframes sequence of quaternions) % trajectories: input & output cell array containing the trajectories that have been computed so far % rotations: input & output cell array containing the rotations that have been computed so far switch lower(mot.angleUnit) case 'deg' conversion_factor = pi/180; case 'rad' conversion_factor = 1; otherwise error(['Unknown angle unit: ' mot.angleUnit]); end trajectories{node_id,1} = current_position; rotations{node_id,1} = current_rotation; for child_id = skel.nodes(node_id).children' child = skel.nodes(child_id); if (~isempty(mot.rotationEuler{child_id})) nRotDOF = size(mot.rotationEuler{child.ID,1},1); % number of rotational DOFs % zero-pad Euler array at the appropriate places, according to rotation order and presence/absence of respective DOFs if nRotDOF > 0 completeEulers = zeros(3,mot.nframes); d = 1; % index for DOFs present in mot.rotationEuler for r = 1:3 % go through rotationOrder. idx = strmatch(['r' lower(child.rotationOrder(r))], lower(child.DOF), 'exact'); if (~isempty(idx)) completeEulers(r,:) = mot.rotationEuler{child.ID,1}(d,:)*conversion_factor; d = d+1; end end axis_quat = repmat(euler2quat(flipud(child.axis)*conversion_factor,'zyx'),1,mot.nframes); % According to ASF specs, rotation order for "axis" should be XYZ. However, they use the opposite multiplication order as we do! rotationQuat = quatmult(axis_quat,quatmult(euler2quat(flipud(completeEulers),fliplr(child.rotationOrder)),quatinv(axis_quat))); % ASF specs use opposite multiplication order as we do, hence fliplr() and flipud()! end child_rotation = quatmult(current_rotation,rotationQuat); else child_rotation = current_rotation; end child_position = current_position + quatrot(repmat(child.offset,1,mot.nframes),child_rotation); [trajectories,rotations] = recursive_forwardKinematicsEuler(skel, mot, child_id, child_position, child_rotation, trajectories, rotations); end
github
sheldona/hessianIK-master
recursive_forwardKinematicsQuat.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/recursive_forwardKinematicsQuat.m
2,212
utf_8
719da37ba0ceddce75b2e190eefffe4c
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [trajectories,rotations] = recursive_forwardKinematicsQuat(skel, mot, node_id, current_position, current_rotation, trajectories, rotations) % trajectories = recursive_forwardKinematicsQuat(skel, mot, node_id, current_position, current_rotation, trajectories) % % skel: skeleton % mot: motion % node_id: index of current node in node array % current_position: for all frames: current local coordinate offsets from world origin (3xnframes sequence of vectors) % current_rotation: for all frames: current local coordinate rotations against world coordinate frame (4xnframes sequence of quaternions) % trajectories: input & output cell array containing the trajectories that have been computed so far trajectories{node_id,1} = current_position; rotations{node_id,1} = current_rotation; parent = skel.nodes(node_id); for child_id = skel.nodes(node_id).children' child = skel.nodes(child_id); if (~isempty(mot.rotationQuat{child_id})) child_rotation = quatmult(current_rotation,mot.rotationQuat{child_id}); else child_rotation = current_rotation; end child_position = current_position + quatrot(repmat(parent.offset,1,mot.nframes),current_rotation); [trajectories,rotations] = recursive_forwardKinematicsQuat(skel, mot, child_id, child_position, child_rotation, trajectories, rotations); end
github
sheldona/hessianIK-master
averageFrontVector.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/averageFrontVector.m
1,289
utf_8
3b7f6f6fe483ed4a64e320be687d842a
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function v = averageFrontVector(mot,varargin) p1_name = 'lhip'; p2_name = 'rhip'; if (nargin>2) p2_name = varargin{2}; end if (nargin>1) p1_name = varargin{1}; end p1 = trajectoryID(mot,p1_name); p2 = trajectoryID(mot,p2_name); n = mot.jointTrajectories{p1} - mot.jointTrajectories{p2}; n = n([1 3],:); n = n./repmat(sqrt(sum(n.^2)),2,1); v = mean(n,2); v = v/sqrt(sum(v.^2)); v = [-v(2);v(1)]; % compute front vector as normal of average direction from lhip to rhip
github
sheldona/hessianIK-master
computeBoundingBox.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/computeBoundingBox.m
1,374
utf_8
27fa4c644f03225656638b7994aff02b
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function boundingBox = computeBoundingBox(mot) boundingBox = [inf;-inf;inf;-inf;inf;-inf]; for k = 1:mot.njoints trajectory = mot.jointTrajectories{k}; boundingBox(1) = min(boundingBox(1),min(trajectory(1,:))); % xmin boundingBox(2) = max(boundingBox(2),max(trajectory(1,:))); % xmax boundingBox(3) = min(boundingBox(3),min(trajectory(2,:))); % ymin boundingBox(4) = max(boundingBox(4),max(trajectory(2,:))); % ymax boundingBox(5) = min(boundingBox(5),min(trajectory(3,:))); % zmin boundingBox(6) = max(boundingBox(6),max(trajectory(3,:))); % zmax end
github
sheldona/hessianIK-master
reflectMotYZ.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/reflectMotYZ.m
1,360
utf_8
b98a41cc5913918c779cdc1eebf6fe0a
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot = reflectMotYZ(mot) %%%%%%%% reflect elderwalk about yz plane for k=1:length(mot.jointTrajectories) mot.jointTrajectories{k,1}([1],:) = -mot.jointTrajectories{k,1}([1],:); mot.jointTrajectories{k,1} = mot.jointTrajectories{k,1} - repmat(mot.rootTranslation(:,1) - mot.rootTranslation(:,1),1,mot.nframes); end mot.rootTranslation([1],:) = -mot.rootTranslation([1],:); mot.rootTranslation = mot.rootTranslation - repmat(mot.rootTranslation(:,1) - mot.rootTranslation(:,1),1,mot.nframes); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
sheldona/hessianIK-master
findNextToken.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/findNextToken.m
1,177
utf_8
4367d453652e96e43a65c9e7ff6bbd00
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [result, token] = findNextToken(fid) % stops at first occurence of any non-whitespace word and returns the entire line as token. line_count = 0; while ~feof(fid) line = fgetl(fid); line_count = line_count + 1; line = strtok(line); if (length(line)>0) token = line; result = true; return; end end result = false;
github
sheldona/hessianIK-master
forwardKinematicsEuler.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/forwardKinematicsEuler.m
2,294
utf_8
cf8b5abbc0e2f08bc9b39c35b738f0e6
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [jointTrajectories,jointRotations] = forwardKinematicsEuler(skel,mot) switch lower(mot.angleUnit) case 'deg' conversion_factor = pi/180; case 'rad' conversion_factor = 1; otherwise error(['Unknown angle unit: ' mot.angleUnit]); end % root node involves special case for determination of rotation order (node.rotationOrder only concerns the global rotational offset in this case) node = skel.nodes(1); completeEulers = mot.rotationEuler{1}; rootTransformationOrder = char(skel.nodes(1).DOF); rootTransformationOrder = rootTransformationOrder(:,2)'; [x,IA,IB] = intersect({'rx','ry','rz'}, lower(skel.nodes(1).DOF)); rootRotationOrder = rootTransformationOrder(sort(IB)); mot.rotationQuat{node.ID,1} = euler2quat(flipud(completeEulers),fliplr(node.rotationOrder)); % ASF specs use opposite multiplication order as we do, hence fliplr() and flipud()! [jointTrajectories,jointRotations] = recursive_forwardKinematicsEuler(skel,... mot,... 1,... mot.rootTranslation + repmat(skel.nodes(1).offset,1,mot.nframes),... quatmult(repmat(skel.rootRotationalOffsetQuat,1,mot.nframes),euler2quat(conversion_factor*flipud(mot.rotationEuler{1}),rootRotationOrder)),... mot.jointTrajectories, mot.jointRotations);
github
sheldona/hessianIK-master
findKeyword.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/findKeyword.m
1,394
utf_8
4b11f2d224ce9c9ee1d15ff1b0edf79c
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [b, line, pos, line_count] = findKeyword(varargin) % stops at first occurence of any of the keywords. NOT case sensitive! % args: fid,keywords if nargin < 2 error('Not enough arguments!'); end fid = varargin{1}; pos = 0; line_count = 0; line = []; while ~feof(fid) l = eatWhitespace(fgetl(fid)); line_count = line_count + 1; for i = 2:nargin k = strfind(upper(l),upper(varargin{i})); if size(k) > 0 line = l(k:size(l,2)); b = true; pos = ftell(fid); return; end end end b = false;
github
sheldona/hessianIK-master
readMocapGUI.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/readMocapGUI.m
1,997
utf_8
27f8ac81934acbe5dbfd371cfc8881dd
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [skel, mot] = readMocapGUI(noCaching); % [skel, mot] = readMocapGUI(noCaching) if nargin < 1 noCaching = false; end global VARS_GLOBAL; oldPath = cd; try defaultPath = VARS_GLOBAL.readMocapGUILastDir; catch try defaultPath = VARS_GLOBAL.dir_root; catch defaultPath = cd; end end cd(defaultPath); [datafile,datapath] = uigetfile('*.c3d; *.amc', 'Choose data file', 40, 40); if datafile ~= 0 VARS_GLOBAL.readMocapGUILastDir = datapath; idx = findstr(datafile,'.'); ext = upper(datafile(idx(end):end)); if strcmp(ext, '.C3D') [skel, mot] = readMocap([datapath,datafile], [], noCaching); elseif strcmp(ext, '.AMC') asfFiles = dir([datapath '\*.ASF']); if isempty(asfFiles) cd(datapath); [asfFile, asfPath] = uigetfile('*.asf', 'Choose ASF file', 40, 40); else asfPath = datapath; asfFile = [datafile(1:6) '.ASF']; end [skel, mot] = readMocap([datapath,asfFile], [datapath,datafile], [], true, true, true, noCaching); end end cd(oldPath);
github
sheldona/hessianIK-master
cropMot.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/cropMot.m
2,152
utf_8
eba0a2efc5c1dac2063903d9f011883b
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot_out = cropMot(mot_in,range) if isempty(range) mot_out = mot_in; return; end mot_out = emptyMotion; mot_out.njoints = mot_in.njoints; mot_out.nframes = length(range); mot_out.frameTime = mot_in.frameTime; mot_out.samplingRate = mot_in.samplingRate; mot_out.jointNames = mot_in.jointNames; mot_out.boneNames = mot_in.boneNames; mot_out.nameMap = mot_in.nameMap; mot_out.animated = mot_in.animated; mot_out.unanimated = mot_in.unanimated; if not(isempty(mot_in.rootTranslation)) mot_out.rootTranslation = mot_in.rootTranslation(:,range); end for k = 1:size(mot_in.jointTrajectories,1) if ~isempty(mot_in.jointTrajectories{k,1}) mot_out.jointTrajectories{k,1} = mot_in.jointTrajectories{k,1}(:,range); end end for k = 1:size(mot_in.rotationEuler,1) if (~isempty(mot_in.rotationEuler{k})) mot_out.rotationEuler{k,1} = mot_in.rotationEuler{k,1}(:,range); end end for k = 1:size(mot_in.rotationQuat,1) if (~isempty(mot_in.rotationQuat{k,1})) mot_out.rotationQuat{k,1} = mot_in.rotationQuat{k,1}(:,range); end end mot_out.filename = mot_in.filename; mot_out.documentation = vertcat(mot_in.documentation,{['The original file has been cropped to the range ' num2str(range) '!']}); mot_out.angleUnit = mot_in.angleUnit; mot_out.boundingBox = computeBoundingBox(mot_out);
github
sheldona/hessianIK-master
filename2info.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/filename2info.m
2,729
utf_8
e4219a9b0c0ec499293fc7d24cf4d08e
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [info,OK] = filename2info(amcfullpath) info = struct('amcname','',... 'asfname','',... 'amcpath','',... 'filetype','ASF/AMC',... 'skeletonSource','',... 'skeletonID','',... 'motionCategory','',... 'motionDescription','',... 'samplingRate',0); [info.amcpath, name, ext] = fileparts(amcfullpath); info.amcname = [name ext]; % n = strfind(amcfullpath, filesep); % if (isempty(n)) % info.amcpath = ''; % info.amcname = amcfullpath; % else % n = n(end); % info.amcpath = amcfullpath(1:n); % info.amcname = amcfullpath(n+1:end); % end OK = true; p = strfind(info.amcname,'_'); if (length(p)~=4) disp(['**** Filename "' info.amcname '" doesn''t conform with MoCaDa standard!']); OK = false; return; end n = strfind(info.amcname,'.'); if (length(n)<=0) % no period in amc filename? weird... there should at least be a ".amc"!! disp(['**** Filename "' info.amcname '" doesn''t have a file extension!']); OK = false; return; % n = length(info.amcname+1); else n = n(end); end info.skeletonSource = info.amcname(1:p(1)-1); info.skeletonID = info.amcname(p(1)+1:p(2)-1); info.motionCategory = info.amcname(p(2)+1:p(3)-1); info.motionDescription = info.amcname(p(3)+1:p(4)-1); [info.samplingRate,OK] = str2num(info.amcname(p(4)+1:n-1)); if (~OK) disp(['**** Couldn''t deduce sampling rate from filename "' info.amcname '"!']); end if (strcmpi(info.amcname(n(end)+1:end),'BVH')) info.asfname = info.amcname; info.filetype = 'BVH'; elseif (strcmpi(info.amcname(n(end)+1:end),'C3D')) info.asfname = info.amcname; info.filetype = 'C3D'; elseif (strcmpi(info.amcname(n(end)+1:end),'mpii')) info.asfname=''; info.filetype = 'MPII'; else info.asfname = [info.skeletonSource '_' info.skeletonID '.asf']; end
github
sheldona/hessianIK-master
readMocapD.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/readMocapD.m
1,493
utf_8
874ec42ed05d5143dff477a18be81a71
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [skel,mot] = readMocapD(file_num, range) global VARS_GLOBAL if ~(exist('DB_concat')) DB_concat = DB_index_load('HDM05_amc',{'AK_lower'},4); files_name = DB_concat.files_name; end amcfullpath = fullfile(VARS_GLOBAL.dir_root, files_name{file_num}); [info,OK] = filename2info(amcfullpath); if (OK) [skel,mot] = readMocap([info.amcpath info.asfname], amcfullpath, [1 inf]); if (nargin > 2) mot = cropMot(mot, range); end elseif strcmpi(amcfullpath(end-4:end),'.bvh') [skel,mot] = readMocap(amcfullpath); else % assume an AMC file with an ASF that has the same name [skel,mot] = readMocap([amcfullpath(1:end-4) '.asf'],amcfullpath); end
github
sheldona/hessianIK-master
emptyMotion.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/emptyMotion.m
2,872
utf_8
38f0c2659c457303e73eb708c9a7ebce
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot = emptyMotion mot = struct('njoints',0,... % number of joints 'nframes',0,... % number of frames 'frameTime',1/120,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',120,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',cell(1,1),... % 3D joint trajectories 'jointRotations',cell(1,1),... % 3D joint rotations (as quats) 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',cell(1,1),... % cell array of joint names: maps node ID to joint name 'boneNames',cell(1,1),... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',cell(1,1),... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',[],... % vector of IDs for animated joints/bones 'unanimated',[],... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad
github
sheldona/hessianIK-master
constructNameMap.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/constructNameMap.m
4,020
utf_8
574b0f767b91884c549577440a2e5408
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function map = constructNameMap(skel) % format: % standard joint name, DOF ID, trajectory ID switch skel.fileType case 'TOM.ASF' map = {'root',1,1;... 'lhip',3,25;... %25 sacroiliac_@_l_hip 'lknee',4,26;... %26 l_hip_@_l_knee 'lankle',5,27;... %27 l_knee_@_l_ankle 'ltoes',0,29;... %29 l_metatarsal_@_l_forefoot_tip 'rhip',8,31;... %31sacroiliac_@_r_hip 'rknee',9,32;... %32r_hip_@_r_knee 'rankle',10,33;... %33r_knee_@_r_ankle 'rtoes',0,35;... %35r_metatarsal_@_r_forefoot_tip 'belly',13,4;... %4vl1_@_vt10 'chest',14,5;... %5vt10_@_vt6 'neck',15,6;... %6vt6_@_vt1 'head',17,7;... %7vt1_@_skullbase 'headtop',0,8;... %8skullbase_@_skull_tip 'lclavicle',18,6;... 'lshoulder',19,13;...%13l_acromioclavicular_@_l_shoulder 'lelbow',20,14;... %14l_shoulder_@_l_elbow 'lwrist',22,15;... %15l_elbow_@_l_wrist 'lfingers',0,16;... %16l_wrist_@_l_wrist_tip 'rclavicle',25,6;... 'rshoulder',26,19;...%19r_acromioclavicular_@_r_shoulder 'relbow',27,20;... %20r_shoulder_@_r_elbow 'rwrist',29,21;... %21r_elbow_@_r_wrist 'rfingers',0,22}; %22r_wrist_@_r_wrist_tip case 'ASF' map = {'root',1,1;... 'lhip',3,2;... 'lknee',4,3;... 'lankle',5,4;... 'ltoes',0,6;... 'rhip',8,7;... 'rknee',9,8;... 'rankle',10,9;... 'rtoes',0,11;... 'belly',13,12;... 'chest',14,13;... 'neck',15,14;... 'head',17,16;... 'headtop',0,17;... 'lclavicle',18,14;... 'lshoulder',19,18;... 'lelbow',20,19;... 'lwrist',22,21;... 'lfingers',0,23;... 'rclavicle',25,14;... 'rshoulder',26,25;... 'relbow',27,26;... 'rwrist',29,28;... 'rfingers',0,30}; case 'BVH' map = {'root',1,1;... 'lhip',19,18;... 'lknee',20,19;... 'lankle',21,20;... 'ltoes',0,21;... 'rhip',23,22;... 'rknee',24,23;... 'rankle',25,24;... 'rtoes',0,25;... 'belly',3,2;... 'chest',17,3;... 'neck',15,14;... 'head',16,15;... 'headtop',0,16;... 'lclavicle',5,4;... 'lshoulder',6,5;... 'lelbow',7,6;... 'lwrist',8,7;... 'lfingers',0,8;... 'rclavicle',10,9;... 'rshoulder',11,10;... 'relbow',12,11;... 'rwrist',13,12;... 'rfingers',0,13}; case 'MPII' map = {'root',0,1;... 'lhip',0,2;... 'lknee',0,3;... 'lankle',0,4;... 'ltoes',0,5;... 'rhip',0,6;... 'rknee',0,7;... 'rankle',0,8;... 'rtoes',0,9;... 'belly',0,10;... 'chest',0,11;... 'neck',0,12;... 'head',0,13;... 'headtop',0,14;... 'lclavicle',0,15;... 'lshoulder',0,16;... 'lelbow',0,17;... 'lwrist',0,18;... 'lfingers',0,19;... 'lhand',0,19;... 'rclavicle',0,20;... 'rshoulder',0,21;... 'relbow',0,22;... 'rwrist',0,23;... 'rfingers',0,24;... 'rhand',0,24}; end
github
sheldona/hessianIK-master
rotateMotY.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/rotateMotY.m
1,223
utf_8
a9f76f0c3d064b7e2ff764321d52c817
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [mot,skel] = rotateMotY(skel,mot,desiredFrontVec,varargin) frontVec = averageFrontVector(mot,varargin{:}); phi = directedAngle(frontVec,desiredFrontVec); skel.rootRotationalOffsetQuat = euler2quat([0; -phi; 0],'xyz'); mot.rootTranslation = quatrot(mot.rootTranslation,skel.rootRotationalOffsetQuat); mot.jointTrajectories = forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot);
github
sheldona/hessianIK-master
escapeUnderscore.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/escapeUnderscore.m
972
utf_8
767b62cc11a1fb04793099750b766bbf
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [ escapedString ] = escapeUnderscore( string ) %ESCAPEUNDERSCORE Escapes all underscores _ of string to \_ . escapedString = strrep(string, '_', '\_');
github
sheldona/hessianIK-master
readMocap.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/readMocap.m
6,473
utf_8
d034211789e7b0ff5581ade56787b029
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [skel,mot] = readMocap(skelfile, varargin) % Reads file formats ASF/AMC, BVH or C3D into [skel, mot] structure. % Possible calls: % % [skel,mot] = readMocap(ASFfile, AMCfile, frameRange, compute_quats, do_FK, use_TXT_or_BIN, noCaching) % [skel,mot] = readMocap(BVHfile, frameRange, compute_quats, do_FK, noCaching) % [skel,mot] = readMocap(C3Dfile, frameRange, generateSkel, skelFitMethod, noCaching) % where skelFitMethod can be 'ATS' (default), 'trans_heu', 'trans_opt' or 'none'. % WARNING: If left empty, bone lengths will vary over time! % [skel,mot] = readMocap(MPIIfile, noCaching) % set defaults global VARS_GLOBAL; if nargin < 1 help readMocap return end motfile = skelfile; range = []; compute_quats = true; do_FK = true; use_TXT_or_BIN = true; generateSkeleton = true; skelFitMethod = 'ATS'; noCaching = false; % parse Parameter list fileExtension = upper(skelfile(end-3:end)); if strcmp(fileExtension, '.C3D') if nargin > 1, range = varargin{1}; end if nargin > 2, generateSkeleton = varargin{2}; end if nargin > 3, skelFitMethod = varargin{3}; end if nargin > 4, noCaching = varargin{4}; end if isempty(skelFitMethod) skelFitMethod = 'ATS'; end elseif strcmp(fileExtension, '.ASF') if nargin > 1, motfile = varargin{1}; end if nargin > 2, range = varargin{2}; end if nargin > 3, compute_quats = varargin{3}; end if nargin > 4, do_FK = varargin{4}; end if nargin > 5, use_TXT_or_BIN = varargin{5}; end if nargin > 6, noCaching = varargin{6}; end elseif strcmp(fileExtension, '.BVH') if nargin > 1, range = varargin{1}; end if nargin > 2, compute_quats = varargin{2}; end if nargin > 3, do_FK = varargin{3}; end if nargin > 4, noCaching = varargin{4}; end elseif strcmp(fileExtension, 'MPII') if nargin > 1, noCaching = varargin{1}; end else error(['Unknown file extension: ' fileExtension]); end % Caching writeMAT = false; % write a MAT-file? existsMAT = false; matFullpath = [motfile '.mat']; csvFullpath = [motfile '.csv']; if exist('VARS_GLOBAL','var') && isfield(VARS_GLOBAL,'dir_root') && isfield(VARS_GLOBAL,'dir_additional') csvFullpath = strrep(csvFullpath,VARS_GLOBAL.dir_root,VARS_GLOBAL.dir_additional); end if ~noCaching h = fopen(matFullpath); % does MAT version already exist? if (h~=-1) fclose(h); load(matFullpath, 'skel', 'mot'); existsMAT = true; % in case of C3D we have to check whether the *.MAT file contains a % skeleton or not. This should not be the case but who knows... % maybe someone saved a version with a generated skeleton. if strcmp(fileExtension, '.C3D') if isempty(strmatch('root', skel.nameMap(:,1))) % if no root-joint present => marker based if generateSkeleton ; % we want a skeleton but did not get one: Construct it later else return; % we did not get a skeleton and don't want one => good! :-) end else if generateSkeleton disp('WARNING:'); disp('Keeping skeleton-version of cached MAT-file... check bone length constraints!'); return; % we got a skeleton and want it => good! :-) else writeMAT = true; % parse again, because we got a skeleton-based MAT-file but don't want it end end else %mot.csvFile = csvFullpath; %[mot.Labels,mot.Data] = BK_load_csv(csvFullpath); return; % in case of BVH or ASF/AMC, use the cached version end else writeMAT = true; end end % delegate to parser if ~existsMAT switch (fileExtension) case '.BVH' [skel,mot] = readBVH(skelfile,range,compute_quats,do_FK); save(matFullpath, 'skel', 'mot'); case '.ASF' skel = readASF(skelfile); mot = readAMC(motfile,skel,range,compute_quats,do_FK,use_TXT_or_BIN); mot.csvFile = csvFullpath; mot.Labels = {}; mot.Data = {}; save(matFullpath, 'skel', 'mot'); case '.C3D' [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError] = readC3D(skelfile); %[skel, mot] = convertC3D_to_skelMot(Markers, ParameterGroup, VideoFrameRate, skelfile, generateSkeleton); [skel, mot] = convertC3D_to_skelMot(Markers, ParameterGroup, VideoFrameRate, skelfile); %[skel, mot] = convertC3D_to_skelMot_NEFF_dirty(Markers, ParameterGroup, VideoFrameRate, skelfile); % save *.MAT if writeMAT save(matFullpath, 'skel', 'mot'); end case 'MPII' [skel, mot] = readMPII(skelfile); % save *.MAT if writeMAT save(matFullpath, 'skel', 'mot'); end end end if strcmp(fileExtension, '.C3D') % generate Skeleton if needed if generateSkeleton [skel, mot] = generateSkel(skel, mot); if not(strcmpi(skelFitMethod, 'none')) switch(upper(skelFitMethod)) case 'ATS' mot = skelfitATS(mot); case 'TRANS_HEU' mot = skelfitH(mot, 'boneNumbers', 0.15); case 'TRANS_OPT' mot = skelfitOptT(mot); otherwise error('Unknown skelfit method!'); end end end end
github
sheldona/hessianIK-master
DOFID.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/DOFID.m
1,104
utf_8
5b01ed99ee13d7c42cbc33375554169f
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function ID = DOFID(skel,jointname) i = strmatch(upper(jointname),upper(skel.nameMap(:,1)),'exact'); if (isempty(i)) error(['Unknown standard joint name "' jointname '"!']); end if (length(i)>1) error(['Ambiguous standard joint name "' jointname '"!']); end ID = skel.nameMap{i,2};
github
sheldona/hessianIK-master
resampleMot_new.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/resampleMot_new.m
2,897
utf_8
511955a12057902dc5b302b8879bd2ab
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot_out = resampleMot_new(skel_in, mot_in,target_frame_rate) target_frame_rate = round(target_frame_rate); mot_out = emptyMotion; mot_out.njoints = mot_in.njoints; mot_out.frameTime = 1/target_frame_rate; mot_out.samplingRate = target_frame_rate; mot_out.jointNames = mot_in.jointNames; mot_out.boneNames = mot_in.boneNames; mot_out.nameMap = mot_in.nameMap; mot_out.animated = mot_in.animated; mot_out.unanimated = mot_in.unanimated; if ~isempty(mot_in.rootTranslation) %mot_out.rootTranslation = resample(mot_in.rootTranslation',target_frame_rate,round(mot_in.samplingRate))'; mot_out.rootTranslation = resampleTSData(mot_in.rootTranslation,round(mot_in.samplingRate),target_frame_rate); end if ~isempty(mot_in.rotationQuat) for k = 1:size(mot_in.rotationQuat,1) if (~isempty(mot_in.rotationQuat{k,1})) %mot_out.rotationQuat{k,1} = resample(mot_in.rotationQuat{k,1}',target_frame_rate,round(mot_in.samplingRate))'; mot_out.rotationQuat{k,1} = resampleTSData(mot_in.rotationQuat{k,1},round(mot_in.samplingRate),target_frame_rate); mot_out.rotationQuat{k,1} = quatnormalize(mot_out.rotationQuat{k,1}); end end mot_out.nframes= size(mot_out.rotationQuat{1}, 2); mot_out.jointTrajectories = forwardKinematicsQuat(skel_in, mot_out); for k = 1:size(mot_in.rotationEuler,1) if (~isempty(mot_in.rotationEuler{k})) mot_out.rotationEuler{k,1} = quat2euler(mot_in.rotationQuat{k, 1}); end end else error('This motion does not contain the field "rotationQuat" or the field is empty!\nIf you want to resize motions containing C3D marker positions, better use "resampleMotion"'); end mot_out.nframes = max( size(mot_out.rootTranslation,2),size(mot_out.jointTrajectories{1},2)); mot_out.filename = mot_in.filename; mot_out.documentation = vertcat(mot_in.documentation,{['The original file has been resampled to new frame rate ' num2str(target_frame_rate) ' Hz!']}); mot_out.angleUnit = mot_in.angleUnit; mot_out.boundingBox = mot_in.boundingBox;
github
sheldona/hessianIK-master
moveMotToXZ.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/moveMotToXZ.m
1,114
utf_8
d4cc909224c2c13ed48c443f6e320177
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot = moveMotToXZ(mot,p) v = p - mot.rootTranslation([1 3],1); for k=1:length(mot.jointTrajectories) mot.jointTrajectories{k}([1 3],:) = mot.jointTrajectories{k}([1 3],:) + repmat(v,1,mot.nframes); end mot.rootTranslation([1 3],:) = mot.rootTranslation([1 3],:) + repmat(v,1,mot.nframes);
github
sheldona/hessianIK-master
readMocapSmart.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/readMocapSmart.m
1,980
utf_8
d9928728ce340b27d7f5237f7fa8ff8a
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [ skel, mot ] = readMocapSmart( fullFilename, noCaching, noScaling ) % [ skel, mot ] = readMocapSmart( fullFilename, noCaching, noScaling ) % % % % readMocapSmart does not require specification of ASF-file % and automatically performs scaling (unit conversion) % % noCaching: Don't read *.MAT-file % noScaling: Don't scale ASF/AMC files by 2.54 (default: false) % % % Units are may be in centimeter or in inches % (ASF/AMC units of HDM05 files are in inches) % (C3D units of HDM05 files are in centimeters) % % noScaling = false -> scaling by factor 1/2.54 to % convert inches -> centimeters (only for ASF/AMC) % if nargin < 2 noCaching = false; end if nargin < 3 noScaling = false; end info = filename2info(fullFilename); if strcmpi(info.filetype, 'C3D') [skel, mot] = readMocap(fullFilename, [], noCaching ); elseif strcmpi(info.filetype, 'ASF/AMC') skelFile = fullfile(info.amcpath, info.asfname); [skel, mot] = readMocap(skelFile, fullFilename, [], true, true, true, noCaching); if ~noScaling [skel, mot] = scaleSkelMot(skel, mot, 1/2.54); % our ASF end end