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
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK_mod.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/GJK_Distance/GJK DISTANCE/GJK_mod.m
6,720
utf_8
5b06ac643912454d6a7709cccdb88a00
function [a,b,c,d,flag] = GJK_mod(shape1,shape2,iterations) % GJK Gilbert-Johnson-Keerthi Collision detection implementation. % Returns whether two convex shapes are are penetrating or not % (true/false). Only works for CONVEX shapes. % % Inputs: % shape1: % must have fields for XData,YData,ZData, which are the x,y,z % coordinates of the vertices. Can be the same as what comes out of a % PATCH object. It isn't required that the points form faces like patch % data. This algorithm will assume the convex hull of the x,y,z points % given. % % shape2: % Other shape to test collision against. Same info as shape1. % % iterations: % The algorithm tries to construct a tetrahedron encompassing % the origin. This proves the objects have collided. If we fail within a % certain number of iterations, we give up and say the objects are not % penetrating. Low iterations means a higher chance of false-NEGATIVES % but faster computation. As the objects penetrate more, it takes fewer % iterations anyway, so low iterations is not a huge disadvantage. % % Outputs: % flag: % true - objects collided % false - objects not collided % [a,b,c,d] - members of the simplex % % % This video helped me a lot when making this: https://mollyrocket.com/849 % Not my video, but very useful. % % Matthew Sheen, 2016 % % Modified: % Philippe Lebel, 2016: % Fixed a bug where aligned vertices would trigger the collision flag % while there was no collision ( line 191 ) %Point 1 and 2 selection (line segment) v = [0.8 0.5 1]; [a,b] = pickLine(v,shape2,shape1); %Point 3 selection (triangle) [a,b,c,flag] = pickTriangle(a,b,shape2,shape1,iterations); %Point 4 selection (tetrahedron) % if flag == 1 %Only bother if we could find a viable triangle. [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape2,shape1,iterations); % end end function [a,b] = pickLine(v,shape1,shape2) %Construct the first line of the simplex b = support(shape2,shape1,v); dir_ori=-b; a = support(shape2,shape1,dir_ori); end function [a,b,c,flag] = pickTriangle(a,b,shape1,shape2,IterationAllowed) flag = 0; %So far, we don't have a successful triangle. %First try: ab = b-a; ao = -a; v = cross(cross(ab,ao),ab); % v is perpendicular to ab pointing in the general direction of the origin. c = b; b = a; a = support(shape2,shape1,v); for i = 1:IterationAllowed %iterations to see if we can draw a good triangle. %Time to check if we got it: ab = b-a; ao = -a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); %Perpendicular to AB going away from triangle abp = cross(ab,abc); %Perpendicular to AC going away from triangle acp = cross(abc,ac); %First, make sure our triangle "contains" the origin in a 2d projection %sense. %Is origin above (outside) AB? if dot(abp,ao) > 0 c = b; %Throw away the furthest point and grab a new one in the right direction b = a; v = abp; %cross(cross(ab,ao),ab); %Is origin above (outside) AC? elseif dot(acp, ao) > 0 b = a; v = acp; %cross(cross(ac,ao),ac); else % flag = 1; % break; %We got a good one. end a = support(shape2,shape1,v); end end function [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape1,shape2,IterationAllowed) %Now, if we're here, we have a successful 2D simplex, and we need to check %if the origin is inside a successful 3D simplex. %So, is the origin above or below the triangle? flag = 0; ab = b-a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); ao = -a; if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = c; c = b; b = a; a=a_new; end else %below d = b; b = a; v = -abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = b; b = a; a=a_new; end end for i = 1:IterationAllowed %Allowing 10 tries to make a good tetrahedron. %Check the tetrahedron: ab = b-a; ao = -a; ac = c-a; ad = d-a; %We KNOW that the origin is not under the base of the tetrahedron based on %the way we picked a. So we need to check faces ABC, ABD, and ACD. %Normal to face of triangle abc = cross(ab,ac); if dot(abc, ao) > 0 %Above triangle ABC %No need to change anything, we'll just iterate again with this face as %default. else acd = cross(ac,ad);%Normal to face of triangle if dot(acd, ao) > 0 %Above triangle ACD %Make this the new base triangle. b = c; c = d; ab = ac; ac = ad; abc = acd; elseif dot(acd, ao) < 0 adb = cross(ad,ab);%Normal to face of triangle if dot(adb, ao) > 0 %Above triangle ADB %Make this the new base triangle. c = b; b = d; ac = ab; ab = ad; abc = adb; else flag = 1; break; %It's inside the tetrahedron. end else %The nearest point is one of the three points contained in the simplex ; end end %try again: if dot(abc, ao) > 0 %Above v = abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = c; c = b; b = a; a=a_new; end else %below v = -abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = b; b = a; a=a_new; end end end end function point = getFarthestInDir(shape, v) %Find the furthest point in a given direction for a shape XData = shape.Vertices(:,1); % Making it more compatible with previous MATLAB releases. YData = shape.Vertices(:,2); ZData = shape.Vertices(:,3); dotted = XData*v(1) + YData*v(2) + ZData*v(3); [maxInCol,rowIdxSet] = max(dotted); [maxInRow,colIdx] = max(maxInCol); rowIdx = rowIdxSet(colIdx); point = [XData(rowIdx,colIdx), YData(rowIdx,colIdx), ZData(rowIdx,colIdx)]'; end function point = support(shape1,shape2,v) %Support function to get the Minkowski difference. point1 = getFarthestInDir(shape1, v); point2 = getFarthestInDir(shape2, -v); point = point1 - point2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK_dist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/GJK_Distance/GJK DISTANCE/GJK_dist.m
10,028
utf_8
536b90ca4f66c97f6dad1e522b854947
%This function is based on the book Real-Time Collision Detection % (http://realtimecollisiondetection.net/) % %It computes the distance, the points of closest proximity points and also %returns the points last contained in the simplex. %[dist,pts,G,H] = GJK_dist_7_point_poly( shape1, shape2 ) % % INPUTS: % % shape1: a patch object representing the first convex solid % shape2: a patch object representing the second convex solid % % OUTPUTS: % % dist: an absolute float number representing the minimum distance between % the shapes. % pts: The points of the minkowsky diference where the alogrithm % stoped. % G: The point on shape1 closest to shape2 % H: The point on shape2 closest to shape1 % updated 05/01/17. Thanks to Amin Ramezanifar for pointing out an error. function [dist,pts,G,H] = GJK_dist( shape1, shape2 ) %pick a random direction d=[1 1 1]; %pick a point [a, point1_a, point2_a]=support_2(shape1,shape2,d); %pick a second point to creat a line [b, point1_b, point2_b]=support_2(shape1,shape2,-d); %pick a third point to make a tirangle ab=b-a; ao=-a; %perpendicular direction d=cross(cross(ab,ao),ab); %pick a third point [c, point1_c, point2_c]=support_2(shape1,shape2,d); %the simplex is now complete pts=[a b c]; pts_1_2=[point1_a point1_b point1_c;point2_a point2_b point2_c]; itt=0; pts_old=pts; norm_old=norm(pts_old); d_old=d; dist_old=1000; dist=1000; flag=0; PP0 = 'V'; %This loop is there for the very rare case where the simplex would contain %duplicate points. while true if isequal(c,b) || isequal(c,a) [c, point1_c, point2_c]=support_2(shape1,shape2,-d); else pts=[a b c]; pts_1_2=[point1_a point1_b point1_c;point2_a point2_b point2_c]; break end end while true %we compute the norm of vector going from the origin to each member %of the simplex Norm_pts = (sqrt(sum(abs(pts').^2,2))); %Computing and removing the farthest point of the simplex from the origin [max_norm,index]=max(Norm_pts); %new search direction d=cross(pts(:,2)-pts(:,1),pts(:,3)-pts(:,1)); origin_projected=(pts(:,1)'*d)*d; if d'*origin_projected>0 d=-d; end d=d/norm(d); %Pciking a new point to add to the simplex. [c, point1_c, point2_c]=support_2(shape1,shape2,d); %we project the origin on the simplex's plane. origin_projected=(pts(:,1)'*d)*d; % We verify if the point is allready contained in the simplex. % The (itt>5 && flag == 5) condition to enter this loop is one of the main % problems of the algorithm. Sometime, when using only the normal to % the triangle, the solution does not converge to the absolute minimum % distance. This other way of computing the new direction allows a % higher rate of succesful convergeance. If one would want to upgrade the % algorithm he would certainly need to work arround here. if any(abs(Norm_pts-norm(c))<0.000001) || (itt>5 && flag == 5) % computing the distance of each traingle lines from the origin d1 = distLinSeg(pts(:,1)',pts(:,2)',origin_projected',origin_projected'); d2 = distLinSeg(pts(:,1)',pts(:,3)',origin_projected',origin_projected'); d3 = distLinSeg(pts(:,2)',pts(:,3)',origin_projected',origin_projected'); % d1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); % d2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); % d3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); dist_seg_min=min(abs([d1 d2 d3])); %we want to pick the two points creating the line closest to the %origin. %We also need to deal with the case where the origin is closest to %a point, resulting in two distances being equal. if dist_seg_min<dist while true if d1==dist_seg_min %pick a third point to make a tirangle ab=pts(:,2)-pts(:,1); ao=-pts(:,1); %perpendicular direction d=cross(cross(ab,ao),ab); if d1~=d2 && d1~=d3 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=3; break else [c_1, point1_c_1, point2_c_1]=support_2(shape1,shape2,d); index_1=3; end end if d2==dist_seg_min %pick a third point to make a tirangle ab=pts(:,3)-pts(:,1); ao=-pts(:,1); %perpendicular direction d=cross(cross(ab,ao),ab); if d2~=d1 && d2~=d3 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=2; break else [c_2, point1_c_2, point2_c_2]=support_2(shape1,shape2,d); index_2=2; end end if d3==dist_seg_min %pick a third point to make a tirangle ab=pts(:,3)-pts(:,2); ao=-pts(:,2); %perpendicular direction d=cross(cross(ab,ao),ab); if d3~=d1 && d3~=d2 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=1; break else [c_3, point1_c_3, point2_c_3]=support_2(shape1,shape2,d); index_3=1; end end if d1==d2 L1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); if L1>L2 c=c_1; point1_c=point1_c_1; point2_c=point2_c_1; else c=c_2; point1_c=point1_c_2; point2_c=point2_c_2; end elseif d1==d3 L1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); if L1>L3 c=c_1; point1_c=point1_c_1; point2_c=point2_c_1; else c=c_3; point1_c=point1_c_3; point2_c=point2_c_3; end elseif d2==d3 L2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); if L2>L3 c=c_2; point1_c=point1_c_2; point2_c=point2_c_2; else c=c_3; point1_c=point1_c_3; point2_c=point2_c_3; end end break end end % if even after picking a new point with the other method, if the % simplex already has it, we assume we converged. if any(abs(Norm_pts-norm(c))<0.000001) if PP0 == 'V' % converged on first itteration, dist and PP0 must be % computed. [dist, PP0] = pointTriangleDistance(pts',[0 0 0]); end Norm_pts=0; break end end pts(:,index)=[]; pts_1_2(:,index)=[]; pts=[pts c]; pts_1_2=[pts_1_2 [point1_c;point2_c]]; [dist, PP0] = pointTriangleDistance(pts',[0 0 0]); %we need to do the following manipulation because sometimes, the %simplex will oscillate arround the closest solution, creating an %infinite loop. We need to backup the solution that resulted in the %minimal distance and use it if the loop times out (10 itteration max) if dist<dist_old pts_prox=pts; dist_prox=dist; PP0_prox=PP0; pts_1_2_prox=pts_1_2; end %The time out is set here. if itt>6 flag=5; if itt>10 && flag==5 pts=pts_prox; dist=dist_prox; PP0=PP0_prox; pts_1_2=pts_1_2_prox; break end end dist_old=dist; d_old=d; pts_old=pts; if abs(norm_old-norm(pts))<0.01 norm_old=norm(pts); end itt=itt+1; % pause(0.1) end % Calculation of the barycentric coordinates of the origin in respect to % the simplex. T = [1 4 3; 1 4 2; 3 4 2; 1 2 3]; pts_t=[pts';PP0]; % commented out by Jeremy %TR=triangulation(T,pts_t); %B=cartesianToBarycentric(TR,4,PP0); G=0; H=0; %calculation of the points G and H of proximity on,respectively, shape1 %and shape2. % commented out by Jeremy %for i=1:3 % G=G+B(i)*pts_1_2(1:3,i); % H=H+B(i)*pts_1_2(4:6,i); %end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/GJK_Distance/GJK DISTANCE/GJK.m
6,009
utf_8
30df12311f7526c9599cde4b2aaf7a3a
function [flag] = GJK(shape1,shape2,iterations) % GJK Gilbert-Johnson-Keerthi Collision detection implementation. % Returns whether two convex shapes are are penetrating or not % (true/false). Only works for CONVEX shapes. % % Inputs: % shape1: % must have fields for XData,YData,ZData, which are the x,y,z % coordinates of the vertices. Can be the same as what comes out of a % PATCH object. It isn't required that the points form faces like patch % data. This algorithm will assume the convex hull of the x,y,z points % given. % % shape2: % Other shape to test collision against. Same info as shape1. % % iterations: % The algorithm tries to construct a tetrahedron encompassing % the origin. This proves the objects have collided. If we fail within a % certain number of iterations, we give up and say the objects are not % penetrating. Low iterations means a higher chance of false-NEGATIVES % but faster computation. As the objects penetrate more, it takes fewer % iterations anyway, so low iterations is not a huge disadvantage. % % Outputs: % flag: % true - objects collided % false - objects not collided % % % This video helped me a lot when making this: https://mollyrocket.com/849 % Not my video, but very useful. % % Matthew Sheen, 2016 % %Point 1 and 2 selection (line segment) v = [0.8 0.5 1]; [a,b] = pickLine(v,shape2,shape1); %Point 3 selection (triangle) [a,b,c,flag] = pickTriangle(a,b,shape2,shape1,iterations); %Point 4 selection (tetrahedron) if flag == 1 %Only bother if we could find a viable triangle. [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape2,shape1,iterations); end end function [a,b] = pickLine(v,shape1,shape2) %Construct the first line of the simplex b = support(shape2,shape1,v); a = support(shape2,shape1,-v); end function [a,b,c,flag] = pickTriangle(a,b,shape1,shape2,IterationAllowed) flag = 0; %So far, we don't have a successful triangle. %First try: ab = b-a; ao = -a; v = cross(cross(ab,ao),ab); % v is perpendicular to ab pointing in the general direction of the origin. c = b; b = a; a = support(shape2,shape1,v); for i = 1:IterationAllowed %iterations to see if we can draw a good triangle. %Time to check if we got it: ab = b-a; ao = -a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); %Perpendicular to AB going away from triangle abp = cross(ab,abc); %Perpendicular to AC going away from triangle acp = cross(abc,ac); %First, make sure our triangle "contains" the origin in a 2d projection %sense. %Is origin above (outside) AB? if dot(abp,ao) > 0 c = b; %Throw away the furthest point and grab a new one in the right direction b = a; v = abp; %cross(cross(ab,ao),ab); %Is origin above (outside) AC? elseif dot(acp, ao) > 0 b = a; v = acp; %cross(cross(ac,ao),ac); else flag = 1; break; %We got a good one. end a = support(shape2,shape1,v); end end function [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape1,shape2,IterationAllowed) %Now, if we're here, we have a successful 2D simplex, and we need to check %if the origin is inside a successful 3D simplex. %So, is the origin above or below the triangle? flag = 0; ab = b-a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); ao = -a; if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end for i = 1:IterationAllowed %Allowing 10 tries to make a good tetrahedron. %Check the tetrahedron: ab = b-a; ao = -a; ac = c-a; ad = d-a; %We KNOW that the origin is not under the base of the tetrahedron based on %the way we picked a. So we need to check faces ABC, ABD, and ACD. %Normal to face of triangle abc = cross(ab,ac); if dot(abc, ao) > 0 %Above triangle ABC %No need to change anything, we'll just iterate again with this face as %default. else acd = cross(ac,ad);%Normal to face of triangle if dot(acd, ao) > 0 %Above triangle ACD %Make this the new base triangle. b = c; c = d; ab = ac; ac = ad; abc = acd; elseif dot(acd, ao) < 0 adb = cross(ad,ab);%Normal to face of triangle if dot(adb, ao) > 0 %Above triangle ADB %Make this the new base triangle. c = b; b = d; ac = ab; ab = ad; abc = adb; else flag = 1; break; %It's inside the tetrahedron. end else %the origin is on the same plane as the triangle ; end end %try again: if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end end end function point = getFarthestInDir(shape, v) %Find the furthest point in a given direction for a shape XData = shape.Vertices(:,1); % Making it more compatible with previous MATLAB releases. YData = shape.Vertices(:,2); ZData = shape.Vertices(:,3); dotted = XData*v(1) + YData*v(2) + ZData*v(3); [maxInCol,rowIdxSet] = max(dotted); [maxInRow,colIdx] = max(maxInCol); rowIdx = rowIdxSet(colIdx); point = [XData(rowIdx,colIdx), YData(rowIdx,colIdx), ZData(rowIdx,colIdx)]'; end function point = support(shape1,shape2,v) %Support function to get the Minkowski difference. point1 = getFarthestInDir(shape1, v); point2 = getFarthestInDir(shape2, -v); point = point1 - point2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
distLinSeg.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/GJK_Distance/GJK DISTANCE/distLinSeg.m
2,407
utf_8
f4674ddd3116bd073e046a82cc0b8e1e
% Function for fast computation of the shortest distance between two line segments % % Algorithm implemented: % Vladimir J. LUMELSKY, % ``ON FAST COMPUTATION OF DISTANCE BETWEEN LINE SEGMENTS'', % Information Processing Letters 21 (1985) 55-61 % % % Input: ([start point of line1], [end point of line1], [start point of % line2], [end point of line2]) % % Output: dist - shortest distance between the line segments (in N dimensions) % points (optional) - shortest points on the line segments % % Example: % >> [dist,points] = distLinSeg([0 0], [1 1], [1 0], [2 0]) % >> dist = 0.7071 % >> points = [0.5 0.5; 1 0] % % % 1.2.2015 - created: Ondrej Sluciak ([email protected]) % function [dist,varargout] = distLinSeg(point1s,point1e,point2s,point2e) d1 = point1e - point1s; d2 = point2e - point2s; d12 = point2s - point1s; D1 = d1*d1'; %D1 = sum(d1.^2); D2 = d2*d2'; %D2 = sum(d2.^2); S1 = d1*d12'; % S1 = sum(d1.*d12); S2 = d2*d12'; % S2 = sum(d2.*d12); R = d1*d2'; % R = sum(d1.*d2); den = D1*D2-R^2; %denominator if (D1 == 0 || D2 == 0) % if one of the segments is a point if (D1 ~= 0) % if line1 is a segment and line2 is a point u = 0; t = S1/D1; t = fixbound(t); elseif (D2 ~= 0) % if line2 is a segment and line 1 is a point t = 0; u = -S2/D2; u = fixbound(u); else % both segments are points t = 0; u = 0; end elseif (den == 0) % if lines are parallel t = 0; u = -S2/D2; uf = fixbound(u); if (uf~= u) t = (uf*R+S1)/D1; t = fixbound(t); u = uf; end else % general case t = (S1*D2-S2*R)/den; t = fixbound(t); u = (t*R-S2)/D2; uf = fixbound(u); if (uf ~= u) t = (uf*R+S1)/D1; t = fixbound(t); u = uf; end end % Compute distance given parameters 't' and 'u' dist = norm(d1*t-d2*u-d12); %dist = sqrt(sum((d1*t-d2*u-d12).^2)); if (nargout > 1) varargout = {[point1s + d1*t;point2s+d2*u]}; end end function num = fixbound(num) % if num is out of (0,1) round to {0,1} if (num < 0) num = 0; elseif (num > 1) num = 1; end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
MakeObj.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/plotting/MakeObj.m
683
utf_8
a81a3fae729eca365c5bffe0df3d8124
% returns convex hull from point cloud function obj = MakeObj(points, color) %figure() % create face representation and create convex hull F = convhull(points(1,:), points(2,:)); fill(points(1,F),points(2,F),color); %{ S.Vertices = transpose(points(1:2,:)); S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; if(strcmp(color,'red')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','red'); elseif(strcmp(color,'green')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','green'); else obj = patch(S); end %} end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSim.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/plotting/PlotSetBasedSim.m
1,265
utf_8
b7d3080567e0a89bd04feaa865dafaf8
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % create objects/convex hulls for each set at each time step for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i);agentPos(3,i)]; curSet(:,2) = [agentPos(1,i);agentPos(4,i)]; curSet(:,3) = [agentPos(2,i);agentPos(3,i)]; curSet(:,4) = [agentPos(2,i);agentPos(4,i)]; % make the object MakeObj(curSet, 'g'); % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % make the object MakeObj(curObstSet, 'r'); end scatter(target(1), target(2), '*') xlabel('x axis') ylabel('y axis') axis([-1 1 -1 1]) grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistance.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/plotting/PlotSimDistance.m
2,186
utf_8
03c83a059200376eaa6a2ef93b87179e
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation [mO,nO] = size(obst); ObstDist = zeros(nA,1); % create objects/convex hulls for each set at each time step for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i);agentPos(3,i)]; curSet(:,2) = [agentPos(1,i);agentPos(4,i)]; curSet(:,3) = [agentPos(2,i);agentPos(3,i)]; curSet(:,4) = [agentPos(2,i);agentPos(4,i)]; % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % min distance to projectile polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); ObstDist(i) = PolytopeMinDist(curSet,curObstSet,polyOptions); end plot(0:1:(nA-1),transpose(ObstDist)); plot(0:1:(nA-1),threshold*ones(1,(nA))); title('Minimum distance between vehicle polytope and obstacle polytope'); xlabel('time'); ylabel('distance'); axis([0 nA-1 0 2]); figure() hold on; dist = zeros(nA,1); for i = 1:nA dist(i) = dist(i) + norm([agentPos(1,i);agentPos(3,i)]-target)^2 ... + norm([agentPos(1,i);agentPos(4,i)]-target)^2 ... + norm([agentPos(2,i);agentPos(3,i)]-target)^2 ... + norm([agentPos(2,i);agentPos(4,i)]-target)^2; end plot(0:1:(nA-1),dist); title('Minimum distance between vehicle polytope and target polytope'); xlabel('time'); ylabel('distance'); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistanceSuccessive.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/plotting/PlotSimDistanceSuccessive.m
2,189
utf_8
1966c59ec2bb87432a05d3b9d69754f9
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance(agentPos, obst, threshold, target) figure(1) hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation % pO - obstacle number [mO,nO,pO] = size(obst); ObstDist = zeros(nA,pO); for i = 1:pO % create objects/convex hulls for each set at each time step for j = 1:nA % format points for MakeObj function curSet = zeros(3,4); curSet(:,1) = [agentPos(1,j);agentPos(3,j);0]; curSet(:,2) = [agentPos(1,j);agentPos(4,j);0]; curSet(:,3) = [agentPos(2,j);agentPos(3,j);0]; curSet(:,4) = [agentPos(2,j);agentPos(4,j);0]; % min distance to projectile temp_xObst = [obst(:,j,i),obst(:,j,i)]; % polytope dist function has trouble with only one point polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); ObstDist(j,i) = PolytopeMinDist(curSet,temp_xObst,polyOptions); end plot(0:1:(nA-1),transpose(ObstDist(:,i))); plot(0:1:(nA-1),threshold*ones(1,(nA))); end title('Minimum distance between vehicle polytope and obstacle polytope'); xlabel('time'); ylabel('distance'); axis([0 nA-1 0 2]); drawnow; figure(2) hold on; dist = zeros(nA,1); for i = 1:nA dist(i) = dist(i) + norm([agentPos(1,i);agentPos(3,i);0]-target)^2 ... + norm([agentPos(1,i);agentPos(4,i);0]-target)^2 ... + norm([agentPos(2,i);agentPos(3,i);0]-target)^2 ... + norm([agentPos(2,i);agentPos(4,i);0]-target)^2; end plot(0:1:(nA-1),dist); title('Minimum distance between vehicle polytope and target polytope'); xlabel('time'); ylabel('distance'); drawnow; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotOptimalPredicted.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/plotting/PlotOptimalPredicted.m
1,217
utf_8
bd1dc3defa90d676db8e6faddd73e8b5
function PlotOptimalPredicted(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % create objects/convex hulls for each set at each time step for i = 1:nA % format points for MakeObj function curVehicleSet = zeros(2,4); curVehicleSet(:,1) = [agentPos(1,i);agentPos(3,i)]; curVehicleSet(:,2) = [agentPos(1,i);agentPos(4,i)]; curVehicleSet(:,3) = [agentPos(2,i);agentPos(3,i)]; curVehicleSet(:,4) = [agentPos(2,i);agentPos(4,i)]; % make the object MakeObj(curVehicleSet, 'g'); % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % make the object MakeObj(curObstSet, 'r'); end scatter(target(1), target(2), '*') xlabel('x axis') ylabel('y axis') zlabel('z axis') grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
Cost.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/system/Cost.m
1,037
utf_8
7d52b29ad7c2ba935094018617a299dc
% c = Cost(x0_set, u, ts, target) % % custom cost function - sum of distance from each vertex to target squared function c = Cost(x0_set, u, ts, target, L, terminalWeight) % predict system state with set based dynamics x_set = Dubin(x0_set,u,ts,L); % calculate cost of prediction for set based dynamics % - iterate through each vertex at each time step and calculate the % distance between that point and the target [m,n] = size(x_set); c = 0; % stage cost for i = 1:n-1 c = c + norm([x_set(1,i);x_set(3,i)]-target)^2 ... + norm([x_set(1,i);x_set(4,i)]-target)^2 ... + norm([x_set(2,i);x_set(3,i)]-target)^2 ... + norm([x_set(2,i);x_set(4,i)]-target)^2; end % terminal cost c = c + terminalWeight*norm([x_set(1,n);x_set(3,n)]-target)^2 ... + terminalWeight*norm([x_set(1,n);x_set(4,n)]-target)^2 ... + terminalWeight*norm([x_set(2,n);x_set(3,n)]-target)^2 ... + terminalWeight*norm([x_set(2,n);x_set(4,n)]-target)^2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
FindOptimalInput.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/system/FindOptimalInput.m
1,227
utf_8
3b444b8c7a413d695610a1b942349128
% function u0 = FindOptimalInput(x0, N, ts, target) % % uses fmincon to minimize cost function given system dynamics and % nonlinear constraints, returns optimal input sequence function uopt = FindOptimalInput(x0_set, N, ts, target, xObst, threshold, L, speedBound, steeringBound, terminalWeight, EXP) A = []; b = []; Aeq = []; beq = []; % set lower and upper bounds on inputs to dubins model lb(1,:) = zeros(1,N); % lower bound is zero (speed) lb(2,:) = -steeringBound*ones(1,N); ub(1,:) = speedBound*ones(1,N); ub(2,:) = steeringBound*ones(1,N); % initial input guess uInit = zeros(2,N); uInit(1,:) = (0)*ones(1,N); % solve optimization options = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set','MaxFunEvals',1000,'ConstraintTolerance',1e-04); polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); [uopt ,fval,exitflag,output] = fmincon(@(u) Cost(x0_set,u,ts,target,L,terminalWeight),uInit,A,b,Aeq,beq,lb,ub, @(u) ObstConstraint(x0_set,u,ts,xObst,threshold,L,polyOptions,EXP),options); output % return optimal input sequence end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
ObstConstraint.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/system/ObstConstraint.m
1,535
utf_8
2006293a6230997ad0315ff18f16d2a3
% [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold) % % defines the non linear constraint - agent polytope to maintain % a distance from the obstacle position above threshold function [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold,L,options,EXP) % predict agent with set based dynamics % coords X time X set points x_set = Dubin(x0_set, u, ts,L); % find distance between agent polytope and obstacle [mA,nA] = size(x_set); [mO,nO,pO] = size(xObst); ObstDist = zeros(1,pO*nA); obstDistCount = 1; for i = 1:nA % time for j = 1:pO % number of obstacles % format the agents set for polytope minimization for time step i xPolytope = zeros(2,4); xPolytope(:,:) = [x_set(1,i), x_set(1,i), x_set(2,i), x_set(2,i); x_set(3,i), x_set(4,i), x_set(3,i), x_set(4,i)]; oPolytope = zeros(2,4); oPolytope(:,:) = [xObst(1,i), xObst(1,i), xObst(2,i), xObst(2,i); xObst(3,i), xObst(4,i), xObst(3,i), xObst(4,i)]; if(EXP) ObstDist(obstDistCount) = PolytopeApproxDist(xPolytope,oPolytope); else ObstDist(obstDistCount) = PolytopeMinDist(xPolytope,oPolytope,options); end obstDistCount = obstDistCount+1; end end % calculate constraints c = -ObstDist+threshold; ceq = []; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SingleIntegrator.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/system/SingleIntegrator.m
412
utf_8
103d816561c56f118cee17686dc4c4c4
% x = SingleIntegrator(x0_set, u, ts) % % set based dynamics of single integrator function x = SingleIntegrator(x0_set, u, ts) [mP,nP] = size(x0_set); [mH,nH] = size(u); % coords X time X set points x = zeros(3,nH+1,nP); x(:,1,:) = x0_set; % apply integrator dynamics for j = 1:nP for i = 1:nH x(:,i+1,j) = x(:,i,j) + ts*u(:,i); end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SimulationProjectilePredict.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/projectile/SimulationProjectilePredict.m
764
utf_8
8ea559140e8b2248afec5e16b1990cb5
% [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % % calls on simulink to predict projectile state given initial conditions function [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % set up simulink set_param('projectile/rx','Value',num2str(p_0(1))); set_param('projectile/ry','Value',num2str(p_0(2))); set_param('projectile/rz','Value',num2str(p_0(3))); set_param('projectile/vx','Value',num2str(p_0(4))); set_param('projectile/vy','Value',num2str(p_0(5))); set_param('projectile/vz','Value',num2str(p_0(6))); set_param('projectile', 'StopTime', num2str(simTime)); % run simulation sim('projectile'); trajectory = projectilePos; velocity = projectileVel; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
CreateSphere.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/polytope/CreateSphere.m
913
utf_8
e7fc2c7730cbb8e66f70c29e702d9c20
% creates a point cloud in a sphere around the center function points = CreateSphere(center, r, thetadis, phidis) % angle discretization thetas = linspace(0,2*pi,thetadis); phis = linspace(0,pi,phidis); % point calculation points = []; x = []; y = []; z = []; for i = 1:length(phis) for j = 1:length(thetas) % removes duplicate point at theta = 2*pi if(thetas(j) == 2*pi) break end x = (r * sin(phis(i)) * cos(thetas(j))) + center(1); y = (r * sin(phis(i)) * sin(thetas(j))) + center(2); z = (r * cos(phis(i))) + center(3); nextPoint = [x;y;z]; points = [points, nextPoint]; % removes duplicate points at the top and bottom of sphere if(phis(i) == 0 || phis(i) == pi) break end end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeMinDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/polytope/PolytopeMinDist.m
1,162
utf_8
e97b9cd17ce23a47a127987797ca0206
% minDist = PolytopeMinDist(X1,X2) % % finds the minimum distance between two polytopes X1 and X2 function minDist = PolytopeMinDist(X1,X2,options) % declare constraints for fmincon lb = []; ub = []; % get sizes of vertices for polytopes [m1,n1] = size(X1); [m2,n2] = size(X2); if(m1 ~= m2) error('USER ERROR: Dimensions mistmatch'); end n = n1+n2; A = [eye(n); -eye(n)]; b = [ones(n,1); zeros(n,1)]; Aeq = [ones(1,n1) zeros(1,n2); zeros(1,n1) ones(1,n2)]; beq = [1;1]; nonlcon = []; % create lambda vectors x0 = zeros(n,1); x0(1) = 1; x0(n1+1) = 1; % declare function to be minimized %fun = @(lambda)(norm((X1 * lambda(1:n1))-(X2 * lambda(n1+1:n)))^2); % evaluate fmincon %x = fmincon(@(lambda) PolytopeDist(X1,X2,lambda,n1,n2,n),x0,A,b,Aeq,beq,lb,ub,nonlcon,options); [x,fval,exitflag,output] = fmincon(@(lambda) PolytopeDist(X1,X2,lambda,n1,n2,n),x0,A,b,Aeq,beq,lb,ub,nonlcon,options); %output % return min distance minDist = sqrt(PolytopeDist(X1,X2,x,n1,n2,n)); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeApproxDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/polytope/PolytopeApproxDist.m
474
utf_8
7306751fed5e8ef4b13d8c2a2c0d62e5
function dist = PolytopeApproxDist(X1,X2) [m1,n1] = size(X1); [m2,n2] = size(X2); c1 = transpose(mean(transpose(X1))); c2 = transpose(mean(transpose(X2))); dist1 = zeros(n1,1); for i = 1:n1 dist1(i) = norm(X1(:,i)-c1); end dist2 = zeros(n2,1); for i = 1:n2 dist2(i) = norm(X2(:,i)-c2); end cDist = norm(c1-c2); d1 = max(dist1); d2 = max(dist2); dist = cDist-d1-d2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/Exp_Dubins_SBONL/polytope/PolytopeDist.m
668
utf_8
34f5332d650d2fb60f349903cb7edf17
function [f,g] = PolytopeDist(X1,X2,lambda,n1,n2,n) f = norm((X1 * lambda(1:n1))-(X2 * lambda(n1+1:n)))^2; %{ g = zeros(n,1); for i = 1:n1 g(i) = 2*((X1(1,:)*lambda(1:n1))-(X2(1,:)*lambda(n1+1:n)))*X1(1,i) ... + 2*((X1(2,:)*lambda(1:n1))-(X2(2,:)*lambda(n1+1:n)))*X1(2,i) ... + 2*((X1(3,:)*lambda(1:n1))-(X2(3,:)*lambda(n1+1:n)))*X1(3,i); end for i = 1:n2 g(i) = 2*((X1(1,:)*lambda(1:n1))-(X2(1,:)*lambda(n1+1:n)))*(-X2(1,i)) ... + 2*((X1(2,:)*lambda(1:n1))-(X2(2,:)*lambda(n1+1:n)))*(-X2(2,i)) ... + 2*((X1(3,:)*lambda(1:n1))-(X2(3,:)*lambda(n1+1:n)))*(-X2(3,i)); end %} end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/GJK.m
5,909
utf_8
acc17476d868c4bb652640495a721180
function flag = GJK(shape1,shape2,iterations) % GJK Gilbert-Johnson-Keerthi Collision detection implementation. % Returns whether two convex shapes are are penetrating or not % (true/false). Only works for CONVEX shapes. % % Inputs: % shape1: % must have fields for XData,YData,ZData, which are the x,y,z % coordinates of the vertices. Can be the same as what comes out of a % PATCH object. It isn't required that the points form faces like patch % data. This algorithm will assume the convex hull of the x,y,z points % given. % % shape2: % Other shape to test collision against. Same info as shape1. % % iterations: % The algorithm tries to construct a tetrahedron encompassing % the origin. This proves the objects have collided. If we fail within a % certain number of iterations, we give up and say the objects are not % penetrating. Low iterations means a higher chance of false-NEGATIVES % but faster computation. As the objects penetrate more, it takes fewer % iterations anyway, so low iterations is not a huge disadvantage. % % Outputs: % flag: % true - objects collided % false - objects not collided % % % This video helped me a lot when making this: https://mollyrocket.com/849 % Not my video, but very useful. % % Matthew Sheen, 2016 % %Point 1 and 2 selection (line segment) v = [0.8 0.5 1]; [a,b] = pickLine(v,shape2,shape1); %Point 3 selection (triangle) [a,b,c,flag] = pickTriangle(a,b,shape2,shape1,iterations); %Point 4 selection (tetrahedron) if flag == 1 %Only bother if we could find a viable triangle. [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape2,shape1,iterations); end end function [a,b] = pickLine(v,shape1,shape2) %Construct the first line of the simplex b = support(shape2,shape1,v); a = support(shape2,shape1,-v); end function [a,b,c,flag] = pickTriangle(a,b,shape1,shape2,IterationAllowed) flag = 0; %So far, we don't have a successful triangle. %First try: ab = b-a; ao = -a; v = cross(cross(ab,ao),ab); % v is perpendicular to ab pointing in the general direction of the origin. c = b; b = a; a = support(shape2,shape1,v); for i = 1:IterationAllowed %iterations to see if we can draw a good triangle. %Time to check if we got it: ab = b-a; ao = -a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); %Perpendicular to AB going away from triangle abp = cross(ab,abc); %Perpendicular to AC going away from triangle acp = cross(abc,ac); %First, make sure our triangle "contains" the origin in a 2d projection %sense. %Is origin above (outside) AB? if dot(abp,ao) > 0 c = b; %Throw away the furthest point and grab a new one in the right direction b = a; v = abp; %cross(cross(ab,ao),ab); %Is origin above (outside) AC? elseif dot(acp, ao) > 0 b = a; v = acp; %cross(cross(ac,ao),ac); else flag = 1; break; %We got a good one. end a = support(shape2,shape1,v); end end function [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape1,shape2,IterationAllowed) %Now, if we're here, we have a successful 2D simplex, and we need to check %if the origin is inside a successful 3D simplex. %So, is the origin above or below the triangle? flag = 0; ab = b-a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); ao = -a; if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end for i = 1:IterationAllowed %Allowing 10 tries to make a good tetrahedron. %Check the tetrahedron: ab = b-a; ao = -a; ac = c-a; ad = d-a; %We KNOW that the origin is not under the base of the tetrahedron based on %the way we picked a. So we need to check faces ABC, ABD, and ACD. %Normal to face of triangle abc = cross(ab,ac); if dot(abc, ao) > 0 %Above triangle ABC %No need to change anything, we'll just iterate again with this face as %default. else acd = cross(ac,ad);%Normal to face of triangle if dot(acd, ao) > 0 %Above triangle ACD %Make this the new base triangle. b = c; c = d; ab = ac; ac = ad; abc = acd; else adb = cross(ad,ab);%Normal to face of triangle if dot(adb, ao) > 0 %Above triangle ADB %Make this the new base triangle. c = b; b = d; ac = ab; ab = ad; abc = adb; else flag = 1; break; %It's inside the tetrahedron. end end end %try again: if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end end end function point = getFarthestInDir(shape, v) %Find the furthest point in a given direction for a shape XData = get(shape,'XData'); % Making it more compatible with previous MATLAB releases. YData = get(shape,'YData'); ZData = get(shape,'ZData'); dotted = XData*v(1) + YData*v(2) + ZData*v(3); [maxInCol,rowIdxSet] = max(dotted); [maxInRow,colIdx] = max(maxInCol); rowIdx = rowIdxSet(colIdx); point = [XData(rowIdx,colIdx), YData(rowIdx,colIdx), ZData(rowIdx,colIdx)]; end function point = support(shape1,shape2,v) %Support function to get the Minkowski difference. point1 = getFarthestInDir(shape1, v); point2 = getFarthestInDir(shape2, -v); point = point1 - point2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
convexhull.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/convexhull.m
1,701
utf_8
cb09453005f6a6fce441276524c4e5c7
%How many iterations to allow for collision detection. iterationsAllowed = 6; % Make a figure figure(1) hold on % constants for set making cntr_1 = [0.0, 0.0, 0.0]; cntr_2 = [1.0, 0.0, 0.0]; r_1 = 0.5; r_2 = 0.2; tdis = 11; pdis = 6; % create point cloud sphere_1 = CreateSphere(cntr_1, r_1, tdis, pdis); sphere_2 = CreateSphere(cntr_2, r_2, tdis, pdis); % make individual convex hulls S1Obj = makeObj(sphere_1); S2Obj = makeObj(sphere_2); % Make tube figure(2) % create points cloud sphere_3 = [sphere_1; sphere_2]; % make combined convex hull S3Obj = makeObj(sphere_3); % check for collision flag = GJK(S1Obj, S2Obj, iterationsAllowed) % returns convex hull from point cloud function obj = makeObj(points) % create face representation and create convex hull F = convhull(points(:,1), points(:,2), points(:,3)); S.Vertices = points; S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; obj = patch(S); end % creates a point cloud in a sphere around the center function points = CreateSphere(center, r, thetadis, phidis) % angle discretization thetas = linspace(0,2*pi,thetadis); phis = linspace(0,pi,phidis); % point calculation points = []; x = []; y = []; z = []; for i = 1:length(phis) for j = 1:length(thetas) x = (r * sin(phis(i)) * cos(thetas(j))) + center(1); y = (r * sin(phis(i)) * sin(thetas(j))) + center(2); z = (r * cos(phis(i))) + center(3); points = [points; x, y, z]; % removes duplicate points at the top and bottom of sphere if(phis(i) == 0 || phis(i) == pi) break end end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
CreateSphere.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/CreateSphere.m
866
utf_8
3ea485e3c5956a7fef00a0fe4c32bddb
% creates a point cloud in a sphere around the center function points = CreateSphere(center, r, thetadis, phidis) % angle discretization thetas = linspace(0,2*pi,thetadis); phis = linspace(0,pi,phidis); % point calculation points = []; x = []; y = []; z = []; for i = 1:length(phis) for j = 1:length(thetas) % removes duplicate point at theta = 2*pi if(thetas(j) == 2*pi) break end x = (r * sin(phis(i)) * cos(thetas(j))) + center(1); y = (r * sin(phis(i)) * sin(thetas(j))) + center(2); z = (r * cos(phis(i))) + center(3); points = [points; x, y, z]; % removes duplicate points at the top and bottom of sphere if(phis(i) == 0 || phis(i) == pi) break end end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SBPC.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/SBPC.m
5,590
utf_8
bf2e9d6733935b85f70c82b3de97fe38
% prediction algorithm % state - [x, y, z, px, py, pz, pxdot, pydot, pzdot] function input = SBPC(state,target,sigma,QR,PR,TDIS,PDIS,N,K,TIMESTEP,VELOCITY) % number of iterations to allow for collision detection. iterationsAllowed = 6; % target object targetSet = CreateSphere(target, 0.001, 5, 5); targetObj = MakeObj(targetSet, 'none'); % get possible velocities S = length(VELOCITY); %% projectile set based prediction % get initial coordinates of projectile projcntr = state(4:6); velcntr = state(7:9); % create point cloud from initial condition s_0 = CreateSphere(projcntr, PR, TDIS, PDIS); % position v_0 = CreateSphere(velcntr, PR, TDIS, PDIS); % velocity % middle point with simulink simLength = double(N*TIMESTEP); projtraj = ProjectilePredict(state(4:9), simLength); % set points [m,n] = size(s_0); for i = 1:m % create initial condition for point in set setState = [s_0(i,:), v_0(i,:)]; % predict trajectory projtraj(:,:,i+1) = ProjectilePredict(setState, simLength); end %% quadrotor set based prediction % get initial coordinates of quad quadcntr = state(1:3); % create point cloud from initial condition s_1 = CreateSphere(quadcntr, QR, TDIS, PDIS); [m,n] = size(s_1); % N+1 because of initial condition % K-1 because 0 and 2pi given equivalent trajectories %quadtraj = ones(N+1,3,S,K-1); theta = linspace(0, 2*pi, K); velPerm = permn(VELOCITY,N); angPerm = permn(theta(1:end-1),N); [vm, vn] = size(velPerm); [am, an] = size(angPerm); quadtraj = zeros(N,3,m+1,N*S); trajCount = 1; % iterate though each set of speeds and each set of angles for i = 1:vm for j = 1:am for p = 0:m % initialize coordinate % location of quad or one of the points in set X_0 if(p == 0) lastX = state(1); lastY = state(2); lastZ = state(3); else lastX = s_1(p,1); lastY = s_1(p,2); lastZ = s_1(p,3); end curTraj = zeros(N,3); for k = 1:N curTraj(k,:) = [lastX,lastY,lastZ]; % propagate the quad one time step with velocity and angle x = lastX + TIMESTEP * velPerm(i,k) * cos(angPerm(j,k)); y = lastY + TIMESTEP * velPerm(i,k) * sin(angPerm(j,k)); z = lastZ; lastX = x; lastY = y; lastZ = z; end % store trajectory quadtraj(:,:,trajCount,p+1) = curTraj; end % adjust trajectory count after each set X_n trajCount = trajCount+1; end end %% collision detection and trajectory optimization safeTraj = ones(S,K-1); for i = 1:N-1 % put data in right form for making convex hull for j = 1:m+1 projset1(j,:) = projtraj(i,:,j); projset2(j,:) = projtraj(i+1,:,j); end % create intersample convex hull for projectile projintersampleSet = [projset1; projset2]; projectileConvexHull(i) = MakeObj(projintersampleSet, 'red'); end % evaluate each trajectory trajCost = zeros(trajCount); % iterate through each trajectory for t = 1:trajCount-1 % run collision detection algorithm for i = 1:N-1 % put data in right form for making convex hull % all points from successive sets for j = 1:m quadset1(j,:) = quadtraj(i,:,t,j); quadset2(j,:) = quadtraj(i+1,:,t,j); end % create intersample convex hull for trajectory k for quadrotor quadIntersampleSet = [quadset1; quadset2]; quadrotorConvexHull = MakeObj(quadIntersampleSet, 'green'); %collisionFlag = GJK(projectileConvexHull(i), quadrotorConvexHull, iterationsAllowed); [dist,~,~,~]=GJK_dist(projectileConvexHull(i),quadrotorConvexHull); if(dist < sigma) fprintf('Collision in trajectory %d at speed %d at time step %d\n\r', k,VELOCITY(s),i); safeTraj(t) = 0; trajCost(t) = inf; break; else [cost,~,~,~] = GJK_dist(targetObj,quadrotorConvexHull); collisionFlag = GJK(targetObj,quadrotorConvexHull,iterationsAllowed); if(collisionFlag) cost cost = 0; error('must increase minimum cost'); end trajCost(t) = trajCost(t) + cost; end end t end %% find optimal input % find minimum cost and return first coordinate in that trajectory %[minCostList, minCostIndexList] = min(trajCost); %[minCost, minCostKIndex] = min(minCostList); %minCostSIndex = minCostIndexList(minCostKIndex); %u_opt = quadtraj(2,:,minCostSIndex,minCostKIndex,1); %input = u_opt; xlabel('x axis'); ylabel('y axis'); zlabel('z axis'); grid on %} input = 0; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
MakeObj.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/MakeObj.m
600
utf_8
53c884edac0b0ac6c6a36eef2b4b63cc
% returns convex hull from point cloud function obj = MakeObj(points, color) %figure() % create face representation and create convex hull F = convhull(points(:,1), points(:,2), points(:,3)); S.Vertices = points; S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; if(strcmp(color,'red')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','red'); elseif(strcmp(color,'green')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','green'); else obj = patch(S); end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SimulationMakeObj.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/SimulationMakeObj.m
367
utf_8
d4f1152a27a0887bcaaf5135543da40a
% returns convex hull from point cloud function obj = SimulationMakeObj(points) %figure() % create face representation and create convex hull F = convhull(points(:,1), points(:,2), points(:,3)); S.Vertices = points; S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; obj = patch(S,'visible','off'); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SimulationSBPC.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/SimulationSBPC.m
5,284
utf_8
60c22e645f032eb5bd2dfa58890c8fa7
% prediction algorithm % state - [x, y, z, px, py, pz, pxdot, pydot, pzdot] function input = SimulationSBPC(state,target,sigma,QR,PR,TDIS,PDIS,N,K,TIMESTEP,VELOCITY) % number of iterations to allow for collision detection. iterationsAllowed = 3; % target object targetSet = CreateSphere(target, 0.001, 5, 5); targetObj = MakeObj(targetSet, 'none'); % get possible velocities S = length(VELOCITY); %% projectile set based prediction % get initial coordinates of projectile projcntr = state(4:6); velcntr = state(7:9); % create point cloud from initial condition s_0 = CreateSphere(projcntr, PR, TDIS, PDIS); % position v_0 = CreateSphere(velcntr, PR, TDIS, PDIS); % velocity % middle point with simulink simLength = double(N*TIMESTEP); [projtraj, projvel] = SimulationProjectilePredict(state(4:9), simLength); % set points [m,n] = size(s_0); for i = 1:m % create initial condition for point in set setState = [s_0(i,:), v_0(i,:)]; % predict trajectory [projtraj(:,:,i+1), projvel(:,:,i+1)] = SimulationProjectilePredict(setState, simLength); end %% quadrotor set based prediction % get initial coordinates of quad quadcntr = state(1:3); % create point cloud from initial condition s_1 = CreateSphere(quadcntr, QR, TDIS, PDIS); [m,n] = size(s_1); % N+1 because of initial condition % K-1 because 0 and 2pi given equivalent trajectories quadtraj = ones(N+1,3,S,K-1); theta = linspace(0, 2*pi, K); j = linspace(0,N,N+1); for i = 1:m+1 for k = 1:K-1 % first is middle point then the set if(i == 1) % integrator dynamics x = quadcntr(1)+transpose(j)*TIMESTEP*VELOCITY*cos(theta(k)); y = quadcntr(2)+transpose(j)*TIMESTEP*VELOCITY*sin(theta(k)); z = quadcntr(3)*ones(N+1,S); quadtraj(:,1,:,k) = x; quadtraj(:,2,:,k) = y; quadtraj(:,3,:,k) = z; else % integrator dynamics x = s_1(i-1,1)+transpose(j)*TIMESTEP*VELOCITY*cos(theta(k)); y = s_1(i-1,2)+transpose(j)*TIMESTEP*VELOCITY*sin(theta(k)); z = s_1(i-1,3)*ones(N+1,S); quadtraj(:,1,:,k) = x; quadtraj(:,2,:,k) = y; quadtraj(:,3,:,k) = z; end end setquadtraj(:,:,:,:,i) = quadtraj; end %% collision detection and trajectory optimization safeTraj = ones(S,K-1); for i = 1:N-1 % put data in right form for making convex hull for j = 1:m+1 projset1(j,:) = projtraj(i,:,j); projset2(j,:) = projtraj(i+1,:,j); end % create intersample convex hull for projectile projintersampleSet = [projset1; projset2]; projectileConvexHull(i) = SimulationMakeObj(projintersampleSet); end % evaluate each trajectory trajCost = zeros(S,K-1); for k = 1:K-1 for s = 1:S % run collision detection algorithm for i = 1:N-1 % put data in right form for making convex hull % all points from successive sets for j = 1:m quadset1(j,:) = setquadtraj(i,:,s,k,j); quadset2(j,:) = setquadtraj(i+1,:,s,k,j); end % create intersample convex hull for trajectory k for quadrotor quadIntersampleSet = [quadset1; quadset2]; quadrotorConvexHull = SimulationMakeObj(quadIntersampleSet); %collisionFlag = GJK(projectileConvexHull(i), quadrotorConvexHull, iterationsAllowed); [dist,~,~,~]=GJK_dist(projectileConvexHull(i),quadrotorConvexHull); if(dist < sigma) %fprintf('Collision in trajectory %d at speed %d at time step %d\n\r', k,VELOCITY(s),i); safeTraj(s,k) = 0; trajCost(s,k) = inf; break; else [cost,~,~,~] = GJK_dist(targetObj,quadrotorConvexHull); collisionFlag = GJK(targetObj,quadrotorConvexHull,iterationsAllowed); if(collisionFlag) cost cost = 0; error('must increase minimum cost'); end trajCost(s,k) = trajCost(s,k) + cost; end end end end %% find optimal input % find minimum cost and return first coordinate in that trajectory [minCostList, minCostIndexList] = min(trajCost); [minCost, minCostKIndex] = min(minCostList); minCostSIndex = minCostIndexList(minCostKIndex); u_opt = setquadtraj(2,:,minCostSIndex,minCostKIndex,1); input = [u_opt,projtraj(2,:,1), projvel(2,:,1)]; xlabel('x axis'); ylabel('y axis'); zlabel('z axis'); grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
CostSum.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/functions/CostSum.m
313
utf_8
49502b1d0e6bda46cdf68a30ef0c6178
% calculates total cost of a trajectory function totalCost = CostSum(trajectory, target, N) totalCost = 0; % sum distances between each point in trajectory and target for i = 1:N cost = pdist([trajectory(i,:); target], 'euclidean'); totalCost = totalCost + cost; end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK_mod.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/GJK DISTANCE/GJK_mod.m
6,720
utf_8
5b06ac643912454d6a7709cccdb88a00
function [a,b,c,d,flag] = GJK_mod(shape1,shape2,iterations) % GJK Gilbert-Johnson-Keerthi Collision detection implementation. % Returns whether two convex shapes are are penetrating or not % (true/false). Only works for CONVEX shapes. % % Inputs: % shape1: % must have fields for XData,YData,ZData, which are the x,y,z % coordinates of the vertices. Can be the same as what comes out of a % PATCH object. It isn't required that the points form faces like patch % data. This algorithm will assume the convex hull of the x,y,z points % given. % % shape2: % Other shape to test collision against. Same info as shape1. % % iterations: % The algorithm tries to construct a tetrahedron encompassing % the origin. This proves the objects have collided. If we fail within a % certain number of iterations, we give up and say the objects are not % penetrating. Low iterations means a higher chance of false-NEGATIVES % but faster computation. As the objects penetrate more, it takes fewer % iterations anyway, so low iterations is not a huge disadvantage. % % Outputs: % flag: % true - objects collided % false - objects not collided % [a,b,c,d] - members of the simplex % % % This video helped me a lot when making this: https://mollyrocket.com/849 % Not my video, but very useful. % % Matthew Sheen, 2016 % % Modified: % Philippe Lebel, 2016: % Fixed a bug where aligned vertices would trigger the collision flag % while there was no collision ( line 191 ) %Point 1 and 2 selection (line segment) v = [0.8 0.5 1]; [a,b] = pickLine(v,shape2,shape1); %Point 3 selection (triangle) [a,b,c,flag] = pickTriangle(a,b,shape2,shape1,iterations); %Point 4 selection (tetrahedron) % if flag == 1 %Only bother if we could find a viable triangle. [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape2,shape1,iterations); % end end function [a,b] = pickLine(v,shape1,shape2) %Construct the first line of the simplex b = support(shape2,shape1,v); dir_ori=-b; a = support(shape2,shape1,dir_ori); end function [a,b,c,flag] = pickTriangle(a,b,shape1,shape2,IterationAllowed) flag = 0; %So far, we don't have a successful triangle. %First try: ab = b-a; ao = -a; v = cross(cross(ab,ao),ab); % v is perpendicular to ab pointing in the general direction of the origin. c = b; b = a; a = support(shape2,shape1,v); for i = 1:IterationAllowed %iterations to see if we can draw a good triangle. %Time to check if we got it: ab = b-a; ao = -a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); %Perpendicular to AB going away from triangle abp = cross(ab,abc); %Perpendicular to AC going away from triangle acp = cross(abc,ac); %First, make sure our triangle "contains" the origin in a 2d projection %sense. %Is origin above (outside) AB? if dot(abp,ao) > 0 c = b; %Throw away the furthest point and grab a new one in the right direction b = a; v = abp; %cross(cross(ab,ao),ab); %Is origin above (outside) AC? elseif dot(acp, ao) > 0 b = a; v = acp; %cross(cross(ac,ao),ac); else % flag = 1; % break; %We got a good one. end a = support(shape2,shape1,v); end end function [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape1,shape2,IterationAllowed) %Now, if we're here, we have a successful 2D simplex, and we need to check %if the origin is inside a successful 3D simplex. %So, is the origin above or below the triangle? flag = 0; ab = b-a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); ao = -a; if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = c; c = b; b = a; a=a_new; end else %below d = b; b = a; v = -abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = b; b = a; a=a_new; end end for i = 1:IterationAllowed %Allowing 10 tries to make a good tetrahedron. %Check the tetrahedron: ab = b-a; ao = -a; ac = c-a; ad = d-a; %We KNOW that the origin is not under the base of the tetrahedron based on %the way we picked a. So we need to check faces ABC, ABD, and ACD. %Normal to face of triangle abc = cross(ab,ac); if dot(abc, ao) > 0 %Above triangle ABC %No need to change anything, we'll just iterate again with this face as %default. else acd = cross(ac,ad);%Normal to face of triangle if dot(acd, ao) > 0 %Above triangle ACD %Make this the new base triangle. b = c; c = d; ab = ac; ac = ad; abc = acd; elseif dot(acd, ao) < 0 adb = cross(ad,ab);%Normal to face of triangle if dot(adb, ao) > 0 %Above triangle ADB %Make this the new base triangle. c = b; b = d; ac = ab; ab = ad; abc = adb; else flag = 1; break; %It's inside the tetrahedron. end else %The nearest point is one of the three points contained in the simplex ; end end %try again: if dot(abc, ao) > 0 %Above v = abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = c; c = b; b = a; a=a_new; end else %below v = -abc; a_new = support(shape2,shape1,v); %Tetrahedron new point if ismember(a_new',[a;b;c;d]') else d = b; b = a; a=a_new; end end end end function point = getFarthestInDir(shape, v) %Find the furthest point in a given direction for a shape XData = shape.Vertices(:,1); % Making it more compatible with previous MATLAB releases. YData = shape.Vertices(:,2); ZData = shape.Vertices(:,3); dotted = XData*v(1) + YData*v(2) + ZData*v(3); [maxInCol,rowIdxSet] = max(dotted); [maxInRow,colIdx] = max(maxInCol); rowIdx = rowIdxSet(colIdx); point = [XData(rowIdx,colIdx), YData(rowIdx,colIdx), ZData(rowIdx,colIdx)]'; end function point = support(shape1,shape2,v) %Support function to get the Minkowski difference. point1 = getFarthestInDir(shape1, v); point2 = getFarthestInDir(shape2, -v); point = point1 - point2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK_dist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/GJK DISTANCE/GJK_dist.m
10,028
utf_8
536b90ca4f66c97f6dad1e522b854947
%This function is based on the book Real-Time Collision Detection % (http://realtimecollisiondetection.net/) % %It computes the distance, the points of closest proximity points and also %returns the points last contained in the simplex. %[dist,pts,G,H] = GJK_dist_7_point_poly( shape1, shape2 ) % % INPUTS: % % shape1: a patch object representing the first convex solid % shape2: a patch object representing the second convex solid % % OUTPUTS: % % dist: an absolute float number representing the minimum distance between % the shapes. % pts: The points of the minkowsky diference where the alogrithm % stoped. % G: The point on shape1 closest to shape2 % H: The point on shape2 closest to shape1 % updated 05/01/17. Thanks to Amin Ramezanifar for pointing out an error. function [dist,pts,G,H] = GJK_dist( shape1, shape2 ) %pick a random direction d=[1 1 1]; %pick a point [a, point1_a, point2_a]=support_2(shape1,shape2,d); %pick a second point to creat a line [b, point1_b, point2_b]=support_2(shape1,shape2,-d); %pick a third point to make a tirangle ab=b-a; ao=-a; %perpendicular direction d=cross(cross(ab,ao),ab); %pick a third point [c, point1_c, point2_c]=support_2(shape1,shape2,d); %the simplex is now complete pts=[a b c]; pts_1_2=[point1_a point1_b point1_c;point2_a point2_b point2_c]; itt=0; pts_old=pts; norm_old=norm(pts_old); d_old=d; dist_old=1000; dist=1000; flag=0; PP0 = 'V'; %This loop is there for the very rare case where the simplex would contain %duplicate points. while true if isequal(c,b) || isequal(c,a) [c, point1_c, point2_c]=support_2(shape1,shape2,-d); else pts=[a b c]; pts_1_2=[point1_a point1_b point1_c;point2_a point2_b point2_c]; break end end while true %we compute the norm of vector going from the origin to each member %of the simplex Norm_pts = (sqrt(sum(abs(pts').^2,2))); %Computing and removing the farthest point of the simplex from the origin [max_norm,index]=max(Norm_pts); %new search direction d=cross(pts(:,2)-pts(:,1),pts(:,3)-pts(:,1)); origin_projected=(pts(:,1)'*d)*d; if d'*origin_projected>0 d=-d; end d=d/norm(d); %Pciking a new point to add to the simplex. [c, point1_c, point2_c]=support_2(shape1,shape2,d); %we project the origin on the simplex's plane. origin_projected=(pts(:,1)'*d)*d; % We verify if the point is allready contained in the simplex. % The (itt>5 && flag == 5) condition to enter this loop is one of the main % problems of the algorithm. Sometime, when using only the normal to % the triangle, the solution does not converge to the absolute minimum % distance. This other way of computing the new direction allows a % higher rate of succesful convergeance. If one would want to upgrade the % algorithm he would certainly need to work arround here. if any(abs(Norm_pts-norm(c))<0.000001) || (itt>5 && flag == 5) % computing the distance of each traingle lines from the origin d1 = distLinSeg(pts(:,1)',pts(:,2)',origin_projected',origin_projected'); d2 = distLinSeg(pts(:,1)',pts(:,3)',origin_projected',origin_projected'); d3 = distLinSeg(pts(:,2)',pts(:,3)',origin_projected',origin_projected'); % d1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); % d2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); % d3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); dist_seg_min=min(abs([d1 d2 d3])); %we want to pick the two points creating the line closest to the %origin. %We also need to deal with the case where the origin is closest to %a point, resulting in two distances being equal. if dist_seg_min<dist while true if d1==dist_seg_min %pick a third point to make a tirangle ab=pts(:,2)-pts(:,1); ao=-pts(:,1); %perpendicular direction d=cross(cross(ab,ao),ab); if d1~=d2 && d1~=d3 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=3; break else [c_1, point1_c_1, point2_c_1]=support_2(shape1,shape2,d); index_1=3; end end if d2==dist_seg_min %pick a third point to make a tirangle ab=pts(:,3)-pts(:,1); ao=-pts(:,1); %perpendicular direction d=cross(cross(ab,ao),ab); if d2~=d1 && d2~=d3 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=2; break else [c_2, point1_c_2, point2_c_2]=support_2(shape1,shape2,d); index_2=2; end end if d3==dist_seg_min %pick a third point to make a tirangle ab=pts(:,3)-pts(:,2); ao=-pts(:,2); %perpendicular direction d=cross(cross(ab,ao),ab); if d3~=d1 && d3~=d2 [c, point1_c, point2_c]=support_2(shape1,shape2,d); index=1; break else [c_3, point1_c_3, point2_c_3]=support_2(shape1,shape2,d); index_3=1; end end if d1==d2 L1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); if L1>L2 c=c_1; point1_c=point1_c_1; point2_c=point2_c_1; else c=c_2; point1_c=point1_c_2; point2_c=point2_c_2; end elseif d1==d3 L1=(pts(:,2)-pts(:,1))'/norm(pts(:,2)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); if L1>L3 c=c_1; point1_c=point1_c_1; point2_c=point2_c_1; else c=c_3; point1_c=point1_c_3; point2_c=point2_c_3; end elseif d2==d3 L2=(pts(:,3)-pts(:,1))'/norm(pts(:,3)-pts(:,1))*(pts(:,1)-origin_projected)/norm((pts(:,1)-origin_projected)); L3=(pts(:,3)-pts(:,2))'/norm(pts(:,3)-pts(:,2))*(pts(:,2)-origin_projected)/norm((pts(:,2)-origin_projected)); if L2>L3 c=c_2; point1_c=point1_c_2; point2_c=point2_c_2; else c=c_3; point1_c=point1_c_3; point2_c=point2_c_3; end end break end end % if even after picking a new point with the other method, if the % simplex already has it, we assume we converged. if any(abs(Norm_pts-norm(c))<0.000001) if PP0 == 'V' % converged on first itteration, dist and PP0 must be % computed. [dist, PP0] = pointTriangleDistance(pts',[0 0 0]); end Norm_pts=0; break end end pts(:,index)=[]; pts_1_2(:,index)=[]; pts=[pts c]; pts_1_2=[pts_1_2 [point1_c;point2_c]]; [dist, PP0] = pointTriangleDistance(pts',[0 0 0]); %we need to do the following manipulation because sometimes, the %simplex will oscillate arround the closest solution, creating an %infinite loop. We need to backup the solution that resulted in the %minimal distance and use it if the loop times out (10 itteration max) if dist<dist_old pts_prox=pts; dist_prox=dist; PP0_prox=PP0; pts_1_2_prox=pts_1_2; end %The time out is set here. if itt>6 flag=5; if itt>10 && flag==5 pts=pts_prox; dist=dist_prox; PP0=PP0_prox; pts_1_2=pts_1_2_prox; break end end dist_old=dist; d_old=d; pts_old=pts; if abs(norm_old-norm(pts))<0.01 norm_old=norm(pts); end itt=itt+1; % pause(0.1) end % Calculation of the barycentric coordinates of the origin in respect to % the simplex. T = [1 4 3; 1 4 2; 3 4 2; 1 2 3]; pts_t=[pts';PP0]; % commented out by Jeremy %TR=triangulation(T,pts_t); %B=cartesianToBarycentric(TR,4,PP0); G=0; H=0; %calculation of the points G and H of proximity on,respectively, shape1 %and shape2. % commented out by Jeremy %for i=1:3 % G=G+B(i)*pts_1_2(1:3,i); % H=H+B(i)*pts_1_2(4:6,i); %end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
GJK.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/GJK DISTANCE/GJK.m
6,009
utf_8
30df12311f7526c9599cde4b2aaf7a3a
function [flag] = GJK(shape1,shape2,iterations) % GJK Gilbert-Johnson-Keerthi Collision detection implementation. % Returns whether two convex shapes are are penetrating or not % (true/false). Only works for CONVEX shapes. % % Inputs: % shape1: % must have fields for XData,YData,ZData, which are the x,y,z % coordinates of the vertices. Can be the same as what comes out of a % PATCH object. It isn't required that the points form faces like patch % data. This algorithm will assume the convex hull of the x,y,z points % given. % % shape2: % Other shape to test collision against. Same info as shape1. % % iterations: % The algorithm tries to construct a tetrahedron encompassing % the origin. This proves the objects have collided. If we fail within a % certain number of iterations, we give up and say the objects are not % penetrating. Low iterations means a higher chance of false-NEGATIVES % but faster computation. As the objects penetrate more, it takes fewer % iterations anyway, so low iterations is not a huge disadvantage. % % Outputs: % flag: % true - objects collided % false - objects not collided % % % This video helped me a lot when making this: https://mollyrocket.com/849 % Not my video, but very useful. % % Matthew Sheen, 2016 % %Point 1 and 2 selection (line segment) v = [0.8 0.5 1]; [a,b] = pickLine(v,shape2,shape1); %Point 3 selection (triangle) [a,b,c,flag] = pickTriangle(a,b,shape2,shape1,iterations); %Point 4 selection (tetrahedron) if flag == 1 %Only bother if we could find a viable triangle. [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape2,shape1,iterations); end end function [a,b] = pickLine(v,shape1,shape2) %Construct the first line of the simplex b = support(shape2,shape1,v); a = support(shape2,shape1,-v); end function [a,b,c,flag] = pickTriangle(a,b,shape1,shape2,IterationAllowed) flag = 0; %So far, we don't have a successful triangle. %First try: ab = b-a; ao = -a; v = cross(cross(ab,ao),ab); % v is perpendicular to ab pointing in the general direction of the origin. c = b; b = a; a = support(shape2,shape1,v); for i = 1:IterationAllowed %iterations to see if we can draw a good triangle. %Time to check if we got it: ab = b-a; ao = -a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); %Perpendicular to AB going away from triangle abp = cross(ab,abc); %Perpendicular to AC going away from triangle acp = cross(abc,ac); %First, make sure our triangle "contains" the origin in a 2d projection %sense. %Is origin above (outside) AB? if dot(abp,ao) > 0 c = b; %Throw away the furthest point and grab a new one in the right direction b = a; v = abp; %cross(cross(ab,ao),ab); %Is origin above (outside) AC? elseif dot(acp, ao) > 0 b = a; v = acp; %cross(cross(ac,ao),ac); else flag = 1; break; %We got a good one. end a = support(shape2,shape1,v); end end function [a,b,c,d,flag] = pickTetrahedron(a,b,c,shape1,shape2,IterationAllowed) %Now, if we're here, we have a successful 2D simplex, and we need to check %if the origin is inside a successful 3D simplex. %So, is the origin above or below the triangle? flag = 0; ab = b-a; ac = c-a; %Normal to face of triangle abc = cross(ab,ac); ao = -a; if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end for i = 1:IterationAllowed %Allowing 10 tries to make a good tetrahedron. %Check the tetrahedron: ab = b-a; ao = -a; ac = c-a; ad = d-a; %We KNOW that the origin is not under the base of the tetrahedron based on %the way we picked a. So we need to check faces ABC, ABD, and ACD. %Normal to face of triangle abc = cross(ab,ac); if dot(abc, ao) > 0 %Above triangle ABC %No need to change anything, we'll just iterate again with this face as %default. else acd = cross(ac,ad);%Normal to face of triangle if dot(acd, ao) > 0 %Above triangle ACD %Make this the new base triangle. b = c; c = d; ab = ac; ac = ad; abc = acd; elseif dot(acd, ao) < 0 adb = cross(ad,ab);%Normal to face of triangle if dot(adb, ao) > 0 %Above triangle ADB %Make this the new base triangle. c = b; b = d; ac = ab; ab = ad; abc = adb; else flag = 1; break; %It's inside the tetrahedron. end else %the origin is on the same plane as the triangle ; end end %try again: if dot(abc, ao) > 0 %Above d = c; c = b; b = a; v = abc; a = support(shape2,shape1,v); %Tetrahedron new point else %below d = b; b = a; v = -abc; a = support(shape2,shape1,v); %Tetrahedron new point end end end function point = getFarthestInDir(shape, v) %Find the furthest point in a given direction for a shape XData = shape.Vertices(:,1); % Making it more compatible with previous MATLAB releases. YData = shape.Vertices(:,2); ZData = shape.Vertices(:,3); dotted = XData*v(1) + YData*v(2) + ZData*v(3); [maxInCol,rowIdxSet] = max(dotted); [maxInRow,colIdx] = max(maxInCol); rowIdx = rowIdxSet(colIdx); point = [XData(rowIdx,colIdx), YData(rowIdx,colIdx), ZData(rowIdx,colIdx)]'; end function point = support(shape1,shape2,v) %Support function to get the Minkowski difference. point1 = getFarthestInDir(shape1, v); point2 = getFarthestInDir(shape2, -v); point = point1 - point2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
distLinSeg.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/TruerMPC/GJK DISTANCE/distLinSeg.m
2,407
utf_8
f4674ddd3116bd073e046a82cc0b8e1e
% Function for fast computation of the shortest distance between two line segments % % Algorithm implemented: % Vladimir J. LUMELSKY, % ``ON FAST COMPUTATION OF DISTANCE BETWEEN LINE SEGMENTS'', % Information Processing Letters 21 (1985) 55-61 % % % Input: ([start point of line1], [end point of line1], [start point of % line2], [end point of line2]) % % Output: dist - shortest distance between the line segments (in N dimensions) % points (optional) - shortest points on the line segments % % Example: % >> [dist,points] = distLinSeg([0 0], [1 1], [1 0], [2 0]) % >> dist = 0.7071 % >> points = [0.5 0.5; 1 0] % % % 1.2.2015 - created: Ondrej Sluciak ([email protected]) % function [dist,varargout] = distLinSeg(point1s,point1e,point2s,point2e) d1 = point1e - point1s; d2 = point2e - point2s; d12 = point2s - point1s; D1 = d1*d1'; %D1 = sum(d1.^2); D2 = d2*d2'; %D2 = sum(d2.^2); S1 = d1*d12'; % S1 = sum(d1.*d12); S2 = d2*d12'; % S2 = sum(d2.*d12); R = d1*d2'; % R = sum(d1.*d2); den = D1*D2-R^2; %denominator if (D1 == 0 || D2 == 0) % if one of the segments is a point if (D1 ~= 0) % if line1 is a segment and line2 is a point u = 0; t = S1/D1; t = fixbound(t); elseif (D2 ~= 0) % if line2 is a segment and line 1 is a point t = 0; u = -S2/D2; u = fixbound(u); else % both segments are points t = 0; u = 0; end elseif (den == 0) % if lines are parallel t = 0; u = -S2/D2; uf = fixbound(u); if (uf~= u) t = (uf*R+S1)/D1; t = fixbound(t); u = uf; end else % general case t = (S1*D2-S2*R)/den; t = fixbound(t); u = (t*R-S2)/D2; uf = fixbound(u); if (uf ~= u) t = (uf*R+S1)/D1; t = fixbound(t); u = uf; end end % Compute distance given parameters 't' and 'u' dist = norm(d1*t-d2*u-d12); %dist = sqrt(sum((d1*t-d2*u-d12).^2)); if (nargout > 1) varargout = {[point1s + d1*t;point2s+d2*u]}; end end function num = fixbound(num) % if num is out of (0,1) round to {0,1} if (num < 0) num = 0; elseif (num > 1) num = 1; end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
MakeObj.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/plotting/MakeObj.m
624
utf_8
21b5894435118a86bc40d17143893710
% returns convex hull from point cloud function obj = MakeObj(points, color) %figure() % create face representation and create convex hull F = convhull(points(1,:), points(2,:), points(3,:)); S.Vertices = transpose(points); S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; if(strcmp(color,'red')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','red'); elseif(strcmp(color,'green')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','green'); else obj = patch(S); end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSim.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/plotting/PlotSetBasedSim.m
1,440
utf_8
8376aa33d176a72521448eb464a1ad66
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - number of points in each set % pA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % create objects/convex hulls for each set at each time step for i = 1:pA % format points for MakeObj function curSet = zeros(mA,nA); for j = 1:nA curSet(:,j) = agentPos(:,j,i); end % make the object MakeObj(curSet, 'green'); end [mO,nO,pO] = size(obst); % NOTE: pA == nO % plot obstacle with threshold for i = 1:nO for j = 1:pO % create sphere for obstacle (threshold and obstacle location) [x,y,z] = sphere; x = threshold*x+obst(1,i,j); y = threshold*y+obst(2,i,j); z = threshold*z+obst(3,i,j); [mS,nS] = size(z); % plot obst C = zeros(mS,nS,3); C(:,:,1) = C(:,:,1) + 1; s = surf(x,y,z,C); scatter3(obst(1,i,j), obst(2,i,j), obst(3,i,j), '*') end end scatter3(target(1), target(2), target(3), '*') xlabel('x axis') ylabel('y axis') zlabel('z axis') grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistance.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/plotting/PlotSimDistance.m
1,669
utf_8
e13929ce3bc4fc592bc379669153b036
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - number of points in each set % pA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation % pO - obstacle number [mO,nO,pO] = size(obst); ObstDist = zeros(pA,pO); for i = 1:pO for j = 1:pA % format points for MakeObj function curSet = zeros(mA,nA); for k = 1:nA curSet(:,k) = agentPos(:,k,j); end % min distance to projectile temp_xObst = [obst(:,j,i),obst(:,j,i)]; % polytope dist function has trouble with only one point ObstDist(j,i) = PolytopeMinDist(curSet,temp_xObst); end plot(0:1:(pA-1),transpose(ObstDist(:,i))); plot(0:1:(pA-1),threshold*ones(1,(pA))); end title('Minimum distance between vehicle polytope and obstacle polytope'); xlabel('time'); ylabel('distance'); figure() hold on; dist = zeros(pA,1); for i = 1:pA for j = 1:nA dist(i) = dist(i) + norm(agentPos(:,j,i)-target)^2; end end plot(0:1:(pA-1),dist); title('Minimum distance between vehicle polytope and target polytope'); xlabel('time'); ylabel('distance'); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotOptimalPredicted.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/plotting/PlotOptimalPredicted.m
1,354
utf_8
dfabe81778fe58855a75e53defd5b6c1
function PlotOptimalPredicted(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation % pA - number of points in each set [mA,nA,pA] = size(agentPos); % create objects/convex hulls for each set at each time step for i = 1:nA % format points for MakeObj function curSet = zeros(mA,pA); for j = 1:pA curSet(:,j) = agentPos(:,i,j); end % make the object MakeObj(curSet, 'green'); end [mO,nO,pO] = size(obst); % NOTE: pA == nO % plot obstacle with threshold for i = 1:nO for j = 1:pO % create sphere for obstacle (threshold and obstacle location) [x,y,z] = sphere; x = threshold*x+obst(1,i,j); y = threshold*y+obst(2,i,j); z = threshold*z+obst(3,i,j); [mS,nS] = size(z); % plot obst C = zeros(mS,nS,3); C(:,:,1) = C(:,:,1) + 1; s = surf(x,y,z,C); scatter3(obst(1,i,j), obst(2,i,j), obst(3,i,j), '*') end end scatter3(target(1), target(2), target(3), '*') xlabel('x axis') ylabel('y axis') zlabel('z axis') grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
Cost.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/system/Cost.m
804
utf_8
12eaf7fb318a8f3e60546adda1dbf9e0
% c = Cost(x0_set, u, ts, target) % % custom cost function - sum of distance from each vertex to target squared function c = Cost(x0_set, u, ts, target) % predict system state with set based dynamics x_set = SingleIntegrator(x0_set,u,ts); % calculate cost of prediction for set based dynamics % - iterate through each vertex at each time step and calculate the % distance between that point and the target [m,n,p] = size(x_set); c = 0; for i = 1:p for j = 1:n c = c + norm(x_set(:,j,i)-target)^2; end end %{ c = 0; for i = 1:n polySet = zeros(3,p); for j = 1:p polySet(:,j) = x_set(:,i,j); end c = c + PolytopeMinDist(polySet, target); end %} end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
FindOptimalInput.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/system/FindOptimalInput.m
825
utf_8
7879ed6c2d02f9d83f588dd8e57d0257
% function u0 = FindOptimalInput(x0, N, ts, target) % % uses fmincon to minimize cost function given system dynamics and % nonlinear constraints, returns optimal input sequence function u0 = FindOptimalInput(x0_set, N, ts, target, xObst, threshold) A = []; b = []; Aeq = []; beq = []; % set lower and upper bounds on inputs to integrator bound = 0.1; lb = -bound*ones(3,N); ub = bound*ones(3,N); uInit = zeros(3,N); % solve optimization options = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set','MaxFunEvals',1000,'ConstraintTolerance',1e-04); uopt = fmincon(@(u) Cost(x0_set,u,ts,target),uInit,A,b,Aeq,beq,lb,ub, @(u) ObstConstraint(x0_set,u,ts,xObst,threshold),options); % return optimal input sequence u0 = uopt; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
ObstConstraint.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/system/ObstConstraint.m
1,338
utf_8
a8f0d3ca6d3c3ba471cafb6dd54a7ced
% [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold) % % defines the non linear constraint - agent polytope to maintain % a distance from the obstacle position above threshold function [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold) % predict agent with set based dynamics % coords X time X set points x_set = SingleIntegrator(x0_set, u, ts); % find distance between agent polytope and obstacle [mA,nA,pA] = size(x_set); [mO,nO,pO] = size(xObst); ObstDist = zeros(1,pO*nA); obstDistCount = 1; for i = 1:nA % time for j = 1:pO % number of obstacles % format the agents set for polytope minimization for time step i xPolytope = zeros(3,pA); for k = 1:pA xPolytope(:,k) = x_set(:,i,k); end % calculate distance between agent and obstacle % xPolytope is a 3xp matrix % xObst(:,i,j) is a 3x1 matrix temp_xObst = [xObst(:,i,j),xObst(:,i,j)]; % polytope dist function has trouble with only one point ObstDist(obstDistCount) = PolytopeMinDist(xPolytope,temp_xObst); obstDistCount = obstDistCount+1; end end % define constraints c = -ObstDist+threshold; ceq = []; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SingleIntegrator.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/system/SingleIntegrator.m
412
utf_8
103d816561c56f118cee17686dc4c4c4
% x = SingleIntegrator(x0_set, u, ts) % % set based dynamics of single integrator function x = SingleIntegrator(x0_set, u, ts) [mP,nP] = size(x0_set); [mH,nH] = size(u); % coords X time X set points x = zeros(3,nH+1,nP); x(:,1,:) = x0_set; % apply integrator dynamics for j = 1:nP for i = 1:nH x(:,i+1,j) = x(:,i,j) + ts*u(:,i); end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SimulationProjectilePredict.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/projectile/SimulationProjectilePredict.m
764
utf_8
8ea559140e8b2248afec5e16b1990cb5
% [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % % calls on simulink to predict projectile state given initial conditions function [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % set up simulink set_param('projectile/rx','Value',num2str(p_0(1))); set_param('projectile/ry','Value',num2str(p_0(2))); set_param('projectile/rz','Value',num2str(p_0(3))); set_param('projectile/vx','Value',num2str(p_0(4))); set_param('projectile/vy','Value',num2str(p_0(5))); set_param('projectile/vz','Value',num2str(p_0(6))); set_param('projectile', 'StopTime', num2str(simTime)); % run simulation sim('projectile'); trajectory = projectilePos; velocity = projectileVel; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
CreateSphere.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/polytope/CreateSphere.m
913
utf_8
e7fc2c7730cbb8e66f70c29e702d9c20
% creates a point cloud in a sphere around the center function points = CreateSphere(center, r, thetadis, phidis) % angle discretization thetas = linspace(0,2*pi,thetadis); phis = linspace(0,pi,phidis); % point calculation points = []; x = []; y = []; z = []; for i = 1:length(phis) for j = 1:length(thetas) % removes duplicate point at theta = 2*pi if(thetas(j) == 2*pi) break end x = (r * sin(phis(i)) * cos(thetas(j))) + center(1); y = (r * sin(phis(i)) * sin(thetas(j))) + center(2); z = (r * cos(phis(i))) + center(3); nextPoint = [x;y;z]; points = [points, nextPoint]; % removes duplicate points at the top and bottom of sphere if(phis(i) == 0 || phis(i) == pi) break end end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeMinDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/OldSimFiles/MatlabSim/SBONL_MultipleObst/polytope/PolytopeMinDist.m
960
utf_8
20c5308cdee25a3c8505d60826371706
% minDist = PolytopeMinDist(X1,X2) % % finds the minimum distance between two polytopes X1 and X2 function minDist = PolytopeMinDist(X1,X2) % declare constraints for fmincon lb = []; ub = []; % get sizes of vertices for polytopes [m1,n1] = size(X1); [m2,n2] = size(X2); if(m1 ~= m2) error('Incorrect Dimensions'); end n = n1+n2; A = [eye(n); -eye(n)]; b = [ones(n,1); zeros(n,1)]; Aeq = [ones(1,n1) zeros(1,n2); zeros(1,n1) ones(1,n2)]; beq = [1;1]; nonlcon = []; % create lambda vectors x0 = zeros(n,1); x0(1) = 1; x0(n1+1) = 1; fun = @(lambda)(norm((X1 * lambda(1:n1))-(X2 * lambda(n1+1:n)))^2); % evaluate fmincon options = optimoptions('fmincon','Display','notify-detailed'); x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options); % return min distance minDist = sqrt(fun(x)); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSimSingle.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSetBasedSimSingle.m
1,656
utf_8
8cb1287b7a1a2b8f0f8452c845b28882
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim(agentPos, obst, threshold, target) % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % create objects/convex hulls for each set at each time step for j = 1:pA figure() hold on for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i,j);agentPos(3,i,j)]; curSet(:,2) = [agentPos(1,i,j);agentPos(4,i,j)]; curSet(:,3) = [agentPos(2,i,j);agentPos(3,i,j)]; curSet(:,4) = [agentPos(2,i,j);agentPos(4,i,j)]; % make the object MakeObj(curSet, 'g'); % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i,j);obst(3,i,j)]; curObstSet(:,2) = [obst(1,i,j);obst(4,i,j)]; curObstSet(:,3) = [obst(2,i,j);obst(3,i,j)]; curObstSet(:,4) = [obst(2,i,j);obst(4,i,j)]; % make the object MakeObj(curObstSet, 'r'); end FS = 16; h = gcf; %set(h,'Units','inches','Position',[2 2 3.4 2]) xlabel('q^1 [m]','FontName','Times','FontSize',FS) ylabel('q^2 [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) h.PaperPositionMode = 'auto'; axis([-2 2 -2 2]) grid on end %scatter(target(1), target(2), '*') end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSim_DO.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSetBasedSim_DO.m
1,625
utf_8
8864545c8077080445e4361d5bdecdc7
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim_DO(agentPos, obst, threshold, target, predictions) % mA - coordinate % nA - time step, equal to iterations in simulation % pA - numSim [mA,nA,pA] = size(agentPos); L = abs(agentPos(1,1,1)-agentPos(2,1,1)); W = abs(agentPos(3,1,1)-agentPos(4,1,1)); % 5 X N+1 X iterations X numSim [mP,nP,pP,qP] = size(predictions); cc = jet(pP); % sim num for i = 1:qP figure() FS = 50; h = gcf; set(gca,'FontSize',FS) axis([-2.0 2.0 -2.0 2.0]); grid on hold on box on % sim iteration for j = 1:pP % prediction horizon for k = 1:nP rectangle('Position',[predictions(1,k,j,i) predictions(3,k,j,i) L W],... 'EdgeColor',cc(mod(j,pP)+1,:)); end % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,j,i);obst(3,j,i)]; curObstSet(:,2) = [obst(1,j,i);obst(4,j,i)]; curObstSet(:,3) = [obst(2,j,i);obst(3,j,i)]; curObstSet(:,4) = [obst(2,j,i);obst(4,j,i)]; % make the object MakeObj(curObstSet, 'r'); end plot(agentPos(1,:,i)+L/2,agentPos(3,:,i)+W/2,'LineWidth',2,'color','red'); plot(agentPos(1,1,i)+L/2,agentPos(3,1,i)+W/2,'hk','MarkerSize',19); plot(target(1),target(2),'k*','MarkerSize',19); end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
MakeObj.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/MakeObj.m
683
utf_8
a81a3fae729eca365c5bffe0df3d8124
% returns convex hull from point cloud function obj = MakeObj(points, color) %figure() % create face representation and create convex hull F = convhull(points(1,:), points(2,:)); fill(points(1,F),points(2,F),color); %{ S.Vertices = transpose(points(1:2,:)); S.Faces = F; S.FaceVertexCData = jet(size(points,1)); S.FaceColor = 'interp'; if(strcmp(color,'red')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','red'); elseif(strcmp(color,'green')) obj = patch('Faces',S.Faces,'Vertices',S.Vertices,'FaceColor','green'); else obj = patch(S); end %} end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistance_DO.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSimDistance_DO.m
1,805
utf_8
3210dc4076617da791e502e3997a68e1
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance_DO(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation [mO,nO,pO] = size(obst); ObstDist = zeros(nA,pA); % create objects/convex hulls for each set at each time step for j = 1:pA for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i,j);agentPos(3,i,j)]; curSet(:,2) = [agentPos(1,i,j);agentPos(4,i,j)]; curSet(:,3) = [agentPos(2,i,j);agentPos(3,i,j)]; curSet(:,4) = [agentPos(2,i,j);agentPos(4,i,j)]; % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i,j);obst(3,i,j)]; curObstSet(:,2) = [obst(1,i,j);obst(4,i,j)]; curObstSet(:,3) = [obst(2,i,j);obst(3,i,j)]; curObstSet(:,4) = [obst(2,i,j);obst(4,i,j)]; % min distance to projectile polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); %ObstDist(i,j) = PolytopeApproxDist(curSet,curObstSet); ObstDist(i,j) = PolytopeMinDist(curSet,curObstSet,polyOptions); end plot(0:1:(nA-1),transpose(ObstDist(:,j))); end plot([0 (nA-1)],[threshold threshold],'--r'); FS = 50; h = gcf; set(gca,'FontSize',FS) axis([0 nA-1 0 1.5]); box on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSim16.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSetBasedSim16.m
2,996
utf_8
18fd234337bdbe6d2e11e27d3c4c7469
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim(agentPos, obst, threshold, target) % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % create objects/convex hulls for each set at each time step for j = 1:pA if(j<=16) if(j==6 || j==7 || j==9 || j==12 || j==13 || j==14 || j==15 || j==16) %subplot(2,2,1) figure(2) else %subplot(2,2,2) figure(1) end else if(j==22 || j==23 || j==25 || j==28 || j==29 || j==30 || j==31 || j==32) %subplot(2,2,3) figure(3) else %subplot(2,2,4) figure(4) end end hold on for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i,j);agentPos(3,i,j)]; curSet(:,2) = [agentPos(1,i,j);agentPos(4,i,j)]; curSet(:,3) = [agentPos(2,i,j);agentPos(3,i,j)]; curSet(:,4) = [agentPos(2,i,j);agentPos(4,i,j)]; % make the object MakeObj(curSet, 'g'); % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % make the object MakeObj(curObstSet, 'r'); end figure(1) FS = 24; h = gcf; xlabel('q^1 [m]','FontName','Times','FontSize',FS) ylabel('q^2 [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) h.PaperPositionMode = 'auto'; axis([-4 4 -4 4]) grid on figure(2) h = gcf; xlabel('q^1 [m]','FontName','Times','FontSize',FS) ylabel('q^2 [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) h.PaperPositionMode = 'auto'; axis([-4 4 -4 4]) grid on figure(3) h = gcf; xlabel('q^1 [m]','FontName','Times','FontSize',FS) ylabel('q^2 [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) h.PaperPositionMode = 'auto'; axis([-4 4 -4 4]) grid on figure(4) h = gcf; xlabel('q^1 [m]','FontName','Times','FontSize',FS) ylabel('q^2 [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) h.PaperPositionMode = 'auto'; axis([-4 4 -4 4]) grid on end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSetBasedSim_SO.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSetBasedSim_SO.m
1,679
utf_8
f30244ad8222015c7e4b7e7f637ffdd5
% PlotSetBasedSim(agentPos, obst, threshold) % % plots associated sets with the simulation function PlotSetBasedSim_SO(agentPos, obst, threshold, target, predictions) figure() FS = 50; h = gcf; set(gca,'FontSize',FS) axis([-1.5 1.0 -1.5 1.5]); grid on box on % mA - coordinate % nA - time step, equal to iterations in simulation % pA - numSim [mA,nA,pA] = size(agentPos); L = abs(agentPos(1,1,1)-agentPos(2,1,1)); W = abs(agentPos(3,1,1)-agentPos(4,1,1)); % 5 X N+1 X iterations X numSim [mP,nP,pP,qP] = size(predictions); cc = jet(pP); % sim num for i = 1:qP hold on % sim iteration for j = 1:pP % prediction horizon for k = 1:nP rectangle('Position',[predictions(1,k,j,i) predictions(3,k,j,i) L W],... 'EdgeColor',cc(mod(j,pP)+1,:),'LineWidth',0.6); end % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % make the object MakeObj(curObstSet, 'r'); end plot(agentPos(1,1,i)+L/2,agentPos(3,1,i)+W/2,'hk','MarkerSize',19); end for i = 1:pA plot(agentPos(1,:,i)+L/2,agentPos(3,:,i)+W/2,'LineWidth',2,'color','red'); end plot(target(1),target(2),'k*','MarkerSize',19); print(h,'sim_SO','-depsc','-r0') end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistance16.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSimDistance16.m
4,064
utf_8
d1c282b26571b195d86ca84a3bf3dde9
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance(agentPos, obst, threshold, target) % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation [mO,nO] = size(obst); ObstDist = zeros(nA,pA); figure(5) hold on % create objects/convex hulls for each set at each time step for j = 1:pA for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i,j);agentPos(3,i,j)]; curSet(:,2) = [agentPos(1,i,j);agentPos(4,i,j)]; curSet(:,3) = [agentPos(2,i,j);agentPos(3,i,j)]; curSet(:,4) = [agentPos(2,i,j);agentPos(4,i,j)]; % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % min distance to projectile polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); %ObstDist(i,j) = PolytopeMinDist(curSet,curObstSet,polyOptions); ObstDist(i,j) = PolytopeApproxDist(curSet,curObstSet); end %plot(0:1:(nA-1),transpose(ObstDist(:,j))); %if(j==16) % plot(0:1:(nA-1),threshold*ones(1,(nA)),'r'); % subplot(2,1,2) % hold on %end end plot([0 (nA-1)],[threshold threshold],'--r'); [y,ind] = min(ObstDist); for i = 1:pA if(y(i) < 0.2) plot(0:1:(nA-1),transpose(ObstDist(:,i))); end end FS = 12; h = gcf; set(h,'Units','inches','Position',[2 2 3.4 2]) xlabel('Time [s]','FontName','Times','FontSize',FS) ylabel('Distance [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) pos = h.PaperPosition; h.PaperPositionMode = 'auto'; set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)]) print(h,'filename','-dpdf','-r0') %title('Minimum Distance Between Vehicle and Obstacle'); axis([0 nA-1 0 2.5]); figure(6) subplot(2,1,1) hold on dist = zeros(nA,pA); for j = 1:pA for i = 1:nA dist(i,j) = dist(i,j) + sqrt(norm([agentPos(1,i,j);agentPos(3,i,j)]-target)^2) ... + sqrt(norm([agentPos(1,i,j);agentPos(4,i,j)]-target)^2) ... + sqrt(norm([agentPos(2,i,j);agentPos(3,i,j)]-target)^2) ... + sqrt(norm([agentPos(2,i,j);agentPos(4,i,j)]-target)^2); end plot(0:1:(nA-1),dist(:,j)); if(j==16) %plot(0:1:(nA-1),threshold*ones(1,(nA)),'r'); h = gcf; set(h,'Units','inches','Position',[2 2 3.4 2]) xlabel('Time [s]','FontName','Times','FontSize',FS) ylabel('Distance [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) pos = h.PaperPosition; h.PaperPositionMode = 'auto'; set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)]) %print(h,'filename','-dpdf','-r0') subplot(2,1,2) hold on end end h = gcf; set(h,'Units','inches','Position',[2 2 3.4 2]) xlabel('Time [s]','FontName','Times','FontSize',FS) ylabel('Distance [m]','FontName','Times','FontSize',FS) set(gca,'FontName','Times','FontSize',FS) pos = h.PaperPosition; h.PaperPositionMode = 'auto'; set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)]) %print(h,'filename','-dpdf','-r0') end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistance_SO.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSimDistance_SO.m
2,921
utf_8
fb80862abdaa4892147f82d5a38ab012
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance_SO(agentPos, obst, threshold, target) % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA,pA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation [mO,nO] = size(obst); L = abs(agentPos(1,1,1)-agentPos(2,1,1)); W = abs(agentPos(3,1,1)-agentPos(4,1,1)); minDist = 2*sqrt(L^2 + W^2); ObstDist = zeros(nA,pA); figure() hold on % create objects/convex hulls for each set at each time step for j = 1:pA for i = 1:nA % format points for MakeObj function curSet = zeros(2,4); curSet(:,1) = [agentPos(1,i,j);agentPos(3,i,j)]; curSet(:,2) = [agentPos(1,i,j);agentPos(4,i,j)]; curSet(:,3) = [agentPos(2,i,j);agentPos(3,i,j)]; curSet(:,4) = [agentPos(2,i,j);agentPos(4,i,j)]; % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % min distance to projectile polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); %ObstDist(i,j) = PolytopeMinDist(curSet,curObstSet,polyOptions); ObstDist(i,j) = PolytopeApproxDist(curSet,curObstSet); end %plot(0:1:(nA-1),transpose(ObstDist(:,j))); %if(j==16) % plot(0:1:(nA-1),threshold*ones(1,(nA)),'r'); % subplot(2,1,2) % hold on %end end plot([0 (nA-1)],[threshold threshold],'--r'); [y,ind] = min(ObstDist); for i = 1:pA if(y(i) < 0.2) plot(0:1:(nA-1),transpose(ObstDist(:,i))); end end FS = 50; h = gcf; set(gca,'FontSize',FS) print(h,'DistToObst','-depsc','-r0') box on grid on axis([0 nA-1 0 1.5]); figure() hold on dist = zeros(nA,pA); for j = 1:pA for i = 1:nA dist(i,j) = dist(i,j) + sqrt(norm([agentPos(1,i,j);agentPos(3,i,j)]-target)^2) ... + sqrt(norm([agentPos(1,i,j);agentPos(4,i,j)]-target)^2) ... + sqrt(norm([agentPos(2,i,j);agentPos(3,i,j)]-target)^2) ... + sqrt(norm([agentPos(2,i,j);agentPos(4,i,j)]-target)^2); end plot(0:1:(nA-1),dist(:,j)); end plot([0 (nA-1)],[minDist minDist],'--r'); h = gcf; set(gca,'FontSize',FS) print(h,'DistToTarg','-depsc','-r0') box on grid on end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotSimDistanceSuccessive.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotSimDistanceSuccessive.m
2,189
utf_8
1966c59ec2bb87432a05d3b9d69754f9
% PlotSetBasedSim(agentPos, obst, threshold) % % plots max distance to target and min distance to projectile throughout % the simulation function PlotSimDistance(agentPos, obst, threshold, target) figure(1) hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % mO - coordinate (usually size 3) % nO - time step, equal to iterations in simulation % pO - obstacle number [mO,nO,pO] = size(obst); ObstDist = zeros(nA,pO); for i = 1:pO % create objects/convex hulls for each set at each time step for j = 1:nA % format points for MakeObj function curSet = zeros(3,4); curSet(:,1) = [agentPos(1,j);agentPos(3,j);0]; curSet(:,2) = [agentPos(1,j);agentPos(4,j);0]; curSet(:,3) = [agentPos(2,j);agentPos(3,j);0]; curSet(:,4) = [agentPos(2,j);agentPos(4,j);0]; % min distance to projectile temp_xObst = [obst(:,j,i),obst(:,j,i)]; % polytope dist function has trouble with only one point polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); ObstDist(j,i) = PolytopeMinDist(curSet,temp_xObst,polyOptions); end plot(0:1:(nA-1),transpose(ObstDist(:,i))); plot(0:1:(nA-1),threshold*ones(1,(nA))); end title('Minimum distance between vehicle polytope and obstacle polytope'); xlabel('time'); ylabel('distance'); axis([0 nA-1 0 2]); drawnow; figure(2) hold on; dist = zeros(nA,1); for i = 1:nA dist(i) = dist(i) + norm([agentPos(1,i);agentPos(3,i);0]-target)^2 ... + norm([agentPos(1,i);agentPos(4,i);0]-target)^2 ... + norm([agentPos(2,i);agentPos(3,i);0]-target)^2 ... + norm([agentPos(2,i);agentPos(4,i);0]-target)^2; end plot(0:1:(nA-1),dist); title('Minimum distance between vehicle polytope and target polytope'); xlabel('time'); ylabel('distance'); drawnow; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PlotOptimalPredicted.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/plotting/PlotOptimalPredicted.m
1,231
utf_8
a1fa72c034992b3f76f995656abe6af9
function PlotOptimalPredicted(agentPos, obst, threshold, target) figure() hold on % mA - coordinate (usually size 3) % nA - time step, equal to iterations in simulation [mA,nA] = size(agentPos); % create objects/convex hulls for each set at each time step for i = 1:nA % format points for MakeObj function curVehicleSet = zeros(2,4); curVehicleSet(:,1) = [agentPos(1,i);agentPos(3,i)]; curVehicleSet(:,2) = [agentPos(1,i);agentPos(4,i)]; curVehicleSet(:,3) = [agentPos(2,i);agentPos(3,i)]; curVehicleSet(:,4) = [agentPos(2,i);agentPos(4,i)]; % make the object MakeObj(curVehicleSet, 'g'); % format points for MakeObj function curObstSet = zeros(2,4); curObstSet(:,1) = [obst(1,i);obst(3,i)]; curObstSet(:,2) = [obst(1,i);obst(4,i)]; curObstSet(:,3) = [obst(2,i);obst(3,i)]; curObstSet(:,4) = [obst(2,i);obst(4,i)]; % make the object MakeObj(curObstSet, 'r'); end scatter(target(1), target(2), '*') xlabel('x axis') ylabel('y axis') zlabel('z axis') grid on drawnow; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
Cost.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/system/Cost.m
1,037
utf_8
7d52b29ad7c2ba935094018617a299dc
% c = Cost(x0_set, u, ts, target) % % custom cost function - sum of distance from each vertex to target squared function c = Cost(x0_set, u, ts, target, L, terminalWeight) % predict system state with set based dynamics x_set = Dubin(x0_set,u,ts,L); % calculate cost of prediction for set based dynamics % - iterate through each vertex at each time step and calculate the % distance between that point and the target [m,n] = size(x_set); c = 0; % stage cost for i = 1:n-1 c = c + norm([x_set(1,i);x_set(3,i)]-target)^2 ... + norm([x_set(1,i);x_set(4,i)]-target)^2 ... + norm([x_set(2,i);x_set(3,i)]-target)^2 ... + norm([x_set(2,i);x_set(4,i)]-target)^2; end % terminal cost c = c + terminalWeight*norm([x_set(1,n);x_set(3,n)]-target)^2 ... + terminalWeight*norm([x_set(1,n);x_set(4,n)]-target)^2 ... + terminalWeight*norm([x_set(2,n);x_set(3,n)]-target)^2 ... + terminalWeight*norm([x_set(2,n);x_set(4,n)]-target)^2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
FindOptimalInput.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/system/FindOptimalInput.m
1,241
utf_8
5caed38f53976af545767fbafde53c10
% function u0 = FindOptimalInput(x0, N, ts, target) % % uses fmincon to minimize cost function given system dynamics and % nonlinear constraints, returns optimal input sequence function uopt = FindOptimalInput(x0_set, N, ts, target, xObst, threshold, L, speedBound, steeringBound, terminalWeight, uGuess, EXP) A = []; b = []; Aeq = []; beq = []; % set lower and upper bounds on inputs to dubins model lb(1,:) = zeros(1,N); % lower bound is zero (speed) lb(2,:) = -steeringBound*ones(1,N); ub(1,:) = speedBound*ones(1,N); ub(2,:) = steeringBound*ones(1,N); % initial input guess % uInit = zeros(2,N); %uInit(1,:) = (0)*ones(1,N); % solve optimization options = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set','MaxFunEvals',3000,'ConstraintTolerance',1e-04); polyOptions = optimoptions('fmincon','Display','notify-detailed','algorithm','active-set'); [uopt ,fval,exitflag,output] = fmincon(@(u) Cost(x0_set,u,ts,target,L,terminalWeight),uGuess,A,b,Aeq,beq,lb,ub, @(u) ObstConstraint(x0_set,u,ts,xObst,threshold,L,polyOptions,EXP),options); %output; % return optimal input sequence end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
ObstConstraint.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/system/ObstConstraint.m
1,535
utf_8
2006293a6230997ad0315ff18f16d2a3
% [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold) % % defines the non linear constraint - agent polytope to maintain % a distance from the obstacle position above threshold function [c,ceq] = ObstConstraint(x0_set, u, ts, xObst, threshold,L,options,EXP) % predict agent with set based dynamics % coords X time X set points x_set = Dubin(x0_set, u, ts,L); % find distance between agent polytope and obstacle [mA,nA] = size(x_set); [mO,nO,pO] = size(xObst); ObstDist = zeros(1,pO*nA); obstDistCount = 1; for i = 1:nA % time for j = 1:pO % number of obstacles % format the agents set for polytope minimization for time step i xPolytope = zeros(2,4); xPolytope(:,:) = [x_set(1,i), x_set(1,i), x_set(2,i), x_set(2,i); x_set(3,i), x_set(4,i), x_set(3,i), x_set(4,i)]; oPolytope = zeros(2,4); oPolytope(:,:) = [xObst(1,i), xObst(1,i), xObst(2,i), xObst(2,i); xObst(3,i), xObst(4,i), xObst(3,i), xObst(4,i)]; if(EXP) ObstDist(obstDistCount) = PolytopeApproxDist(xPolytope,oPolytope); else ObstDist(obstDistCount) = PolytopeMinDist(xPolytope,oPolytope,options); end obstDistCount = obstDistCount+1; end end % calculate constraints c = -ObstDist+threshold; ceq = []; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SingleIntegrator.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/system/SingleIntegrator.m
412
utf_8
103d816561c56f118cee17686dc4c4c4
% x = SingleIntegrator(x0_set, u, ts) % % set based dynamics of single integrator function x = SingleIntegrator(x0_set, u, ts) [mP,nP] = size(x0_set); [mH,nH] = size(u); % coords X time X set points x = zeros(3,nH+1,nP); x(:,1,:) = x0_set; % apply integrator dynamics for j = 1:nP for i = 1:nH x(:,i+1,j) = x(:,i,j) + ts*u(:,i); end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
SimulationProjectilePredict.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/projectile/SimulationProjectilePredict.m
764
utf_8
8ea559140e8b2248afec5e16b1990cb5
% [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % % calls on simulink to predict projectile state given initial conditions function [trajectory, velocity] = SimulationProjectilePredict(p_0, simTime) % set up simulink set_param('projectile/rx','Value',num2str(p_0(1))); set_param('projectile/ry','Value',num2str(p_0(2))); set_param('projectile/rz','Value',num2str(p_0(3))); set_param('projectile/vx','Value',num2str(p_0(4))); set_param('projectile/vy','Value',num2str(p_0(5))); set_param('projectile/vz','Value',num2str(p_0(6))); set_param('projectile', 'StopTime', num2str(simTime)); % run simulation sim('projectile'); trajectory = projectilePos; velocity = projectileVel; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
CreateSphere.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/polytope/CreateSphere.m
913
utf_8
e7fc2c7730cbb8e66f70c29e702d9c20
% creates a point cloud in a sphere around the center function points = CreateSphere(center, r, thetadis, phidis) % angle discretization thetas = linspace(0,2*pi,thetadis); phis = linspace(0,pi,phidis); % point calculation points = []; x = []; y = []; z = []; for i = 1:length(phis) for j = 1:length(thetas) % removes duplicate point at theta = 2*pi if(thetas(j) == 2*pi) break end x = (r * sin(phis(i)) * cos(thetas(j))) + center(1); y = (r * sin(phis(i)) * sin(thetas(j))) + center(2); z = (r * cos(phis(i))) + center(3); nextPoint = [x;y;z]; points = [points, nextPoint]; % removes duplicate points at the top and bottom of sphere if(phis(i) == 0 || phis(i) == pi) break end end end end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeMinDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/polytope/PolytopeMinDist.m
1,162
utf_8
e97b9cd17ce23a47a127987797ca0206
% minDist = PolytopeMinDist(X1,X2) % % finds the minimum distance between two polytopes X1 and X2 function minDist = PolytopeMinDist(X1,X2,options) % declare constraints for fmincon lb = []; ub = []; % get sizes of vertices for polytopes [m1,n1] = size(X1); [m2,n2] = size(X2); if(m1 ~= m2) error('USER ERROR: Dimensions mistmatch'); end n = n1+n2; A = [eye(n); -eye(n)]; b = [ones(n,1); zeros(n,1)]; Aeq = [ones(1,n1) zeros(1,n2); zeros(1,n1) ones(1,n2)]; beq = [1;1]; nonlcon = []; % create lambda vectors x0 = zeros(n,1); x0(1) = 1; x0(n1+1) = 1; % declare function to be minimized %fun = @(lambda)(norm((X1 * lambda(1:n1))-(X2 * lambda(n1+1:n)))^2); % evaluate fmincon %x = fmincon(@(lambda) PolytopeDist(X1,X2,lambda,n1,n2,n),x0,A,b,Aeq,beq,lb,ub,nonlcon,options); [x,fval,exitflag,output] = fmincon(@(lambda) PolytopeDist(X1,X2,lambda,n1,n2,n),x0,A,b,Aeq,beq,lb,ub,nonlcon,options); %output % return min distance minDist = sqrt(PolytopeDist(X1,X2,x,n1,n2,n)); end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeApproxDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/polytope/PolytopeApproxDist.m
474
utf_8
7306751fed5e8ef4b13d8c2a2c0d62e5
function dist = PolytopeApproxDist(X1,X2) [m1,n1] = size(X1); [m2,n2] = size(X2); c1 = transpose(mean(transpose(X1))); c2 = transpose(mean(transpose(X2))); dist1 = zeros(n1,1); for i = 1:n1 dist1(i) = norm(X1(:,i)-c1); end dist2 = zeros(n2,1); for i = 1:n2 dist2(i) = norm(X2(:,i)-c2); end cDist = norm(c1-c2); d1 = max(dist1); d2 = max(dist2); dist = cDist-d1-d2; end
github
HybridSystemsLab/SetBasedPredictionCollisionAndEvasion-master
PolytopeDist.m
.m
SetBasedPredictionCollisionAndEvasion-master/CASE_Simulation/polytope/PolytopeDist.m
668
utf_8
34f5332d650d2fb60f349903cb7edf17
function [f,g] = PolytopeDist(X1,X2,lambda,n1,n2,n) f = norm((X1 * lambda(1:n1))-(X2 * lambda(n1+1:n)))^2; %{ g = zeros(n,1); for i = 1:n1 g(i) = 2*((X1(1,:)*lambda(1:n1))-(X2(1,:)*lambda(n1+1:n)))*X1(1,i) ... + 2*((X1(2,:)*lambda(1:n1))-(X2(2,:)*lambda(n1+1:n)))*X1(2,i) ... + 2*((X1(3,:)*lambda(1:n1))-(X2(3,:)*lambda(n1+1:n)))*X1(3,i); end for i = 1:n2 g(i) = 2*((X1(1,:)*lambda(1:n1))-(X2(1,:)*lambda(n1+1:n)))*(-X2(1,i)) ... + 2*((X1(2,:)*lambda(1:n1))-(X2(2,:)*lambda(n1+1:n)))*(-X2(2,i)) ... + 2*((X1(3,:)*lambda(1:n1))-(X2(3,:)*lambda(n1+1:n)))*(-X2(3,i)); end %} end
github
nasa/VirtualADAPT-master
FaultInjectionGUI.m
.m
VirtualADAPT-master/MATLAB/FaultInjectionGUI.m
17,252
utf_8
fee51603cf5f6ca78bf33120e3ef2a19
function varargout = FaultInjectionGUI(varargin) % FAULTINJECTIONGUI M-file for FaultInjectionGUI.fig % FAULTINJECTIONGUI, by itself, creates a new FAULTINJECTIONGUI or raises the existing % singleton*. % % H = FAULTINJECTIONGUI returns the handle to a new FAULTINJECTIONGUI or the handle to % the existing singleton*. % % FAULTINJECTIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in FAULTINJECTIONGUI.M with the given input arguments. % % FAULTINJECTIONGUI('Property','Value',...) creates a new FAULTINJECTIONGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before FaultInjectionGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to FaultInjectionGUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help FaultInjectionGUI % Last Modified by GUIDE v2.5 24-Jul-2012 07:36:36 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @FaultInjectionGUI_OpeningFcn, ... 'gui_OutputFcn', @FaultInjectionGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before FaultInjectionGUI is made visible. function FaultInjectionGUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to FaultInjectionGUI (see VARARGIN) % Choose default command line output for FaultInjectionGUI handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes FaultInjectionGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % clear out fault table %set(handles.faultTable,'Data',{}) ADAPTComponents; % loads 'components' variable % determine active fault modes in the sim and initialize faults table data = {}; count = 0; names = fieldnames(components); for i=1:length(names) component = names{i}; path = components.(component).path; % for each fault mode, check if it is present for j=1:length(components.(component).faultModes) faultPath = [path components.(component).paths{j}]; if ~strcmp(get_param(faultPath,'FP'),'Nominal') % add to table count = count+1; data{count,1} = component; data{count,2} = components.(component).faultModes{j}; data{count,3} = get_param(faultPath,'FT'); data{count,4} = get_param(faultPath,'FM'); end end end set(handles.faultTable,'Data',data); % put it here % contents = get(handles.component,'String'); % data{i,1} = contents{get(handles.component,'Value')}; % contents = get(handles.fault,'String'); % data{i,2} = contents{get(handles.fault,'Value')}; % data(i,3) = cellstr(get(handles.injection,'String')); % data(i,4) = cellstr(get(handles.magnitude,'String')); % set_param([components.(component).path components.(component).paths{faultIndex}],'FT',num2str(injectionTime)); % set_param([components.(component).path components.(component).paths{faultIndex}],'FM',num2str(magnitude)); % set_param([components.(component).path components.(component).paths{faultIndex}],'FP',components.(component).profiles(faultIndex)); % get user data userData = get(handles.figure1,'UserData'); userData.components = components; set(handles.figure1,'UserData',userData); % populate the component drop-down componentNames = sort(fieldnames(components)); set(handles.component,'String',componentNames); % populate the fault drop-down for the first fault updateFaultMode(handles); % function loadFaults(handles,parameters) % faultData = {}; % components = fieldnames(parameters.components); % for i=1:length(components) % component = components{i}; % tf = parameters.components.(component).tf; % if tf<Inf % magnitude = parameters.components.(component).magnitude; % faultMode = parameters.components.(component).faultMode; % faultModes = parameters.components.(component).faultModes; % % add to table % faultData{end+1,1} = component; % faultData{end,2} = faultModes{faultMode}; % faultData{end,3} = tf; % faultData{end,4} = magnitude; % end % end % set(handles.faultTable,'data',faultData); function updateFaultMode(handles) userData = get(handles.figure1,'UserData'); % get current component components = get(handles.component,'String'); component = components{get(handles.component,'Value')}; % set corresponding fault modes set(handles.fault,'Value',1); %set(handles.fault,'String',sort(userData.components.(component).faultModes)); set(handles.fault,'String',userData.components.(component).faultModes); % --- Outputs from this function are returned to the command line. function varargout = FaultInjectionGUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function expandColWidths(handles) colWidth = get(handles.faultTable,'ColumnWidth'); colWidth{1} = colWidth{1}+4; colWidth{2} = colWidth{2}+4; colWidth{3} = colWidth{3}+4; colWidth{4} = colWidth{4}+4; set(handles.faultTable,'ColumnWidth',colWidth) function contractColWidths(handles) colWidth = get(handles.faultTable,'ColumnWidth'); colWidth{1} = colWidth{1}-4; colWidth{2} = colWidth{2}-4; colWidth{3} = colWidth{3}-4; colWidth{4} = colWidth{4}-4; set(handles.faultTable,'ColumnWidth',colWidth) % --- Executes on button press in addFault. function addFault_Callback(hObject, eventdata, handles) % hObject handle to addFault (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % add current fault to faultTable userData = get(handles.figure1,'UserData'); data = get(handles.faultTable,'Data'); % if component is already in there, overwrite with new fault for i=1:size(data,1) contents = get(handles.component,'String'); if strcmp(data{i,1},contents{get(handles.component,'Value')}) % replace and return contents = get(handles.fault,'String'); data{i,2} = contents{get(handles.fault,'Value')}; data(i,3) = cellstr(get(handles.injection,'String')); data(i,4) = cellstr(get(handles.magnitude,'String')); set(handles.faultTable,'Data',data); % inject the fault addFault(userData,str2double(data{i,3}),data{i,1},data{i,2},str2double(data{i,4})); return end end % if data empty or need to make room, add a blank row if isempty(data) data{1,1} = ''; data{1,2} = ''; data{1,3} = ''; data{1,4} = ''; elseif ~isempty(data{size(data,1),1}) nextRow = size(data,1)+1; data{nextRow,1} = ''; data{nextRow,2} = ''; data{nextRow,3} = ''; data{nextRow,4} = ''; end % find first empty row and put fault info in there for i=1:size(data,1) if isempty(data{i,1}) % put it here contents = get(handles.component,'String'); data{i,1} = contents{get(handles.component,'Value')}; contents = get(handles.fault,'String'); data{i,2} = contents{get(handles.fault,'Value')}; data(i,3) = cellstr(get(handles.injection,'String')); data(i,4) = cellstr(get(handles.magnitude,'String')); % if have 5 rows, contract col widths to fit scrollbar if size(data,1)==5 contractColWidths(handles); end break; end end set(handles.faultTable,'Data',data); % inject the fault addFault(userData,str2double(data{i,3}),data{i,1},data{i,2},str2double(data{i,4})); % add fault function function addFault(userData,injectionTime,component,faultMode,magnitude) components = userData.components; % set this fault mode on [~,faultIndex] = ismember(faultMode,components.(component).faultModes); set_param([components.(component).path components.(component).paths{faultIndex}],'FT',num2str(injectionTime)); set_param([components.(component).path components.(component).paths{faultIndex}],'FM',num2str(magnitude)); set_param([components.(component).path components.(component).paths{faultIndex}],'FP',components.(component).profiles(faultIndex)); % set all other fault modes off for i=1:length(components.(component).faultModes) path = components.(component).paths{faultIndex}; if ~strcmp(components.(component).paths{i},path) faultMode = components.(component).faultModes{i}; removeFault(userData,component,faultMode); end end % remove fault function function removeFault(userData,component,faultMode) components = userData.components; [~,faultIndex] = ismember(faultMode,components.(component).faultModes); set_param([components.(component).path components.(component).paths{faultIndex}],'FT',num2str(0)); set_param([components.(component).path components.(component).paths{faultIndex}],'FP',0); % reset to nominal function function resetToNominal(userData) components = userData.components; names = fieldnames(components); for i=1:length(names) component = names{i}; for j=1:length(components.(component).faultModes) faultMode = components.(component).faultModes{j}; removeFault(userData,component,faultMode); end end % --- Executes on button press in removeFault. function removeFault_Callback(hObject, eventdata, handles) % hObject handle to removeFault (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1,'UserData'); data = get(handles.faultTable,'Data'); % get row number of selected cell row = get(handles.faultTable,'UserData'); if isempty(row) || row>size(data,1) % nothing or phantom row selected if size(data,1)==1 %if only 1 entry, select him row = 1; else % else nothing selected and multiple entries, do nothing return; end end if isempty(data) return; elseif ~isempty(data{row,1}) % remove fault removeFault(userData,data{row,1},data{row,2}); % then remove this row data(row,:) = []; set(handles.faultTable,'Data',data); end % if now has 4 rows then expand col widths if size(data,1)==4 expandColWidths(handles); end % --- Executes on button press in resetToNominal. function resetToNominal_Callback(hObject, eventdata, handles) % hObject handle to resetToNominal (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) userData = get(handles.figure1,'UserData'); data = get(handles.faultTable,'Data'); % if have >3 faults want to expand the col widths b/c scrollbar will % disappear if size(data,1)>5 expandColWidths(handles); end data = {}; set(handles.faultTable,'Data',data); % reset to nominal resetToNominal(userData); function injection_Callback(hObject, eventdata, handles) % hObject handle to injection (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of injection as text % str2double(get(hObject,'String')) returns contents of injection as a double % --- Executes during object creation, after setting all properties. function injection_CreateFcn(hObject, eventdata, handles) % hObject handle to injection (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function magnitude_Callback(hObject, eventdata, handles) % hObject handle to magnitude (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of magnitude as text % str2double(get(hObject,'String')) returns contents of magnitude as a double % --- Executes during object creation, after setting all properties. function magnitude_CreateFcn(hObject, eventdata, handles) % hObject handle to magnitude (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in component. function component_Callback(hObject, eventdata, handles) % hObject handle to component (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns component contents as cell array % contents{get(hObject,'Value')} returns selected item from component updateFaultMode(handles); % --- Executes during object creation, after setting all properties. function component_CreateFcn(hObject, eventdata, handles) % hObject handle to component (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in fault. function fault_Callback(hObject, eventdata, handles) % hObject handle to fault (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns fault contents as cell array % contents{get(hObject,'Value')} returns selected item from fault % --- Executes during object creation, after setting all properties. function fault_CreateFcn(hObject, eventdata, handles) % hObject handle to fault (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes when selected cell(s) is changed in faultTable. function faultTable_CellSelectionCallback(hObject, eventdata, handles) % hObject handle to faultTable (see GCBO) % eventdata structure with the following fields (see UITABLE) % Indices: row and column indices of the cell(s) currently selecteds % handles structure with handles and user data (see GUIDATA) if size(eventdata.Indices,1)>0 set(hObject,'UserData',eventdata.Indices(1)) end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); % --- Executes on button press in saveConfig. function saveConfig_Callback(hObject, eventdata, handles) % hObject handle to saveConfig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % save what is in fault table data = get(handles.faultTable,'Data'); uisave('data','config.mat'); % --- Executes on button press in loadConfig. function loadConfig_Callback(hObject, eventdata, handles) % hObject handle to loadConfig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [filename pathname] = uigetfile('*.mat'); if filename~=0 load([pathname filename]); % inject each fault in config file for i=1:size(data,1) component = data{i,1}; faultMode = data{i,2}; injectionTime = data{i,3}; magnitude = data{i,4}; userData = get(handles.figure1,'UserData'); addFault(userData,injectionTime,component,faultMode,magnitude) end set(handles.faultTable,'Data',data); end
github
xhuang31/LANE-master
Performance.m
.m
LANE-master/Performance.m
3,202
utf_8
ad6f8f3b492868c911c6b76ecf5768ec
function [F1macro,F1micro] = Performance(Xtrain,Xtest,Ytrain,Ytest) %Evaluate the performance of classification for both multi-class and multi-label Classification % [F1macro,F1micro] = Performance(Xtrain,Xtest,Ytrain,Ytest) % % Xtrain is the training data with row denotes instances, column denotes features % Xtest is the test data with row denotes instances, column denotes features % Ytrain is the training labels with row denotes instances % Ytest is the test labels % Copyright 2017, Xiao Huang and Jundong Li. % $Revision: 1.0.0 $ $Date: 2017/10/18 00:00:00 $ %% Multi class Classification if size(Ytrain,2) == 1 && length(unique(Ytrain)) > 2 t = templateSVM('Standardize',true); model = fitcecoc(Xtrain,Ytrain,'Learners',t); pred_label = predict(model,Xtest); [micro, macro] = micro_macro_PR(pred_label,Ytest); F1macro = macro.fscore; F1micro = micro.fscore; else %% For multi-label classification, computer micro and macro rng default % For repeatability NumLabel = size(Ytest,2); macroTP = zeros(NumLabel,1); macroFP = zeros(NumLabel,1); macroFN = zeros(NumLabel,1); macroF = zeros(NumLabel,1); for i = 1:NumLabel model = fitcsvm(Xtrain,Ytrain(:,i),'Standardize',true,'KernelFunction','RBF','KernelScale','auto'); pred_label = predict(model,Xtest); mat = confusionmat(Ytest(:,i), pred_label); if size(mat,1) == 1 macroTP(i) = sum(pred_label); macroFP(i) = 0; macroFN(i) = 0; if macroTP(i) ~= 0 macroF(i) = 1; end else macroTP(i) = mat(2,2); macroFP(i) = mat(1,2); macroFN(i) = mat(2,1); macroF(i) = 2*macroTP(i)/(2*macroTP(i)+macroFP(i)+macroFN(i)); end end F1macro = mean(macroF); F1micro = 2*sum(macroTP)/(2*sum(macroTP)+sum(macroFP)+sum(macroFN)); end end function [micro, macro] = micro_macro_PR(pred_label,orig_label) % computer micro and macro: precision, recall and fscore mat = confusionmat(orig_label, pred_label); len = size(mat,1); macroTP = zeros(len,1); macroFP = zeros(len,1); macroFN = zeros(len,1); macroP = zeros(len,1); macroR = zeros(len,1); macroF = zeros(len,1); for i = 1:len macroTP(i) = mat(i,i); macroFP(i) = sum(mat(:, i))-mat(i,i); macroFN(i) = sum(mat(i,:))-mat(i,i); macroP(i) = macroTP(i)/(macroTP(i)+macroFP(i)); macroR(i) = macroTP(i)/(macroTP(i)+macroFN(i)); macroF(i) = 2*macroP(i)*macroR(i)/(macroP(i)+macroR(i)); end % macroP(isnan(macroP)) = 0; % macroR(isnan(macroR)) = 0; macroF(isnan(macroF)) = 0; % macro.precision = mean(macroP); % macro.recall = mean(macroR); macro.fscore = mean(macroF); micro.precision = sum(macroTP)/(sum(macroTP)+sum(macroFP)); micro.recall = sum(macroTP)/(sum(macroTP)+sum(macroFN)); micro.fscore = 2*micro.precision*micro.recall/(micro.precision+micro.recall); end
github
SakaSerbia/MATLAB-Filter-ECG-signal-and-FIR-direct-transposed-Homework-number-3-master
FIR_direct_transpose.m
.m
MATLAB-Filter-ECG-signal-and-FIR-direct-transposed-Homework-number-3-master/FIR_direct_transpose.m
1,257
utf_8
739f3ed8f5d294dc952ee4d7951be1ca
%Teorija %Transpozicija se vrsi tako sto ulazni i izlazni signali promene mesta, %svim granama se promeni smer, cvorovi granjanja postanu sabiraci, a %sabiraci postanu tacke granjanja. %Dodatna objasnjenja MIT OpenCourseWare http://ocw.mit.edu %Signal Processing: Continuous and Discrete, Fall 2008 function [ y ] = FIR_direct_transpose( h, x) % function [ y ] = FIR_direct( b, x ) % %FIR_DIREXT Function that implements direct realizaton of FIR filter % delay_line = zeros(length(b),1); % if isfi(b) % delay_line = fi( delay_line, b.Signed, b.WordLength, b.FractionLength); % end; % % for k = 1:length(x) % delay_line = [x(k); delay_line(1:end-1)]; % accumulator_contents = b*delay_line; % y(k) = accumulator_contents; % end % end delay_line = zeros(1,length(h)-1); if isfi(h) delay_line = fi( delay_line, h.Signed, h.WordLength, h.FractionLength); end y = zeros(1,length(x)); for k=1:length(x) accumulator_contents = fliplr(h)*x(k); y(k) = accumulator_contents(length(accumulator_contents)) + delay_line(length(delay_line)); delay_line=[accumulator_contents(1),accumulator_contents(2:length(accumulator_contents)-1)+delay_line(1:length(delay_line)-1)]; end end
github
JenifferWuUCLA/DSB2017-1-master
label_stage1.m
.m
DSB2017-1-master/training/detector/labels/label_stage1.m
4,931
utf_8
a9fdc8773cd38b8f717beaf07df746ff
clear clc close all lungwindow = [-1900,1100]; lumTrans = @(x) uint8((x-lungwindow(1))/(diff(lungwindow))*256); path = 'E:\Kaggle.Data\stage1'; cases = dir(path); cases = {cases.name}; cases = cases(3:end); header = {'id', 'coordx1','coordx1','coordx1','diameter'}; labelfile = 'label_job2.csv'; if ~ exist(labelfile) initial_label = header; for i = 1:length(cases) initial_label = [initial_label;{cases{i},'x','x','x','x'}]; end cell2csv(labelfile,initial_label) label_tabel = initial_label; else label_tabel = csv2cell(labelfile,'fromfile'); end label_tabel = label_tabel(2:end,:); fullnamelist = label_tabel(:,1); uniqueNameList = unique(fullnamelist, 'stable'); % uniqueNameList = fullnamelist(ismember(fullnamelist, uniqueNameList)); annos = label_tabel(:,2:end); for i = 1:size(fullnamelist) if annos{i,1}=='x' lineid = i; name = fullnamelist{i}; id = find(strcmp(uniqueNameList,name)); break end end for id = id:length(uniqueNameList) name = uniqueNameList{id}; disp(name) found = 0; folder = [path,'/',name]; % info = dicom_folder_info(folder); im = dicomfolder(folder); imint8 = lumTrans(im); rgbim = repmat(imint8,[1,1,1,3]); h1 = figure(1); imshow3D(rgbim) while 1 in = input('add_square(a), add_diameter(b), delete_last(d), or next(n):','s'); if in =='n' if found==0 label_tabel(lineid,:) = {name,0,0,0,0}; lineid = lineid+1; end break elseif in =='d' found = found-1; lineid = lineid-1; if found ==0 label_tabel(lineid,:) = {name,'x','x','x','x'}; elseif found>0 label_tabel(lineid,:) = []; else disp('invalid delete') end if found>=0 rgbim=rgbim_back; imshow3D(rgbim) end figure(1); elseif strcmp(in,'a')||strcmp(in,'b') if found==0 label_tabel(lineid,:) = []; end if strcmp(in,'a') anno = label_rect(im); elseif strcmp(in,'b') anno = label_line(); end found=found+1; label_tabel= [label_tabel(1:lineid-1,:);{name,anno(1),anno(2),anno(3),anno(4)};label_tabel(lineid:end,:)]; lineid = lineid+1; rgbim_back = rgbim; rgbim = drawRect(rgbim,anno,1); imshow3D(rgbim) else figure(1); continue end % disp(label_tabel(max([1, (lineid - 4)]):lineid,:)) end fulltable = [header;label_tabel]; cell2csv(labelfile,fulltable) end function [anno] = label_line() h_obj=imline; pos = getPosition(h_obj); center = mean(pos,1); diameter = sqrt(sum(diff(pos).^2)); h = gcf; strtmp = strsplit(h.Children(8).String,' '); id_layer = str2num(strtmp{2}); anno = [center,id_layer,diameter]; h_obj.delete() end function [anno] = label_rect(im) h = gcf; h_rect=imrect; label_pos = round(getPosition (h_rect)); mask = createMask(h_rect); strtmp = strsplit(h.Children(8).String,' '); id_layer = str2num(strtmp{2}); im_layer = squeeze( im(:,:,id_layer)); patch = im_layer(label_pos(2):label_pos(2)+label_pos(4),label_pos(1):label_pos(1)+label_pos(3)); bw = patch>-600; se = strel('disk',round(label_pos(3)/12)); bw2 = imopen(bw,se); re = regionprops(bw2,'PixelIdxList','area','centroid'); if isempty(re) disp('wrong place') h_rect.delete() anno = label_rect(im); return end areas = [re.Area]; [bigarea,id_re] = max(areas); bw3 = bw2-bw2; bw3(re(id_re).PixelIdxList)=1; h2 = figure(2); imshow(bw3) pause(1) h2.delete(); diameter = (bigarea/pi).^0.5*2; centroid = re(id_re).Centroid+label_pos(1:2); anno = [centroid,id_layer,diameter]; h_rect.delete() end function rgbim = drawRect(rgbim,tmpannos,channel) n_annos = size(tmpannos,1); newim = squeeze(rgbim(:,:,:,channel)); for i_annos = 1:n_annos coord = tmpannos(i_annos,1:3); diameter = tmpannos(i_annos,4); layer = round(coord(3)); zspan = 2; newimtmp = newim(:,:,layer-zspan:layer+zspan); if diameter > 40 coeff = 1.5; else coeff= 2; end newimtmp = drawRectangleOnImg(round([coord(1:2)-diameter*coeff/2,diameter*coeff,diameter*coeff]),newimtmp); newim(:,:,layer-zspan:layer+zspan) = newimtmp; end rgbim(:,:,:,channel)=newim; end function rgbI = drawRectangleOnImg (box,rgbI) x = box(2); y = box(1); w = box(4); h = box(3); rgbI(x:x+w,y,:) = 255; rgbI(x:x+w,y+h,:) = 255; rgbI(x,y:y+h,:) = 255; rgbI(x+w,y:y+h,:) = 255; end % dicom_folder_info
github
pascal220/PMSM_Control-master
MPCController.m
.m
PMSM_Control-master/Model Predictive Control/MPCtools-1.0/MPCtools-1.0/MPCController.m
4,302
utf_8
66841584b3d48bab415e1eaafb795dad
function [sys,x0,str,ts] = MPCController(t,x,u,flag,md) % % [sys,x0,str,ts] = MPCController(t,x,u,flag,md) % % is an S-function implementing the MPC controller intended for use % with Simulink. The argument md, which is the only user supplied % argument, contains the data structures needed by the controller. The % input to the S-function block is a vector signal consisting of the % measured outputs and the reference values for the controlled % outputs. The output of the S-function block is a vector signal % consisting of the control variables and the estimated state vector, % potentially including estimated disturbance states. switch flag, case 0 [sys,x0,str,ts] = mdlInitializeSizes(md); % Initialization case 2 sys = mdlUpdates(t,x,u,md); % Update discrete states case 3 sys = mdlOutputs(t,x,u,md); % Calculate outputs case {1, 4, 9} % Unused flags sys = []; otherwise error(['unhandled flag = ',num2str(flag)]); % Error handling end % End of dsfunc. %============================================================== % Initialization %============================================================== function [sys,x0,str,ts] = mdlInitializeSizes(md) % Call simsizes for a sizes structure, fill it in, and convert it % to a sizes array. sizes = simsizes; sizes.NumContStates = 0; sizes.NumDiscStates = md.ne + md.pye + md.me + md.Hu*md.me; sizes.NumOutputs = md.me+md.ne; sizes.NumInputs = md.pye+md.pz; sizes.DirFeedthrough = 1; % Matrix D is non-empty. sizes.NumSampleTimes = 1; sys = simsizes(sizes); x0 = zeros(md.ne + md.pye + md.me + md.Hu*md.me,1); global x; x = zeros(md.ne + md.pye + md.me + md.Hu*md.me,1); % Initialize the discrete states. str = []; % Set str to an empty matrix. ts = [md.h 0]; % sample time: [period, offset] % End of mdlInitializeSizes %============================================================== % Update the discrete states %============================================================== function sys = mdlUpdates(t,x,u,md) sys = x; % End of mdlUpdate. %============================================================== % Calculate outputs %============================================================== function sys = mdlOutputs(t,x_i,u,md) global x; fprintf('Update start, t=%4.2f\n',t) x_hat = x(1:md.ne,:); y_old = x(md.ne+1:md.ne+md.pye,:); u_old = x(md.ne+md.pye+1:md.ne+md.pye+md.me,:); duOpt = x(md.ne+md.pye+md.me+1:md.ne+md.pye+md.me+md.me*md.Hu,:); y_plant = u(1:md.pye,:); r = u(md.pye+1:md.pye+md.pz); % Get observer values if md.cmode == 0, x_hat(1:md.n) = y_plant; refval = r; elseif md.cmode == 1; % State feedback x_hat(1:md.n) = y_plant; % Take care of integrator states x_hat(md.n+1:md.n+md.nbr_int) = x_hat(md.n+1:md.n+md.nbr_int) + ... r(1:md.nbr_int) - md.Czde(1:md.nbr_int,1:md.n)*x_hat(1:md.n); refval = [r' zeros(1,md.nbr_int)]'; elseif md.cmode == 2; % Update Observer x_hat = md.Ade*x_hat + md.Bde*u_old + md.K*(y_old - md.Cyde* ... x_hat); y_old = y_plant; refval = r; elseif md.cmode == 3; % Notice that it is assumed that the first pz entriew of y is % actually the controlled outputs! % Take care of integrator states x_hat(md.n+1:md.n+md.nbr_int) = x_hat(md.n+1:md.n+md.nbr_int) + ... r(1:md.nbr_int) - y_plant(1:md.nbr_int); % Update observer x_hat(1:md.n) = md.Ade(1:md.n,1:md.n)*x_hat(1:md.n) + ... md.Bde(1:md.n,:)*u_old +... md.K*(y_old - md.Cyde(:,1:md.n)*x_hat(1:md.n)); y_old = y_plant; % Set reference value refval = [r' zeros(1,md.nbr_int)]'; elseif md.cmode == 4; % Update observer x_hat = md.Ade*x_hat + md.Bde*u_old + md.K*(y_old - md.Cyde* ... x_hat); y_old = y_plant; %set reference value refval = r; end % Optimize %[duOpt,zOpt] = MPCOptimizeSolSC(x_hat,u_old,duOpt,refval,md); [duOpt,zOpt] = MPCOptimizeSol(x_hat,u_old,duOpt,refval,md); % Calculate control signal to store u_old = u_old + duOpt(1:md.me); x(1:md.ne,1) = x_hat; x(md.ne+1:md.ne+md.pye,:) = y_old; x(md.ne+md.pye+1:md.ne+md.pye+md.me,:) = u_old; x(md.ne+md.pye+md.me+1:md.ne+md.pye+md.me+md.me*md.Hu,:) = duOpt; sys = [x(md.ne+md.pye+1:md.ne+md.pye+md.me,:); x(1:md.ne,1);]; % End of mdlOutputs.
github
pascal220/PMSM_Control-master
ssmpc_simulate.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/ssmpc_simulate.m
5,037
utf_8
fe5c0e959b026751851ad7d07bfcc69a
%%% Simulation of dual mode optimal predictive control %%% %% [x,y,u,c,r] = ssmpc_simulate(A,B,C,D,Q,R,umax,umin,Kxmax,xmax,nc,x0,ref,dist,noise) %% %%% x(k+1) = A x(k) + B u(k) x0 is the initial condition %%% y(k) = C x(k) + D u(k) + dist Note: Assumes D=0, dist unknown %%% %% input constraint umax, umin %% state constraints | Kxmax x | < xmax %% reference trajectory ref, r %% perturbation to control c %% Number of d.o.f. nc %% Weighting matrices in J Q, R %% measurement noise noise %% %% Author: J.A. Rossiter (email: [email protected]) function [x,y,u,c,r] = ssmpc_simulate(A,B,C,D,Q,R,umax,umin,Kxmax,xmax,nc,x0,ref,dist,noise) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Find L2 optimal control law and observor with integrator %%%%% Control law is written as %%%%% %%%% Control law is u = -Knew z + Pr r + c %%%% %%%%% Observor is z = Ao*z +Bo*u + L*(y + noise - Co*z ); z=[xhat;dhat] %%%%% %%%%% K the underlying control law: u-uss = -K(x-xss) [K,L,Ao,Bo,Co,Do,Knew,Pr] = ssmpc_observor(A,B,C,D,Q,R); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% To set up prediction matrices for dual mode state space MPC %%%%% Assume closed-loop predictions %%%%% x = Pc1*c + Pz1*z + Pr1*r z=[x;d] %%%%% u = Pc2*c + Pz2*z + Pr2*r %%%%% y = Pc3*c + Pz3*z + Pr3*r [Pc1,Pc2,Pc3,Pz1,Pz2,Pz3,Pr1,Pr2,Pr3] = ssmpc_predclp(A,B,C,D,Knew,Pr,nc); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% The optimal cost is %%%%% J = c'Sc + c'X + unconstrained optimal [S] = ssmpc_costfunction(A,B,K,nc,Q,R); S=(S+S')/2; X = zeros(nc*size(B,2),1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Constraints are summarised as %%%%% CC c - dfixed - dx0*[z;r;d] <= 0 d is a known disturbance [CC,dfixed,dx0] = ssmpc_constraints(Pc1,Pc2,Pz1,Pz2,Pr1,Pr2,umin,umax,Kxmax,xmax); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% SIMULATION %%%%%%%%%% Initial Conditions nu=size(B,2); c = zeros(nu*nc,2); u =zeros(nu,2); y=zeros(nu,2); x=[x0,x0]; z = [x;y]; r=ref; nK = size(Kxmax,1); runtime = size(ref,2)-1; opt = optimset; opt.Display='off'; %'notify'; opt.Diagnostics='off'; opt.LargeScale='off'; for i=2:runtime; %%%%%%%%%%%%%%% CONSTRAINT HANDLING PART c(:,i+1) = c(:,i); c(:,i) = quadprog(S,X,CC,dfixed+dx0*[z(:,i);r(:,i)],[],[],[],[],[],opt); %%%%% Control law u(:,i) = -Knew*z(:,i) + c(1:nu,i) + Pr*r(:,i); %%%%% Physical constraint check for j=1:nu; if u(j,i) > umax(j); u(j,i) = umax(j); end if u(j,i) < umin(j); u(j,i) = umin(j); end end %%%% Simulate model x(:,i+1) = A*x(:,i) + B*u(:,i) ; y(:,i+1) = C*x(:,i+1) + dist(:,i+1); %%%% Observer part z(:,i+1) = Ao*z(:,i) +Bo*u(:,i) + L*(y(:,i) + noise(:,i) - Co*z(:,i)); end %%%% Ensure all variables have conformal lengths u(:,i+1) = u(:,i); c(:,i+1)=c(:,i); r = r(:,1:i+1); noise = noise(:,1:i+1); d = dist(:,1:i+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Produce a neat plot time=0:size(u,2)-1; for i=1:nu; figure(i);clf reset plotall(y(i,:),r(i,:),u(i,:),c(i,:),d(i,:),noise(i,:),umax(i),umin(i),time,i); end disp('**************************************************'); disp(['*** There are ',num2str(nu),' figures ***']); disp('**************************************************'); %%%%% Function to do plotting in the MIMO case and %%%%% allow a small boundary around each plot function plotall(y,r,u,c,d,noise,umax,umin,time,loop) uupper = [umax,umax]'; ulower = [umin,umin]'; time2 = [0,time(end)]; rangeu = (max(umax)-min(umin))/20; rangey = (max(max(y))-min(min(y)))/20; ranged = (max(max([d,noise]))-min(min([d,noise])))/20;if ranged==0;ranged=1;end rangec = (max(c)-min(c))/20; if rangec==0;rangec=1;end subplot(221);plot(time,y','-',time,r','--'); axis([time2,min(min(y))-rangey,max(max(y))+rangey]); xlabel(['LQMPC - Outputs and set-point in loop ',num2str(loop)]); subplot(222);plot(time,c','-'); axis([time2,min(c)-rangec,max(c)+rangec]); xlabel(['LQMPC - Input perturbations in loop ',num2str(loop)]); subplot(223);plot(time,u','-',time2,uupper,'--',time2,ulower,'--'); axis([time2,min(umin)-rangeu,max(umax)+rangeu]); xlabel(['LQMPC - Inputs in loop ',num2str(loop)]); subplot(224);plot(time,d','b',time,noise,'g'); axis([time2,min(min([d,noise]))-ranged,max(max([d,noise]))+ranged]); xlabel(['LQMPC - Disturbance/noise in loop ',num2str(loop)]);
github
pascal220/PMSM_Control-master
mpc_predtfilt.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/mpc_predtfilt.m
1,025
utf_8
930a72b67ebbc32559919cf286a96a67
%%% To find the prediction matrices with a T-filter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% yfut = H*Dufut + Pt*Dut + Qt*yt %%% %%% Dut = Du/Tfilt yt = y/Tfilt %%% %%% GIVEN yfut = H *Dufut + P*Dupast + Q*ypast %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% [Pt,Qt] = mpc_predtfilt(H,P,Q,Tfilt,sizey,ny); %%% %%% sizey is the dimension of y %%% ny is the output horizon %%% Tfilt - parameters of the T-filter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %% Author: J.A. Rossiter (email: [email protected]) function [Pt,Qt] = mpc_predtfilt(H,P,Q,Tfilt,sizey,ny); [Ct,Ht] = caha(Tfilt,sizey,ny); Pt = Ct*P; Qt =Ct*Q; nT = size(Tfilt,2)/sizey; %% Therefore Ht has nT-1 block columns np2 = size(Pt,2)/sizey; np3 = size(Qt,2)/sizey; if np2<nT-1; Pt(1,sizey*(nT-1))=0;end if np3<nT-1; Qt(1,sizey*(nT-1))=0;end Pt(:,1:sizey*(nT-1)) = Pt(:,1:sizey*(nT-1)) - H*Ht; Qt(:,1:sizey*(nT-1)) = Qt(:,1:sizey*(nT-1)) + Ht;
github
pascal220/PMSM_Control-master
imgpc_costfunction.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/imgpc_costfunction.m
1,783
utf_8
43ab78f5ad32ef078482ebd990bd1682
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Find a predictive control law and optimal cost given predictions %%%% yfut = P*xfut+H*ufut+L*offset %%%% uss = M(r-offset) %%%% %%%% Uses the cost function J = sum (r-y)^2 + R(u-uss)^2 %%%% J = ufut'*S*ufut + 2 ufut'*X*[x;r-offset] + k %%%% %%%% Cost weights absolute inputs (not increments) so need assumption %%%% u(k+nu+i) = u(k+nu-1) in predictions %%%% %%%% Control weighting R %%%% Control/ouput horizon nu, ny %%%% Output dimension sizey %%%% %%%% Control law is %%%% ufut = -K*x + Pr*(r-offset) (No advance knowledge is used) %%%% %%%% [S,X,K,Pr] = imgpc_costfunction(H,P,L,M,R,nu,sizey,ny); %% %% Author: J.A. Rossiter (email: [email protected]) function [S,X,K,Pr,H] = imgpc_costfunction(H,P,L,M,R,nu,sizey,ny); %% J = | Lr - P x- H ufut - L*offset | + R |ufut-uss| %% J = | Lr - P x- H ufut - L*offset | + R |ufut - M*(r-offset)| %%% Sum last columns of H v=(nu-1)*sizey; for k=1:sizey; HH(:,k) = sum(H(:,v+k:sizey:end),2); end H = [H(:,1:(nu-1)*sizey),HH]; %%% Form weighting matrix and uss matrix MM=[]; for k=1:nu; v = (k-1)*sizey+1:k*sizey; RR(v,v)=R; MM=[MM;M]; end %%%% Cost function %% J = | L*r - P x- H ufut - L*offset | + R |ufut - MM*(r-offset)| %% J = ufut'*S*ufut + 2 ufut'*X*[x;r-offset] + k %% = ufut'(H'H+R)ufut + 2ufut'* H'*P*x + 2ufut'*H'*L*(offset-r) %% - 2*ufut'R*MM*(r-offset) + k S = H'*H+RR; X1 = H'*P; X2 = -H'*L-RR*MM; X=[X1,X2]; %%%% Unconstrained control law %%%% ufut = -K*x + Pr*(r-offset) (No advance knowledge is used) Mi=inv(S); K = Mi*X1; Pr = -Mi*X2;
github
pascal220/PMSM_Control-master
mpc_law.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/mpc_law.m
1,464
utf_8
ad7c22af39298911ea7d46ec1708387c
%%%% Compute MPC control law given the prediction matrices %%%% Assumes: (i) u constant after nu steps %%%% (ii) predictions given as %%%% y = H*Du(future) + P*Du(past) + Q*y(past) %%%% (iii) weights on cost are Wy (outputs), Wu (inputs) %%%% (iv) sizey is the number of outputs %%%% %%%% Performance index is given as %%%% J = Du(future)' S Du(future) + Du(future)'*2X*[Du(past);y(past);r] %%%% %%%% Control law is given as %%%% Du(future) = Pr*r - Dk*Du(past) - Nk*y(past) %%%% %%%% Pr is given as a simple gain (edit this code to reinstitute advance knowledge) %%%% %%%% [Nk,Dk,Pr,S,X] =mpc_law(H,P,Q,nu,Wu,Wy,sizey) %% %% Author: J.A. Rossiter (email: [email protected]) function [Nk,Dk,Pr,S,X] =mpc_law(H,P,Q,nu,Wu,Wy,sizey) %%%% Control horizon P1 = H(:,1:sizey*nu); %% Set up weighting matrices WY=Wy; WU=Wu; L = eye(sizey); npred = size(P1,1)/sizey; for i = 2:npred; v=(i-1)*sizey+1:i*sizey; WY(v,v) = Wy; WU(v,v) = Wu; L = [L;eye(sizey)]; end WU = WU(1:nu*sizey,1:nu*sizey); %%% Define performance index parameters S = P1'*WY*P1 + WU; X = [P1'*WY*P,P1'*WY*Q,-P1'*WY]; %%%% Define the control law parameters M = inv(S); Nk = M*P1'*WY*Q; Dk = M*P1'*WY*P; Pr = M*P1'*WY; %%%%% Remove advance knowledge on the set point Pr = Pr*L; X = [P1'*WY*P,P1'*WY*Q,-P1'*WY*L];
github
pascal220/PMSM_Control-master
summary.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/summary.m
1,130
utf_8
0706ed07547ce1a03d5147827795e39f
FILES IN SUPPORT OF: Model-based predictive control: a practical approach, by J.A. Rossiter These files are intended as a support to this book to enable students to investigate predictive control algorithms from the formulation of the prediction equations right through to the closed-loop simulation. The code is mostly elementary MATLAB and is also transparent in structure. Hence the files form useful templates for algorithm modifications or to formulate the precise scenario or plots desired. Example files are provided to facilitate this. Some files allow for transfer function models and some for state space models and they cater for both SISO and MIMO processes and include systematic constraint handling. Most files do not use any MATLAB toolboxes but the few exceptions can easily be editted out with a small loss in functionality. The files are provided free of charge and as such no guarantee is given as to their behaviour nor are they intended to be comprehensive. However, USERS are invited to contact the author if they discover either bugs or wish to suggest useful improvements.
github
pascal220/PMSM_Control-master
mpc_simulate.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/mpc_simulate.m
6,141
utf_8
8a8b31fbc04bc0109e3963b34a0c1ffc
%%%%%%%%%%%%%% Either: (NO T-filter!!) %%%%%%%%%%%%%% (1) Gives control law parameters (nargin = 6 only) %%%%%%%%%%%%%% (2) Simulates MIMO GPC with constraint handling %%% %%%%% [Nk,Dk,Pr] = mpc_simulate(B,A,nu,ny,Wu,Wy) %%%%% Du(k) = Pr*r(k+1) - Dk*Du(k-1) - Nk*y(k) %% %%%%% [y,u,Du,r] = mpc_simulate(B,A,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) % y, u, Du, r are dimensionally compatible % closed-loop outputs/inputs/input increments and supplied set-point and disturbance % % MFD model Ay(k) = Bu(k-1) + dist % % ny is output horizon % nu is the input horizon % Wu is the diagonal control weighting % Wy is the diagonal output weighting % sizey no. outputs and inputs (assumed square) % dist,noise are the disturbance and noise signals % ref is the reference signal % Dumax is a vector of limits on input increments (assumed symetric) % umax, umin are vectors of limits on the inputs % % [y,u,Du,r,d] = mpc_simulate(B,A,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) %% %% Author: J.A. Rossiter (email: [email protected]) function [y,u,Du,r] = mpc_simulate(B,A,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Error checks sizey = size(A,1); if size(B,2)==sizey;B=[B,zeros(sizey,sizey)];end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Find prediction matrices %%%% yfut = H *Dufut + P*Dupast + Q*ypast [H,P,Q] = mpc_predmat(A,B,ny); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Find control law and parameters of the cost function %%%% Dufut = Pr*rfut - Dk*Dupast - Nk*ypast %%%% J = Dufut'*S*Dufut + Dufut'*2X*[Dupast;ypast;rfut] [Nk,Dk,Pr,S,X] = mpc_law(H,P,Q,nu,Wu,Wy,sizey); if nargin==6; %%%% collect control law and stop y=Nk(1:sizey,:); u=Dk(1:sizey,:); Du=Pr(1:sizey,:); else %%%% continue to simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin~=12;disp('Incomplete input information - stopping');break;end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%% Define constraint matrices %%%%%% CC*Dufut - dd - dd1*ut <= 0 [CC,dd,dd1] = mpc_constraints(Dumax,umax,umin,sizey,nu); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Set up simulation parameters nNk = size(Nk,2)/sizey; nDk = size(Dk,2)/sizey; init = max([nNk,nDk])+2; y = zeros(sizey,init); u = y; Du = u; r = u; d=u; opt = optimset('quadprog'); opt.Diagnostics='off'; %%%%% Switches of unwanted MATLAB displays opt.LargeScale='off'; %%%%% However no warning of infeasibility opt.Display='off'; runtime = size(ref,2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% Closed-loop simulation for i=init:runtime-1; %%% Update unconstrained control law d(1:sizey,i+1)=dist(:,i+1); ypast = y(:, i:-1:i+1-nNk)+noise(:, i:-1:i+1-nNk); Dupast = Du(:, i-1:-1:i-nDk) ; upast = u(:, i-1); rfut = ref(:,i+1); %%%%%%% Unconstrained law - if needed Dufast = Pr*rfut - Nk*ypast(:) - Dk*Dupast(:); % Form constraint matrices and solve constrained optimisation % CC*Dufast-dd-dd1*upast <=0; dt = dd+dd1*upast; Dufast2 = quadprog(S,X*[Dupast(:);ypast(:);rfut(:)],CC,dt,[],[],[],[],[],opt); Du(:,i) = Dufast2(1:sizey); u(:,i) = u(:,i-1)+Du(:,i); % Ensure the constraints satisfied by proposed control law for j=1:sizey; if u(j,i)>u(j,i-1)+Dumax(j);u(j,i)=u(j,i-1)+Dumax(j);end if u(j,i)<u(j,i-1)-Dumax(j);u(j,i)=u(j,i-1)-Dumax(j);end if u(j,i)>umax(j); u(i)=umax(j);end if u(j,i)<umin(j); u(i)=umin(j);end end Du(:,i) = u(:,i)-u(:,i-1); %%% End of update to the control law %%% Simulate the process upast2 = u(:,i:-1:i-nDk); ypast2 = y(:, i:-1:i+2-nNk); y(:,i+1) = -A(:,sizey+1:nNk*sizey)*ypast2(:) + B*[upast2(:)] + d(:,i+1); r(:,i+1) = ref(:,i+1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Ensure all outputs are dimensionally compatible u(:,i+1) = u(:,i); Du(:,i+1) = Du(:,i)*0; noise = noise(:,1:i+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Produce a neat plot time=0:size(u,2)-1; for i=1:sizey; figure(i);clf reset plotall(y(i,:),r(i,:),u(i,:),Du(i,:),d(i,:),noise(i,:),umax(i),umin(i),Dumax(i),time,i); end disp('*******************************************************************************'); disp(['*** For GPC there are ',num2str(sizey),' figures beginning at figure 1 ***']); disp('*******************************************************************************'); end %%%% Check for nargin = 6 %%%%% Function to do plotting in the MIMO case and %%%%% allow a small boundary around each plot function plotall(y,r,u,Du,d,noise,umax,umin,Dumax,time,loop) uupper = [umax,umax]'; ulower = [umin,umin]'; Dulim = [Dumax,Dumax]'; time2 = [0,time(end)]; rangeu = (max(umax)-min(umin))/20; rangey = (max(max(y))-min(min(y)))/20; ranged = (max(max([d,noise]))-min(min([d,noise])))/20;if ranged==0;ranged=1;end subplot(221);plot(time,y','-',time,r','--'); axis([time2,min(min(y))-rangey,max(max(y))+rangey]); xlabel(['GPC - Outputs and set-point in loop ',num2str(loop)]); subplot(222);plot(time,Du','-',time2,Dulim,'--',time2,-Dulim,'--'); axis([time2,min(-Dumax)-rangeu,max(Dumax)+rangeu]); xlabel(['GPC - Input increments in loop ',num2str(loop)]); subplot(223);plot(time,u','-',time2,uupper,'--',time2,ulower,'--'); axis([time2,min(umin)-rangeu,max(umax)+rangeu]); xlabel(['GPC - Inputs in loop ',num2str(loop)]); subplot(224);plot(time,d','b',time,noise,'g'); axis([time2,min(min([d,noise]))-ranged,max(max([d,noise]))+ranged]); xlabel(['GPC - Disturbance/noise in loop ',num2str(loop)]);
github
pascal220/PMSM_Control-master
imgpc_predmat.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/imgpc_predmat.m
1,002
utf_8
fb63d0fcda8514a1ecbbded69d442163
%%%% To form prediction matrices over horizon ny given %%%% %%%% x(k+1) = Ax(k)+Bu(k); y(k) = Cx(k) + D u(k); Assumes D=0 %%%% %%%% Use absolute inputs (not increments) %%%% %%%% yfut = P*x + H*ufut + L*offset [offset = y(process) - y(model)] %%%% %%% Also estimate steady-state input as uss = M(r-offset) %%% %%%% [H,P,L,M] = imgpc_predmat(A,B,C,D,ny); %% %% Author: J.A. Rossiter (email: [email protected]) function [H,P,L,M] = imgpc_predmat(A,B,C,D,ny) %%% Estimate uss as uss = M(r-offset) Gss = C*inv(eye(size(A,2))-A)*B; M=inv(Gss); %%%% Initialise Px=C*A; Pu=C*B; P=C; nx=size(A,1); nB=size(B,2); nC = size(C,1); L=[]; %%%% Use recursion to find predictions for i=1:ny; Puterm = P*B; for j=i:ny; vrow=(j-1)*nC+1:j*nC; vcol=(j-i)*nB+1:(j-i+1)*nB; Pu(vrow,vcol)=Puterm; end P=P*A; vrow=(i-1)*nC+1:i*nC; Px(vrow,1:nx) = P; L=[L;eye(nC)]; end H=Pu; P=Px;
github
pascal220/PMSM_Control-master
mpc_simulate_tfilt.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/mpc_simulate_tfilt.m
6,612
utf_8
e58a9597a07c38d673092adcc08d4907
%%%%%%%%%%%%%% Either: (WITH T-filter!!) %%%%%%%%%%%%%% (1) Gives control law parameters (nargin = 6 only) %%%%%%%%%%%%%% (2) Simulates MIMO GPC with constraint handling %%% %%%%% [Nk,Dk,Pr] = mpc_simulate_tfilt(B,A,Tfilt,nu,ny,Wu,Wy) %%%%% Du(k) = Pr*r(k+1) - Dk*Du(k-1) - Nk*y(k) %% %%%%% [y,u,Du,r] = mpc_simulate_tfilt(B,A,Tfilt,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) % y, u, Du, r are dimensionally compatible % closed-loop outputs/inputs/input increments and supplied set-point and disturbance % % MFD model Ay(k) = Bu(k-1) + Tfilt*dist % % ny is output horizon % nu is the input horizon % Wu is the diagonal control weighting % Wy is the diagonal output weighting % sizey no. outputs and inputs (assumed square) % dist, noise are the disturbance and noise signals % ref is the reference signal % Dumax is a vector of limits on input increments (assumed symetric) % umax, umin are vectors of limits on the inputs % %%%%% %%%%% [y,u,Du,r] = mpc_simulate_tfilt(B,A,Tfilt,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) %% %% Author: J.A. Rossiter (email: [email protected]) function [y,u,Du,r] = mpc_simulate_tfilt(B,A,Tfilt,nu,ny,Wu,Wy,Dumax,umax,umin,ref,dist,noise) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Error checks sizey = size(A,1); if size(B,2)==sizey;B=[B,zeros(sizey,sizey)];end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Find prediction matrices %%%% yfut = H *Dufut + P*Dupast + Q*ypast %%%% yfut = H *Dufut + Pt*Dutpast + Qt*ytpast %% filtered data [H,P,Q] = mpc_predmat(A,B,ny); [Pt,Qt] = mpc_predtfilt(H,P,Q,Tfilt,sizey,ny); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Find control law and parameters of the cost function %%%% Dufut = Pr*rfut - Dk*Dutpast - Nk*ytpast %%%% J = Dufut'*S*Dufut + Dufut'*2X*[Dutpast;ytpast;rfut] [Nk,Dk,Pr,S,X] = mpc_law(H,Pt,Qt,nu,Wu,Wy,sizey); if nargin==7; %%%% collect control law and stop y=Nk(1:sizey,:); u=Dk(1:sizey,:); Du=Pr(1:sizey,:); else %%%% continue to simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin~=13;disp('Incomplete input information - stopping');break;end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%% Define constraint matrices %%%%%% CC*Dufut - dd - dd1*ut <= 0 [CC,dd,dd1] = mpc_constraints(Dumax,umax,umin,sizey,nu); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Set up simulation parameters nNk = size(Nk,2)/sizey; nDk = size(Dk,2)/sizey; nT = size(Tfilt,2)/sizey; T2 = Tfilt(:,sizey+1:nT*sizey); nA = size(A,2)/sizey; nB = size(B,2)/sizey; init = max([nNk,nDk,nA,nB])+2; y = zeros(sizey,init); yt=y; u = y; Du = u; Dut = u; r = u; d=u; opt = optimset('quadprog'); opt.Diagnostics='off'; %%%%% Switches of unwanted MATLAB displays opt.LargeScale='off'; %%%%% However no warning of infeasibility opt.Display='off'; runtime = size(ref,2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i=init:runtime-1; %%% Update unconstrained control law %%%%% Update filtered data ytpast = yt(:,i-1:-1:i-nT+1); yt(:,i) = y(:,i) + noise(:,i) - T2*ytpast(:); Dutpast = Dut(:,i-2:-1:i-nT); Dut(:,i-1) = Du(:,i-1) - T2*Dutpast(:); %%% Define vectors of past filtered data for use by control law d(1:sizey,i+1)=dist(:,i+1); ypast = yt(:, i:-1:i+1-nNk); Dupast = Dut(:, i-1:-1:i-nDk) ; upast = u(:, i-1); rfut = ref(:,i+1); %%%%%%% Unconstrained law - if needed Dufast = Pr*rfut - Nk*ypast(:) - Dk*Dupast(:); % Form constraint matrices and solve constrained optimisation % CC*Dufast-dd-dd1*upast<=0 dt = dd+dd1*upast; Dufast2 = quadprog(S,X*[Dupast(:);ypast(:);rfut(:)],CC,dt,[],[],[],[],[],opt); Du(:,i) = Dufast2(1:sizey); u(:,i) = u(:,i-1)+Du(:,i); % Ensure the constraints satisfied by proposed control law for j=1:sizey; if u(j,i)>u(j,i-1)+Dumax(j),u(j,i)=u(j,i-1)+Dumax(j);end if u(j,i)<u(j,i-1)-Dumax(j),u(j,i)=u(j,i-1)-Dumax(j);end if u(j,i)>umax(j); u(i)=umax(j);end if u(j,i)<umin(j); u(i)=umin(j);end end Du(:,i) = u(:,i)-u(:,i-1); % End to update control law %%% Simulate the process upast2 = u(:,i:-1:i-nB+1); ypast2 = y(:, i:-1:i+2-nA); y(:,i+1) = -A(:,sizey+1:nA*sizey)*ypast2(:) + B*[upast2(:)]+ d(:,i+1); r(:,i+1) = ref(:,i+1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Ensure all outputs are dimensionally compatible u(:,i+1) = u(:,i); Du(:,i+1) = Du(:,i)*0; noise = noise(:,1:i+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Produce a neat plot time=0:size(u,2)-1; for i=1:sizey; figure(i+3);clf reset plotall(y(i,:),r(i,:),u(i,:),Du(i,:),d(i,:),noise(i,:),umax(i),umin(i),Dumax(i),time,i); end disp('*******************************************************************************'); disp(['*** For GPCT there are ',num2str(sizey),' figures beginning at figure 4 ***']); disp('*******************************************************************************'); end %%%% Check for nargin = 6 %%%%% Function to do plotting in the MIMO case and %%%%% allow a small boundary around each plot function plotall(y,r,u,Du,d,noise,umax,umin,Dumax,time,loop) uupper = [umax,umax]'; ulower = [umin,umin]'; Dulim = [Dumax,Dumax]'; time2 = [0,time(end)]; rangeu = (max(umax)-min(umin))/20; rangey = (max(max(y))-min(min(y)))/20; ranged = (max(max([d,noise]))-min(min([d,noise])))/20; subplot(221);plot(time,y','-',time,r','--'); axis([time2,min(min(y))-rangey,max(max(y))+rangey]); xlabel(['GPCT - Outputs and set-point in loop ',num2str(loop)]); subplot(222);plot(time,Du','-',time2,Dulim,'--',time2,-Dulim,'--'); axis([time2,min(-Dumax)-rangeu,max(Dumax)+rangeu]); xlabel(['GPCT - Input increments in loop ',num2str(loop)]); subplot(223);plot(time,u','-',time2,uupper,'--',time2,ulower,'--'); axis([time2,min(umin)-rangeu,max(umax)+rangeu]); xlabel(['GPCT - Inputs in loop ',num2str(loop)]); subplot(224);plot(time,d','b',time,noise,'g'); axis([time2,min(min([d,noise]))-ranged,max(max([d,noise]))+ranged]); xlabel(['GPCT - Disturbance/noise in loop ',num2str(loop)]);
github
pascal220/PMSM_Control-master
caha.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/caha.m
664
utf_8
8a6e93e762728865acd3f8797920c379
% function [CA,HA] = caha(A,sizey,n) %% %% To find Toeplitz matrix Ca and hankel matrix Ha %% with Ca having n block rows %% Assume n > order(A) %% sizey is the dimension of implied A(z) %% %% Author: J.A. Rossiter (email: [email protected]) function [Ca,Ha] = caha(A,sizey,n) na = size(A,2)/sizey; nA = size(A,2); for i=1:na; Av((i-1)*sizey+1:i*sizey,1:sizey) = A(:,(i-1)*sizey+1:i*sizey); end for i=1:n; v=(i-1)*sizey; Ca(v+1:v+nA,v+1:v+sizey)=Av; end Ca = Ca(1:n*sizey,:); Ha = zeros(n*sizey,sizey); for i=1:na-1; v = (i-1)*sizey+1:i*sizey; Ha(v,1:(na-i)*sizey) = A(:,i*sizey+1:nA); end
github
pascal220/PMSM_Control-master
imgpc_simulate.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/imgpc_simulate.m
5,712
utf_8
239e7422c6460da4318cb9c812544e5d
%%% Simulation of independent model GPC with a state space model (Figure 1 on) %%% %%% Uses the cost function J = sum (r-y)^2 + R(u-uss)^2 %%% (weights absolute inputs not increments) %%% %% [x,y,u,r] = imgpc_simulate(A,B,C,D,R,ny,nu,umax,umin,Dumax,x0,ref,dist,noise); %% %%% x(k+1) = A x(k) + B u(k) x0 is the initial condition %%% y(k) = C x(k) + D u(k) + dist Note: Assumes D=0, dist unknown %%% %% input constraint umax, umin %% input rate constraint Dumax %% reference trajectory ref, r %% steady-state input uss %% Output/input horizons ny,nu %% Weighting matrix in J R %% measurement noise noise %% %% Author: J.A. Rossiter (email: [email protected]) function [x,y,u,r] = imgpc_simulate(A,B,C,D,R,ny,nu,umax,umin,Dumax,x0,ref,dist,noise); sizey = size(C,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Find GPC law and observor (using independent model approach) %%%%% Control law is written as a combination of feedback and %%%%% simulation of the independent model %%%%% %%%%% u = -Kz + Pr (r - offset); offset = yprocess-ymodel %%%%% %%%%% Indpendent model is %%%%% z = Az + Bu; y = Cz; %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Predictions are yfut = P*x + H*ufut + L*offset %%% Steady state input is estimated as M*(r-offset) %%% Note: As using inputs (not increments) require all columns of H [H,P,L,M] = imgpc_predmat(A,B,C,D,ny); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Find control law minimising J = sum yfut'yfut + ufut*R*ufut %%% Assume that u(k+nu+i) = u(k+nu-1) in predictions %%% The optimal cost is %%% J = ufut'Sufut + ufut'X*[x;r-offset] + unconstrained optimal %%% The control law is %%% ufut = -K*x +Pr*(r-offset) %%% %%% Predictions are yfut = P*x + H*ufut + L*offset [S,X,K,Pr] = imgpc_costfunction(H,P,L,M,R,nu,sizey,ny); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Constraints are summarised as %%%%% umin < ufut < umax %%%%% CC*ufut - dfixed -dxu u(k-1)<=0 [CC,dfixed,dxu] = imgpc_constraints(nu,umin,umax,Dumax); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% SIMULATION %%% initialise data nx = size(A,1);nuu=size(B,2); x=[x0,x0];xm=x;xp=x; yp=C*xm;ym=yp; u=zeros(sizey,2);r=yp*0; runtime = size(ref,2)-1; opt = optimset; opt.Display='off'; %'notify'; opt.Diagnostics='off'; opt.LargeScale='off'; for i=2:runtime; r(:,i+1) = ref(:,i+1); %%%%% Update offset offset(:,i) = yp(:,i) + noise(:,i)-ym(:,i); %%% Noise effects measurement only %%%% Update control decisions using a quadratic program %ufut = -K*xm(:,i) +Pr*(r(:,i+1)-offset(:,i)); %% (unconstrained) ufut = quadprog(S,X*[xm(:,i);r(:,i+1)-offset(:,i)],CC,dfixed+dxu*u(:,i-1),[],[],[],[],[],opt); u(:,i) = ufut(1:sizey); Du(:,i)=u(:,i)-u(:,i-1); % Ensure the constraints satisfied by proposed control law for j=1:sizey; if u(j,i)>u(j,i-1)+Dumax(j);u(j,i)=u(j,i-1)+Dumax(j);end if u(j,i)<u(j,i-1)-Dumax(j);u(j,i)=u(j,i-1)-Dumax(j);end if u(j,i)>umax(j); u(i)=umax(j);end if u(j,i)<umin(j); u(i)=umin(j);end end Du(:,i) = u(:,i)-u(:,i-1); %%% End of update to the control law %%%% Simulate model xm(:,i+1) = A*xm(:,i)+B*u(:,i); ym(:,i+1) = C*xm(:,i+1); %%%% Simulate process xp(:,i+1) = A*xp(:,i)+B*u(:,i); yp(:,i+1) = C*xp(:,i+1)+dist(:,i); end %%%%% Ensure data lengths are all compatible u(:,i+1)=u(:,i); Du(:,i+1)=Du(:,i)*0; r(:,i+1) = ref(:,i+1); noise = noise(:,1:i+1); d = dist(:,1:i+1); x=xp;y=yp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Produce a neat plot time=0:size(u,2)-1; for i=1:size(B,2); figure(i);clf reset plotall(yp(i,:),r(i,:),u(i,:),Du(i,:),d(i,:),noise(i,:),umax(i),umin(i),Dumax(i),time,i); end disp('**************************************************'); disp(['*** There are ',num2str(size(B,2)),' figures ***']); disp('**************************************************'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% Function to do plotting in the MIMO case and %%%%% allow a small boundary around each plot function plotall(y,r,u,Du,d,noise,umax,umin,Dumax,time,loop) uupper = [umax,umax]'; ulower = [umin,umin]'; Duupper = [Dumax,Dumax]'; Dulower = -[Dumax,Dumax]'; time2 = [0,time(end)]; rangeu = (max(umax)-min(umin))/20; rangedu = max(Dumax)/20; rangey = (max(max(y))-min(min(y)))/20; ranged = (max(max([d,noise]))-min(min([d,noise])))/20; if ranged==0;ranged=1;end subplot(221);plot(time,y','-',time,r','--'); axis([time2,min(min(y))-rangey,max(max(y))+rangey]); xlabel(['IMGPC - Outputs and set-point in loop ',num2str(loop)]); subplot(222);plot(time,Du','-',time2,Duupper,'--',time2,Dulower,'--'); axis([time2,min(-Dumax)-rangedu,max(Dumax)+rangedu]); xlabel(['IMGPC - Input increments in loop ',num2str(loop)]); subplot(223);plot(time,u','-',time2,uupper,'--',time2,ulower,'--'); axis([time2,min(umin)-rangeu,max(umax)+rangeu]); xlabel(['IMGPC - Inputs in loop ',num2str(loop)]); subplot(224);plot(time,d','b',time,noise,'g'); axis([time2,min(min([d,noise]))-ranged,max(max([d,noise]))+ranged]); xlabel(['IMGPC- Disturbance/noise in loop ',num2str(loop)]);
github
pascal220/PMSM_Control-master
imgpc_constraints.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/imgpc_constraints.m
884
utf_8
9e4933e9823712e2b43e6aec76d6e353
%%%%% Constraints are summarised as %%%%% umin < u < umax and | Du | < Dumax %%%%% %%%%% or CC*ufut -dfixed - dxu*u(k-1)<=0 %%%%% [Note: absolute inputs not increments] %%%%% %%%%% nu is the control horizon %%%%% %%%%% [CC,dfixed,dxu] = imgpc_constraints(nu,umin,umax,Dumax) %% %% Author: J.A. Rossiter (email: [email protected]) function [CC,dfixed,dxu] = imgpc_constraints(nu,umin,umax,Dumax) sizeu = length(umax); %%%%% Absolute limits CC=[eye(nu*sizeu);-eye(nu*sizeu)]; dfixed=[umax;-umin]; for k=2:nu; dfixed = [umax;dfixed;-umin]; end %%%% rate limits [Cd,Hd] = caha([eye(sizeu),-eye(sizeu)],sizeu,nu); CCR=[Cd;-Cd]; dfixedr=[Dumax]; for k=2:2*nu; dfixedr = [dfixedr;Dumax]; end dxu=[zeros(2*nu*sizeu,sizeu);-Hd;Hd]; %%% All limits CC=[CC;CCR]; dfixed = [dfixed;dfixedr];
github
pascal220/PMSM_Control-master
ssmpc_costfunction.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/ssmpc_costfunction.m
718
utf_8
4138d9ebd39bd4a954fe8832dc00d2c8
%%% Given a model x = Ax + Bu %%% control u = -Kx + c %%% cost function J = sum xQx + uRu (sum to infinity) %%% %%% Then the cost function reduces to %%% J = cSc + unconstrained optimal %%% SS is for just one block, S is for nc blocks %%% %%% [S,SS] = ssmpc_costfunction(A,B,K,nc,Q,R); %%% %% %% Author: J.A. Rossiter (email: [email protected]) function [S,SS] = ssmpc_costfunction(A,B,K,nc,Q,R); Phi = A-B*K; Sx = dlyap(Phi',Q); %%% S = [I +Phi'Phi + Phi^2'Phi^2+...] Su = dlyap(Phi',K'*K); %%% S = [K'K +Phi'K'KPhi + Phi^2'K'K Phi^2+...] SS = B'*[Sx+Su]*B + eye(size(B,2)); nu=size(B,2); for k=1:nc; vec=(k-1)*nu+1:k*nu; S(vec,vec)=SS; end
github
pascal220/PMSM_Control-master
ssmpc_constraints.m
.m
PMSM_Control-master/Model Predictive Control/rossiter/ssmpc_constraints.m
2,262
utf_8
5c5ee9bf6f1761a7c7b647eba28610f6
%%%%% Constraints are summarised as %%%%% CC c - dfixed - dx0*[z;r;d] <= 0 %%%%% d is a known disturbance %%%%% %%%%% Predictions are %%%%% x = Pc1*c + Pz1*z + Pr1*r + Pd1*d %%%%% u = Pc2*c + Pz2*z + Pr2*r + Pd2*d %%%%% Constraints are %%%%% umin < u < umax Kxmax * x <xmax %%%%% %%%%% [CC,dfixed,dx0] = ssmpc_constraints(Pc1,Pc2,Pz1,Pz2,Pr1,Pr2,umin,umax,Kxmax,xmax); %%%%% %% %% Author: J.A. Rossiter (email: [email protected]) function [CC,dfixed,dx0] = ssmpc_constraints(Pc1,Pc2,Pz1,Pz2,Pr1,Pr2,umin,umax,Kxmax,xmax); nx=size(Kxmax,2); [CC,dfixed,dx0] = inputcons(Pc2,Pz2,Pr2,umax,umin); %%%% Input constraints [CCx,dfixedx,dx0x] = statecons(Pc1,Pz1,Pr1,Kxmax,xmax,nx); %%%% State constraints CC=[CC;CCx]; dfixed = [dfixed;dfixedx]; dx0 = [dx0;dx0x]; %%%%% Set up input constraints CC * c - dfixed - dx0 * [z;r] <=0 %%%%% given %%%%% u = Pc2*c + Pz2*z + Pr2*r + Pd2*d %%%%% umin < u < umax %%%%% function [CC,dfixed,dx0] = inputcons(Pc2,Pz2,Pr2,umax,umin); nrows = size(Pc2,1); steps = nrows/length(umax); Up = umax; Ul = umin; for i=2:steps Up = [Up;umax]; Ul = [Ul;umin]; end %%%%% Pc2 c + Pz2 z + Pr2 r < Up %%%%% Pc2 c + Pz2 z + Pr2 r > Ul or -Pc2 c - Pz2 z - Pr2 r < - Ul CC = [Pc2;-Pc2]; dfixed = [Up;-Ul]; dx0 = [-Pz2,-Pr2;Pz2,Pr2]; %%%% Set up state constraints for a state-space system %%%% CC * c - dfixed - dx0 * [z;r] <=0 z is state estimate %%%% %%%% x = Pc1*c + Pz1*z + Pr1*r and | Kxmax * x| < xmax function [CC,dfixed,dx0] = statecons(Pc1,Pz1,Pr1,Kxmax,xmax,nx); nrows = size(Pc1,1); steps = nrows/nx; nK = size(Kxmax,1); nc = size(Pc1,2); nz = size(Pz1,2); nr = size(Pr1,2); Xp = xmax; Xl = -xmax; for i=1:steps-1 Xp = [Xp;xmax]; end for i=1:steps; Pc((i-1)*nK+1:i*nK,1:nc) = Kxmax*Pc1((i-1)*nx+1:i*nx,:); Pz((i-1)*nK+1:i*nK,1:nz) = Kxmax*Pz1((i-1)*nx+1:i*nx,:); Pr((i-1)*nK+1:i*nK,1:nr) = Kxmax*Pr1((i-1)*nx+1:i*nx,:); end %%%%% Constraints are %%%%% Pc2 c + Pz2 z + Pr2 r < Up %%%%% Pc2 c + Pz2 z + Pr2 r > Ul or -Pc2 c - Pz2 z - Pr2 r < - Ul CC = [Pc;-Pc]; dfixed = [Xp;Xp]; dx0 = [-Pz,-Pr;Pz,Pr];
github
Chaogan-Yan/PaperScripts-master
SexinSeparateSites.m
.m
PaperScripts-master/WangYW_2023_NeuroImage/6Misuse/SexinSeparateSites.m
14,920
utf_8
9292a40c5035c39ae19742388b062dee
%% SMA clear; clc; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/CoRR/SubInfo/SubInfo_420.mat'); site = info.Site; age = info.Age; sex = info.Sex; sex(sex==-1)=0; motion1 = info.Motion(:,1); motion2 = info.Motion(:,2); subid = info.SubID; SiteSWU_ind = find(site==8); ResultsSet = {'Results','S2_Results'}; SexTarget = sex(SiteSWU_ind); AgeTarget = age(SiteSWU_ind); AgeTarget = double(AgeTarget<22)+1; IndexTarget = AgeTarget;% + 2*double(SexTarget) ; files = {'Results','S2_Results'}; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/FCP_Organized/SubInfo/600_subinfo.mat'); % 1-female 2-male site = info.SiteID; age = double(info.Age); sex = info.Sex-1; % 0-female 1-male motion = info.MeanFDJ; eye = info.eyeclosed; sitename = info.SiteName; subid = info.Subid; BEIJING_female_inds = find(strcmp(sitename,"Beijing")& sex==0); Cambridge_male_inds = find(strcmp(sitename,"Cambridge")& sex==1); refer_site = {BEIJING_female_inds,Cambridge_male_inds}; inds = cell2mat(refer_site'); refer_sitename = sitename(inds); IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; % overlap mask Cov = [sex(inds),double(age(inds)),motion(inds),ones(180,1)]; Datadir = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites'; subid = info.Subid(inds); %parpool(15); for ses =1:2 savepath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/',files{ses}]; mkdir(savepath); for i_Index = 2:2% length(IndexName) file = [savepath,'/',IndexName{i_Index},'_SMA_SWU_beijing_cambridge.mat']; if ~exist(file,'file') if strcmp(IndexName{i_Index},'FC') datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',files{ses},'/',IndexName{i_Index},'_raw.mat']; else datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',files{ses},'/',IndexName{i_Index},'_raw.mat']; end data = importdata(datapath); Xtarget = data(SiteSWU_ind,:); datapath =['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/FCP/Results/',IndexName{i_Index},'_raw.mat']; FCP_data = importdata(datapath); %% define target and source for i =1:length(refer_site) AgeSource = age(refer_site{i}); SexSource = sex(refer_site{i}); Xsource = FCP_data(refer_site{i},:); temp = zeros(size(Xsource)); AgeSource = double(AgeSource<22)+1; IndexSource = AgeSource + 2*double(SexSource) ; %MatrixTran{i-1}= zeros(4,3); for k = 1:size(temp,2) MatrixTran=[]; Source = Xsource(:,k); Target = Xtarget(:,k); [slope,intercept,pvalue] = subsamplingMMD(Source,Target,IndexSource,IndexTarget,100); %[slope,intercept,pvalue] = fitMMD(Source,Target,0); %MatrixTran(k,:) = [slope,intercept,pvalue]; temp(:,k) = slope*Source+ones(size(Source))*intercept; %Here, pvalue is for subsamples from first iteration end new_site_data{i} = temp; fprintf('site %d fitting completed \n', i); end SMA = cell2mat(new_site_data'); save([savepath,'/',IndexName{i_Index},'_SMA_SWU_beijing_cambridge.mat'],'SMA'); else load(file); end RawNiiPath = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/FCP_Organized/AllMaps/'; MaskFile = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Mask/Overlap38810.nii'; NII_outputpath = fullfile(Datadir,'/Niis/',ResultsSet{ses},'/',IndexName{i_Index}); mkdir(NII_outputpath); StatOutDir = fullfile(Datadir,'/Stat/SWU_beijing_cambridge/',ResultsSet{ses},'/',IndexName{i_Index}); mkdir(StatOutDir); outputname = [StatOutDir,'/MaleVSFemaleT.nii']; GRFOutDir=[StatOutDir,'/GRF/ClusterCorrected001_05/']; mkdir(GRFOutDir); GRFOutName=[GRFOutDir,'/MaleVsFemaleT']; if ~exist(outputname,'file') % write nii StatList = writeSiteNii(SMA,IndexName{i_Index},refer_sitename,subid,NII_outputpath,MaskFile,RawNiiPath); % TWO-SAMPLE-TEST y_GroupAnalysis_Image(StatList,Cov,outputname,MaskFile,[],[1,0,0,0],'T',0); end % GRF correction if length(dir(GRFOutDir))==2 % dir is empty [Data_corrected,~,Header]= y_GRF_Threshold(outputname,0.001,1,0.05,GRFOutName,MaskFile); else Data_corrected = y_Read([GRFOutDir,'/ClusterThresholded_MaleVsFemaleT.nii']); end Data_corrected =Data_corrected(Data_corrected~=0); NMax = min(Data_corrected(Data_corrected<0)); NMin = max(Data_corrected(Data_corrected<0)); PMin = min(Data_corrected(Data_corrected>0)); PMax = max(Data_corrected(Data_corrected>0)); ConnectivityCriterion = 18; ClusterSize = 0; UnderlayFileName='/mnt/Data3/RfMRILab/Wangyw/software/DPABI_V6.0_ForCamp/Templates/ch2.nii'; GRFfile = [GRFOutDir,'/ClusterThresholded_MaleVsFemaleT.nii'] ColorMap = y_AFNI_ColorMap(12); [BrainNetViewerPath, fileN, extn] = fileparts(which('BrainNet.m')); SurfFileName=[BrainNetViewerPath,filesep,'Data',filesep,'SurfTemplate',filesep,'BrainMesh_ICBM152_smoothed.nv']; viewtype='MediumView'; pics_path = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/Pics/',ResultsSet{ses}]; mkdir(pics_path); H_BrainNet = y_CallBrainNetViewer(GRFfile,NMin,PMin,ClusterSize,ConnectivityCriterion,SurfFileName,viewtype,ColorMap,NMax,PMax ); JPGFile=[pics_path,'/',IndexName{i_Index},'_BeijingF_CambM.jpeg']; eval(['print -r300 -djpeg -noui ''',JPGFile,''';']); end end %% ComBat/CovBat clear; clc; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/CoRR/SubInfo/SubInfo_420.mat'); site = info.Site; age_corr = info.Age; sex = info.Sex; sex(sex==-1)=0; sex_corr=sex; motion1 = info.Motion(:,1); motion2 = info.Motion(:,2); subid = info.SubID; SiteSWU_ind = find(site==8); file = {'Results','S2_Results'}; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/FCP_Organized/SubInfo/600_subinfo.mat'); % 1-female 2-male site = info.SiteID; age = double(info.Age); sex = info.Sex-1; % 0-female 1-male motion = info.MeanFDJ; eye = info.eyeclosed; sitename = info.SiteName; subid = info.Subid; BEIJING_female_inds = find(strcmp(sitename,"Beijing")& sex==0); Cambridge_male_inds = find(strcmp(sitename,"Cambridge")& sex==1); refer_site = {BEIJING_female_inds,Cambridge_male_inds}; inds = cell2mat(refer_site'); refer_sitename = sitename(inds); batch = repelem([1,2,3]',[221,106,74]); IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; mod = [[sex_corr(SiteSWU_ind);sex(inds)],[age_corr(SiteSWU_ind);double(age(inds))]]; % overlap mask Cov = [sex(inds),double(age(inds)),motion(inds),ones(180,1)]; Datadir = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites'; subid = info.Subid(inds); parpool(4); parfor ses =1:2 savepath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/',file{ses}]; mkdir(savepath); for i_Index = 2:2% length(IndexName) if strcmp(IndexName{i_Index},'FC') datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',file{ses},'/',IndexName{i_Index},'_raw.mat']; else datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',file{ses},'/',IndexName{i_Index},'_raw.mat']; end data = importdata(datapath); Xtarget = data(SiteSWU_ind,:); datapath =['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/FCP/Results/',IndexName{i_Index},'_raw.mat']; FCP_data = importdata(datapath); Xsource = FCP_data(inds,:); d = [Xtarget;Xsource]; sp = [savepath,'/',IndexName{i_Index},'_SWU_beijing_cambridge']; cb(d,batch,mod,sp); end end clear; clc; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/CoRR/SubInfo/SubInfo_420.mat'); site = info.Site; age_corr = info.Age; sex = info.Sex; sex(sex==-1)=0; sex_corr=sex; motion1 = info.Motion(:,1); motion2 = info.Motion(:,2); subid = info.SubID; SiteSWU_ind = find(site==8); ResultsSet = {'Results','S2_Results'}; file = {'Results','S2_Results'}; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/FCP_Organized/SubInfo/600_subinfo.mat'); % 1-female 2-male site = info.SiteID; age = double(info.Age); sex = info.Sex-1; % 0-female 1-male motion = info.MeanFDJ; eye = info.eyeclosed; sitename = info.SiteName; subid = info.Subid; BEIJING_female_inds = find(strcmp(sitename,"Beijing")& sex==0); Cambridge_male_inds = find(strcmp(sitename,"Cambridge")& sex==1); refer_site = {BEIJING_female_inds,Cambridge_male_inds}; inds = cell2mat(refer_site'); refer_sitename = sitename(inds); batch = repelem([1,2,3]',[221,106,74]); IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; mod = [[sex_corr(SiteSWU_ind);sex(inds)],[age_corr(SiteSWU_ind);double(age(inds))]]; % overlap mask Cov = [sex(inds),double(age(inds)),motion(inds),ones(180,1)]; Datadir = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites'; subid = info.Subid(inds); methods = {'SWU_beijing_cambridge_para_adj_combat',... 'SWU_beijing_cambridge_nonpara_adj_combat',... 'SWU_beijing_cambridge_adjust_covbat',... 'SWU_beijing_cambridge_para_unadj_combat',... 'SWU_beijing_cambridge_nonpara_unadj_combat',... 'SWU_beijing_cambridge_unadj_covbat' }; for ses =1:2 savepath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/',file{ses}]; mkdir(savepath); for i_method = 1:numel(methods) for i_Index = 2:2% length(IndexName) if strcmp(methods{i_method},'raw') datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',ResultsSet{ses},'/',IndexName{i_Index},'_',methods{i_method},'.mat']; else datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/',ResultsSet{ses},'/',IndexName{i_Index},'_',methods{i_method},'.mat']; end data = importdata(datapath); if ~strcmp(methods{i_method},'raw') d = data(222:end,:); end %load([savepath,'/',IndexName{i_Index},'_para_adj_combat_SWU_beijing_cambridge.mat']); %load([savepath,'/',IndexName{i_Index},'_adjust_covbat_SWU_beijing_cambridge.mat']); %covbat = covbat(222:end,:); NII_outputpath = fullfile(Datadir,'/Niis/FCP/',ResultsSet{ses},IndexName{i_Index},methods{i_method}); mkdir(NII_outputpath); StatOutDir = fullfile(Datadir,'/Stat/SWU_beijing_cambridge/FCP/',ResultsSet{ses},IndexName{i_Index},methods{i_method}); mkdir(StatOutDir); outputname = [StatOutDir,'/MaleVSFemaleT.nii']; GRFOutDir=[StatOutDir,'/GRF/ClusterCorrected001_05/']; mkdir(GRFOutDir); GRFOutName=[GRFOutDir,'/MaleVsFemaleT']; RawNiiPath = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/old/FCP_Organized/AllMaps/'; MaskFile = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Mask/Overlap38810.nii'; %if ~exist(outputname,'file') % write nii StatList = writeSiteNii(d,IndexName{i_Index},refer_sitename,subid,NII_outputpath,MaskFile,RawNiiPath); % TWO-SAMPLE-TEST y_GroupAnalysis_Image(StatList,Cov,outputname,MaskFile,[],[1,0,0,0],'T',0); %end % GRF correction [Data_corrected,~,Header]= y_GRF_Threshold(outputname,0.001,1,0.05,GRFOutName,MaskFile); Data_corrected =Data_corrected(Data_corrected~=0); NMax = min(Data_corrected(Data_corrected<0)); NMin = max(Data_corrected(Data_corrected<0)); PMin = min(Data_corrected(Data_corrected>0)); PMax = max(Data_corrected(Data_corrected>0)); ConnectivityCriterion = 18; ClusterSize = 0; UnderlayFileName='/mnt/Data3/RfMRILab/Wangyw/software/DPABI_V6.0_ForCamp/Templates/ch2.nii'; GRFfile = [GRFOutDir,'/ClusterThresholded_MaleVsFemaleT.nii']; ColorMap = y_AFNI_ColorMap(12); [BrainNetViewerPath, fileN, extn] = fileparts(which('BrainNet.m')); SurfFileName=[BrainNetViewerPath,filesep,'Data',filesep,'SurfTemplate',filesep,'BrainMesh_ICBM152_smoothed.nv']; viewtype='MediumView'; pics_path = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Revision/Data/SexinSeparateSites/Pics/',ResultsSet{ses},'/',IndexName{i_Index}]; mkdir(pics_path); H_BrainNet = y_CallBrainNetViewer(GRFfile,NMin,PMin,ClusterSize,ConnectivityCriterion,SurfFileName,viewtype,ColorMap,NMax,PMax ); JPGFile=[pics_path,'/',methods{i_method},'.jpeg']; eval(['print -r300 -djpeg -noui ''',JPGFile,''';']); end end end function cb(data,batch,mod,savepath) para_adj_combat = combat(data',batch,mod,1)'; save([savepath,'_para_adj_combat.mat'],'para_adj_combat'); para_unadj_combat = combat(data',batch,[],1)'; save([savepath,'_para_unadj_combat.mat'],'para_unadj_combat'); nonpara_adj_combat = combat(data',batch,mod,0)'; save([savepath,'_nonpara_adj_combat.mat'],'nonpara_adj_combat'); nonpara_unadj_combat = combat(data',batch,[],0)'; save([savepath,'_nonpara_unadj_combat.mat'],'nonpara_unadj_combat'); end
github
Chaogan-Yan/PaperScripts-master
SMA_TSP3.m
.m
PaperScripts-master/WangYW_2023_NeuroImage/1Harmo/1TSP3/SMA_TSP3.m
2,490
utf_8
6d2d91e5739a96f4ab4ab13282dfc43a
%% fitMMD for TST dataset % different reference site % calculate rmse and ICC % IndexName ={'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; % % MeasurePrefixSet={'szReHoMap_','szALFFMap_','szfALFFMap_','szDegreeCentrality_PositiveWeightedSumBrainMap_'}; % datapath = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/TSP3/ResultsS'; % refer_site = 'pku_ge'; % % outputpath = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/TSP3/ResultsS'; % parpool(5); % parfor i = 1:numel(IndexName) % dataname = [datapath,'/',IndexName{i},'_raw.mat']; % outputname = [outputpath,'/',IndexName{i},'_SMA.mat']; % fitMMD4TST(dataname,refer_site,IndexName{i},outputname); % end function fitMMD4TST(datapath,refer_site,feature_name,outputpath) %datapath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/TST/TSTafterHarmonization/3SIte41Sub/ResultsS/',IndexName{i},'_raw.mat']; data = importdata(datapath); ipcas_ge_index = [1:41]; pku_ge_index = [42:82]; pku_siemens_index = [83:123]; if size(data,1) ~= 123 data= data'; end ipcas_ge = data(ipcas_ge_index,:); pku_ge = data(pku_ge_index,:); pku_siemens = data(pku_siemens_index,:); site_names = {'ipcas_ge','pku_ge','pku_siemens'}; transform_mat =zeros(size(data,2),length(site_names)-1); %for target_index = 1:length(site_names) target_site = refer_site; %pku_ge eval(['target_data = ',target_site,';']); source_names = site_names(find(~ismember(site_names,target_site))); trans_data = zeros(size(data)); transformation.b = transform_mat; transformation.w = transform_mat; for source_index = 1:length(source_names) source_site = source_names{source_index}; eval(['source_data = ' source_site ';']); fprintf('we are map %s to %s', source_site, target_site) for ele = 1:size(data,2) [slope,intercept,~] = fitMMD(source_data(:,ele),target_data(:,ele),0); transformation.b(ele,source_index) = intercept; transformation.w(ele,source_index) = slope; temp(:,ele) = source_data(:,ele).*slope+intercept; end eval(['trans_data(' source_site '_index,:) = temp;']); end eval(['trans_data(' target_site '_index,:) = target_data']); save([outputpath,'/',feature_name,'_MMD_',target_site,'.mat'],'trans_data'); %end end
github
Chaogan-Yan/PaperScripts-master
FCP_ComBatcorr2022.m
.m
PaperScripts-master/WangYW_2023_NeuroImage/1Harmo/3FCP/FCP_ComBatcorr2022.m
3,283
utf_8
f9b67608a18ee406532492ed29d689c9
clear;clc; %%load info %corr load /mnt/Data3/RfMRILab/Wangyw/harmonization_project/CoRR/SubInfo/SubInfo_420.mat ; %load /mnt/Data3/RfMRILab/Wangyw/harmonization_project/CoRR/SubInfo/map_402in420.mat ; Sex(Sex==-1)=0; %female %fcp FCP.info = importdata('/mnt/Data3/RfMRILab/Wangyw/harmonization_project/FCP_Organized/SubInfo/600_subinfo.mat'); FCP.info.Sex(FCP.info.Sex==1)=0 %female FCP.info.Sex(FCP.info.Sex==2)=1 %male Age = [Age;FCP.info.Age]; Sex = [Sex;FCP.info.Sex]; Motion = [Motion;[FCP.info.MeanFDJ,FCP.info.MeanFDJ]]; SubID = [SubID;FCP.info.Subid]; Site = [Site;FCP.info.SiteID+max(Site)]; if length(unique(Site))~=max(Site) s = unique(Site); for i = 1:length(s) Site(Site==s(i)) = i ; end end clear FCP; MaskFile ='/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/Mask/Overlap38810.nii'; Mask = y_Read(MaskFile); mask_size = size(Mask); % mapping index x = find(reshape(Mask,[],1)==1); newmap = zeros(size(reshape(Mask,[],1))); newmap(x,1) = 1; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; outputpath = '/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/FCP'; % load data %parpool(4); Rdir ={'Results','S2_Results'} for ses = 1:2 mod = [double(Age),Sex,Motion(:,ses)]; for i =1:length(IndexName) com = importdata(['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/CORR/',Rdir{ses},'/',IndexName{i},'_raw.mat']); fcp = importdata(['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/FCP/',Rdir{ses},'/',IndexName{i},'_raw.mat']); raw = [com;fcp]; % clear fcp; % clear combat; fprintf('now is harmonizing %s \n',IndexName{i} ); outputpath = ['/mnt/Data3/RfMRILab/Wangyw/harmonization_project/Restart/HarmonizationResults/FCP/',Rdir{ses}]; para_adj(raw,Site, mod, outputpath, IndexName{i}); nonpara_adj(raw,Site, mod, outputpath, IndexName{i}); para_unadj(raw,Site, outputpath, IndexName{i}); nonpara_unadj(raw,Site, outputpath, IndexName{i}); % para_unadj_combat = combat(raw',Site, [],1,0)'; % save([outputpath,'/',IndexName{i} ,'_para_unadj_combat.mat'],'para_unadj_combat'); % % nonpara_unadj_combat = combat(raw',Site, [],0,0)'; % save([outputpath,'/',IndexName{i} ,'_nonpara_unadj_combat.mat'],'nonpara_unadj_combat'); end end function para_adj(data,Site,mod,outputpath,featurename) para_adj_combat = combat(data',Site, mod,1,0)'; save([outputpath,'/',featurename ,'_para_adj_combat.mat'],'para_adj_combat'); end function nonpara_adj(data,Site,mod,outputpath,featurename) nonpara_adj_combat =combat(data',Site, mod,0,0)';; save([outputpath,'/',featurename ,'_nonpara_adj_combat.mat'],'nonpara_adj_combat'); end function para_unadj(data,Site,outputpath,featurename) para_unadj_combat = combat(data',Site,[],1,0)'; save([outputpath,'/',featurename ,'_para_unadj_combat.mat'],'para_unadj_combat'); end function nonpara_unadj(data,Site,outputpath,featurename) nonpara_unadj_combat =combat(data',Site, [],0,0)';; save([outputpath,'/',featurename ,'_nonpara_unadj_combat.mat'],'nonpara_unadj_combat'); end
github
Chaogan-Yan/PaperScripts-master
bootstrappingExps2.m
.m
PaperScripts-master/WangYW_2023_NeuroImage/7SMATargetsiteChoice/FCP-Bootstrapping-Stability/bootstrappingExps2.m
3,547
utf_8
921a7c03bbb6bb708af0ecc21df261ab
%% bootstrapping for hypothsis test % H0.a sample size does not affect result when distribution unchanged % H0.b distribution does not affect result when sample size unchanged %% H0.b distribution does not affect result when sample size unchanged % target site: beijing % source sites: leidein2200 satitlouis % bootstrapp settings: % sample distribution conditions: % 1. left bias 30, 5, 30 , 5 % 2. right bias 5, 30, 5, 30 % bootstrapping times: 50 clear;clc; addpath(genpath('/mnt/Data3/RfMRILab/Wangyw/software/PNAS2018-master')); conditions = [30, 5, 30, 5 ;5, 30, 5, 30]; bootTime = 50; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; %parpool(20); for i_Metric = 1: numel(IndexName) load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/Beijing/',IndexName{i_Metric},'.mat']); BeijingSubgroup = subgroup; leiden_2200 = load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/Leiden_2200/',IndexName{i_Metric},'.mat']); sl = load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/SaintLouis/',IndexName{i_Metric},'.mat']); for i_Distribution = 1:size(conditions,1) for i_boot = 1:bootTime tic; outputdir = ['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/ExperimentResults/TargetSiteDistribution/Distribution',int2str(i_Distribution),'/',int2str(i_boot)]; mkdir(outputdir); [SampleInds,targetlabel] = subgroup_subsamping(BeijingSubgroup,conditions(i_Distribution,:),0); TargetData = sdata(SampleInds,:); sourcedata = {leiden_2200.sdata;sl.sdata}; sourcelabel = {leiden_2200.subgroup;sl.subgroup}; sma = []; for i_source = 1:numel(sourcedata) SD = sourcedata{i_source}; SL = sourcelabel{i_source}; temp = zeros(size(SD)); parfor k = 1:size(temp,2) source = SD(:,k); target = TargetData(:,k); [slope,intercept,pvalue] = subsamplingMMD(source,target,SL,targetlabel,50); temp(:,k) = slope*source+ones(size(source))*intercept; if sum(isnan(temp(:,k))) warning('there are nans'); end end sma{i_source} = temp; end %sma = cell2mat(sma); save([outputdir,'/',IndexName{i_Metric},'_SMA.mat'],'sma','SampleInds'); fprintf('%d / 50 ...',i_boot); toc; end end end %% function [Subsample_ind,Labels] = subgroup_subsamping(groups,subsize,isrepeat) % 1 get indexs for each sub group unique_group_labels = unique(groups); for i = 1:numel(unique_group_labels) subgroup_index{i} = find(groups==unique_group_labels(i)); end % 2 get assigned size of samples for each group if numel(subsize)~=numel(unique_group_labels) error('The number of sizes of subgroups does not match the number of unique groups.'); elseif ~isrepeat for i = 1:numel(unique_group_labels) Subgroup_ind_choice{i} = subgroup_index{i}(randperm(numel(subgroup_index{i}),subsize(i))); end else for i = 1:numel(unique_group_labels) Subgroup_ind_choice{i} = subgroup_index{i}(randi(numel(subgroup_index{i}),subsize(i))); end end Subsample_ind=cell2mat(Subgroup_ind_choice'); Labels = repelem(unique_group_labels,subsize); end
github
Chaogan-Yan/PaperScripts-master
bootstrappingExps.m
.m
PaperScripts-master/WangYW_2023_NeuroImage/7SMATargetsiteChoice/FCP-Bootstrapping-Stability/bootstrappingExps.m
3,913
utf_8
95c431f6f43e369b49289a9b95fc18de
%% bootstrapping for hypothsis test % H0.a sample size does not affect result when distribution unchanged % H0.b distribution does not affect result when sample size unchanged %% H0.a sample size does not affect result when distribution unchanged % target site: beijing % source sites: leidein2200 satitlouis % bootstrap settings: % sample size conditions: % 1. 7, 4, 4, 3 % 2. 27, 16, 15, 12 % 3. 49, 30, 29, 22 % bootstrapping times: 50 clear;clc; addpath(genpath('/mnt/Data3/RfMRILab/Wangyw/software/PNAS2018-master')); sizes = [7, 4, 4, 3 ;27, 16, 15, 12; 49, 30, 29, 22]; bootTime = 50; IndexName = {'ReHo_FunImgARCWF','ALFF_FunImgARCW','fALFF_FunImgARCW','DegreeCentrality_FunImgARCWF','FC_D142'}; %parpool(20); for i_Metric = 1: numel(IndexName) load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/Beijing/',IndexName{i_Metric},'.mat']); BeijingSubgroup = subgroup; leiden_2200 = load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/Leiden_2200/',IndexName{i_Metric},'.mat']); sl = load(['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/SaintLouis/',IndexName{i_Metric},'.mat']); for i_size = 1:size(sizes,1) for i_boot = 1:bootTime fprintf('%d / 50 ...',i_boot); tic; outputdir = ['/mnt/Data6/RfMRILab/Wangyuwei/bootstrapping/ExperimentResults/TargetSiteSampleSize/Size',int2str(i_size),'/',int2str(i_boot)]; mkdir(outputdir); [SampleInds,targetlabel] = subgroup_subsamping(BeijingSubgroup,sizes(i_size,:),0); TargetData = sdata(SampleInds,:); sourcedata = {leiden_2200.sdata;sl.sdata}; sourcelabel = {leiden_2200.subgroup;sl.subgroup}; sma = []; for i_source = 1:numel(sourcedata) SD = sourcedata{i_source}; SL = sourcelabel{i_source}; temp = zeros(size(SD)); parfor k = 1:size(temp,2) source = SD(:,k); target = TargetData(:,k); [slope,intercept,pvalue] = subsamplingMMD(source,target,SL,targetlabel,50); temp(:,k) = slope*source+ones(size(source))*intercept; if sum(isnan(temp(:,k))) warning('there are nans'); end end sma{i_source} = temp; end %sma = cell2mat(sma); save([outputdir,'/',IndexName{i_Metric},'_SMA.mat'],'sma','SampleInds'); toc; end end end %% H0.b distribution does not affect result when sample size unchanged % target site: beijing % source sites: leidein2200 satitlouis % bootstrapp settings: % sample distribution conditions: % 1. left bias 30, 5, 30 , 5 % 2. right bias 5, 30, 5, 30 % bootstrapping times: 50 %% function [Subsample_ind,Labels] = subgroup_subsamping(groups,subsize,isrepeat) % 1 get indexs for each sub group unique_group_labels = unique(groups); for i = 1:numel(unique_group_labels) subgroup_index{i} = find(groups==unique_group_labels(i)); end % 2 get assigned size of samples for each group if numel(subsize)~=numel(unique_group_labels) error('The number of sizes of subgroups does not match the number of unique groups.'); elseif ~isrepeat for i = 1:numel(unique_group_labels) Subgroup_ind_choice{i} = subgroup_index{i}(randperm(numel(subgroup_index{i}),subsize(i))); end else for i = 1:numel(unique_group_labels) Subgroup_ind_choice{i} = subgroup_index{i}(randi(numel(subgroup_index{i}),subsize(i))); end end Subsample_ind=cell2mat(Subgroup_ind_choice'); Labels = repelem(unique_group_labels,subsize); end
github
skyhejing/IJCAI2017-master
list_update_u_l_three.m
.m
IJCAI2017-master/list_update_u_l_three.m
1,575
utf_8
77637ea8b8c19135e77e48efc352c342
% function [f,g] = list_update_u_l_three(u_l_sample,user_unique_three, l_u,trainset_three,lamda,h,matrix_feature) function [f,g] = list_update_u_l_three(u_l_sample, l_u,trainset_three,lamda,h,matrix_feature) %deal f u_l_sample=reshape(u_l_sample, h, matrix_feature); u_l_trainset=u_l_sample(trainset_three(:,1),:); l_u_trainset_one=l_u(trainset_three(:,3),:); l_u_trainset_two=l_u(trainset_three(:,6),:); l_u_trainset_three=l_u(trainset_three(:,9),:); l_u_trainset_four=l_u(trainset_three(:,10),:); u_l_sum_one=sum(u_l_trainset .* l_u_trainset_one,2); u_l_sum_two=sum(u_l_trainset .* l_u_trainset_two,2); u_l_sum_three=sum(u_l_trainset .* l_u_trainset_three,2); u_l_sum_four=sum(u_l_trainset .* l_u_trainset_four,2); result_first=log(exp(u_l_sum_one) + exp(u_l_sum_two) +exp(u_l_sum_three)+exp(u_l_sum_four))-u_l_sum_one; result_second=log(exp(u_l_sum_two) +exp(u_l_sum_three)+exp(u_l_sum_four))-u_l_sum_two; result_third=log(exp(u_l_sum_three)+exp(u_l_sum_four))-u_l_sum_three; f=sum(result_first+result_second+result_third); %deal g g = zeros(size(u_l_sample)); %comment at 20151027. Replaced by arrayfun. u_l_new_cell=arrayfun(@(i) list_update_u_l_three_gradient( l_u,u_l_sample,trainset_three,matrix_feature,lamda,i ),1:size(u_l_sample,1),'UniformOutput', false); g=reshape(cell2mat(u_l_new_cell),size(u_l_sample'))'; g = g(:); % g(g<0.00001)=0.00001; % g(isnan(g))=100; legal = sum(any(imag(g(:))))==0 & sum(isnan(g(:)))==0 & sum(isinf(g(:)))==0; if ~legal disp 'u_l_update: g is not legal!' end end %endfunction
github
abhijitbendale/OWR-master
OW_plotResults.m
.m
OWR-master/src/OW_plotResults.m
2,077
utf_8
a67559535bad8f1fb0de24dcf1c12fe2
function OW_plotResults(OSNCM, OSNNO, xx, yy) % This script illustrates the a way to generate surface plots as shown % in the paper [1]. You can replace performance numbers for OSNCM and % OSNNO with whatever algorithm you prefer. A script that contains % hard-coded performance numbers used in the paper are available in % plots/plot_results_50.m and plots/lot_results_200.m. These two scripts % should give a fair idea about how to use this function. I have % ignored plotting of SVM/1vSet baselines in this script. However, it can % be easily added by modifying this function % % [1] Abhijit Bendale, Terrance Boult "Towards Open World Recognition" % Computer Vision and Pattern Recognition Conference (CVPR) 2015 % % If you use this code, please cite the above paper [1]. % % Author: Abhijit Bendale ([email protected]) % Vision and Security Technology Lab % University of Colorado at Colorado Springs % Code Available at: http://vast.uccs.edu/OpenWorld % % OSNCM = Performance Number for Open Set NCM Classifier (or any other algorithm) % OSNNO = Performance Number for Open Set NNO Classifier (or any other algorithm) % xx = # Unknown Testing Categories e.g. [0, 100, 200, 500] % yy = # Vary Known Classes e.g. [200, 300, 400, 500] % figure;hold on colormap([1 0 1;0 0 1]) %red and blue surf(xx,yy, OSNCM', 'FaceColor','red','EdgeColor','black', 'MeshStyle', 'both', 'AlphaData', 0.5); %first color (red) surf(xx,yy, OSNNO', 'FaceColor','green','EdgeColor','white', 'MeshStyle', 'both'); %second color(blue) %line(xx,yymet, OSSVM','linewidth', 2, 'marker', 'o', 'color', 'c'); %line(xx,yymet, CSSVM','linewidth', 2, 'marker', '*', 'color','b'); alpha(0.55) LEG = legend('NCM','NNO'); set(LEG,'FontSize',15); xl = xlabel('# Unknown Testing Categories', 'Rotation', 13); yl = ylabel('# Known Training Categories', 'Rotation', -16); zl = zlabel('Top-1 Accuracy'); set(xl, 'FontSize',14) set(yl, 'FontSize',14) set(zl, 'FontSize',14) grid on camlight left; lighting phong view(139, 19) set(gcf, 'PaperPosition', [0 0 7 5]); set(gcf, 'PaperSize', [7 5]);
github
wme7/MultiGPU_AdvectionDiffusion-master
diffusion2dTest.m
.m
MultiGPU_AdvectionDiffusion-master/Matlab_Prototipes/DiffusionNd/diffusion2dTest.m
1,860
utf_8
5c2e8fdbee601257cce69d07c903db7c
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solving 2-D heat equation with jacobi method % % u_t = D*(u_xx + u_yy) + s(u), % for (x,y) \in [0,L]x[0,W] and S = s(u): source term % % coded by Manuel Diaz, manuel.ade'at'gmail.com % National Health Research Institutes, NHRI, 2016.02.11 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [L1,Linf] = diffusion2dTest(nx,ny,tFinal,param) %% Parameters D = 1.0; % alpha t0 = 0.1; % Initial time L = 10; dx = L/(nx-1); W = 10; dy = W/(ny-1); Dx = D/dx^2; Dy = D/dy^2; % Build Numerical Mesh [x,y] = meshgrid(-L/2:dx:L/2,-W/2:dy:W/2); % Add source term sourcefun='dont'; % add source term switch sourcefun case 'add'; S = @(w) 0.1*w.^2; case 'dont'; S = @(w) zeros(size(w)); end % Build IC d=1; u0 = exp( -(x.^2+y.^2)/(4*d*t0) ); % Build Exact solution uE = t0/tFinal*exp( -(x.^2+y.^2)/(4*d*tFinal) ); % Set Initial time step dt0 = 1/(2*D*(1/dx^2+1/dy^2))*param; % stability condition %% Solver Loop % load initial conditions t=t0; it=0; u=u0; dt=dt0; while t < tFinal % RK stages uo=u; % 1st stage dF=Laplace2d(u,nx,ny,Dx,Dy); u=uo+dt*dF; % 2nd Stage dF=Laplace2d(u,nx,ny,Dx,Dy); u=0.75*uo+0.25*(u+dt*dF); % 3rd stage dF=Laplace2d(u,nx,ny,Dx,Dy); u=(uo+2*(u+dt*dF))/3; % set BCs u(1,:) = 0; u(nx,:) = 0; u(:,1) = 0; u(:,ny) = 0; % compute time step if t+dt>tFinal, dt=tFinal-t; end; % Update iteration counter and time it=it+1; t=t+dt; end % Error norms err = abs(uE(:)-u(:)); L1 = dx*dy*sum(abs(err)); fprintf('L_1 norm: %1.2e \n',L1); L2 = (dx*dy*sum(err.^2))^0.5; fprintf('L_2 norm: %1.2e \n',L2); Linf = norm(err,inf); fprintf('L_inf norm: %1.2e \n',Linf);
github
wme7/MultiGPU_AdvectionDiffusion-master
diffusion1dTest.m
.m
MultiGPU_AdvectionDiffusion-master/Matlab_Prototipes/DiffusionNd/diffusion1dTest.m
1,724
utf_8
5dceb46128b35b857dee840a8bf932f4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solving 2-D heat equation with jacobi method % % u_t = D*(u_xx + u_yy) + s(u), % for (x,y) \in [0,L]x[0,W] and S = s(u): source term % % coded by Manuel Diaz, manuel.ade'at'gmail.com % National Health Research Institutes, NHRI, 2016.02.11 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [L1,Linf] = diffusion1dTest(nx,tFinal,param) %% Parameters D = 1.0; % alpha t0 = 0.1; % Initial time L = 10; dx = L/(nx-1); Dx = D/dx^2; % Build Numerical Mesh x = -L/2:dx:L/2; % Add source term sourcefun='dont'; % add source term switch sourcefun case 'add'; S = @(w) 0.1*w.^2; case 'dont'; S = @(w) zeros(size(w)); end % Build IC d=1; u0 = exp( -x.^2/(4*d*t0) ); % Build Exact solution uE = sqrt(t0/tFinal)*exp( -x.^2/(4*d*tFinal) ); % Set Initial time step dt0 = 1/(2*D*(1/dx^2))*param; % stability condition %% Solver Loop % load initial conditions t=t0; it=0; u=u0; dt=dt0; while t < tFinal % RK stages uo=u; % 1st stage dF=Laplace1d(u,nx,Dx); u=uo+dt*dF; % 2nd Stage dF=Laplace1d(u,nx,Dx); u=0.75*uo+0.25*(u+dt*dF); % 3rd stage dF=Laplace1d(u,nx,Dx); u=(uo+2*(u+dt*dF))/3; % set BCs u(1) = 0; u(nx) = 0; % compute time step if t+dt>tFinal, dt=tFinal-t; end; % Update iteration counter and time it=it+1; t=t+dt; end % Error norms err = abs(uE(:)-u(:)); L1 = dx*sum(abs(err)); fprintf('L_1 norm: %1.2e \n',L1); L2 = (dx*sum(err.^2))^0.5; fprintf('L_2 norm: %1.2e \n',L2); Linf = norm(err,inf); fprintf('L_inf norm: %1.2e \n',Linf);
github
wme7/MultiGPU_AdvectionDiffusion-master
diffusion3dTest.m
.m
MultiGPU_AdvectionDiffusion-master/Matlab_Prototipes/DiffusionNd/diffusion3dTest.m
2,010
utf_8
370e428c010b3f77f0bbb480b6fa1455
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solving 3-D heat equation with jacobi method % % u_t = D*(u_xx + u_yy + u_zz) + s(u), % for (x,y,z) \in [0,L]x[0,W]x[0,H] and S = s(u): source term % % coded by Manuel Diaz, manuel.ade'at'gmail.com % National Health Research Institutes, NHRI, 2016.02.11 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [L1,Linf] = diffusion3dTest(nx,ny,nz,tFinal,param) %% Parameters D = 1.0; % alpha t0 = 0.1; % Initial time L = 10; dx = L/(nx-1); W = 10; dy = W/(ny-1); H = 10; dz = H/(nz-1); Dx = D/dx^2; Dy = D/dy^2; Dz = D/dz^2; % Build Numerical Mesh [x,y,z] = meshgrid(-L/2:dx:L/2,-W/2:dy:W/2,-H/2:dz:H/2); % Add source term sourcefun='dont'; % add source term switch sourcefun case 'add'; S = @(w) 0.1*w.^2; case 'dont'; S = @(w) zeros(size(w)); end % Build IC d=1; u0 = exp( -(x.^2+y.^2+z.^2)/(4*d*t0) ); % Build Exact solution uE = (t0/tFinal)^1.5*exp( -(x.^2+y.^2+z.^2)/(4*d*tFinal) ); % Set Initial time step dt0 = 1/(2*D*(1/dx^2+1/dy^2+1/dz^2))*param; % stability condition %% Solver Loop % load initial conditions t=t0; it=0; u=u0; dt=dt0; while t < tFinal % RK stages uo=u; % 1st stage dF=Laplace3d(u,nx,ny,nz,Dx,Dy,Dz); u=uo+dt*dF; % 2nd Stage dF=Laplace3d(u,nx,ny,nz,Dx,Dy,Dz); u=0.75*uo+0.25*(u+dt*dF); % 3rd stage dF=Laplace3d(u,nx,ny,nz,Dx,Dy,Dz); u=(uo+2*(u+dt*dF))/3; % set BCs u(1,:,:) = 0; u(nx,:,:) = 0; u(:,1,:) = 0; u(:,ny,:) = 0; u(:,:,1) = 0; u(:,:,nz) = 0; % compute time step if t+dt>tFinal, dt=tFinal-t; end; % Update iteration counter and time it=it+1; t=t+dt; end % Error norms err = abs(uE(:)-u(:)); L1 = dx*dy*dz*sum(abs(err)); fprintf('L_1 norm: %1.2e \n',L1); L2 = (dx*dy*dz*sum(err.^2))^0.5; fprintf('L_2 norm: %1.2e \n',L2); Linf = norm(err,inf); fprintf('L_inf norm: %1.2e \n',Linf);
github
yhw-yhw/caffe_rtpose-master
classification_demo.m
.m
caffe_rtpose-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
zhxing001/DIP_exercise-master
vanherk.m
.m
DIP_exercise-master/matlab/defog_hekaiming/vanherk.m
4,665
utf_8
29b98c380fda32f85f9b5f3d68ad8529
function Y = vanherk(X,N,TYPE,varargin) % VANHERK Fast max/min 1D filter % % Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row % vector X using a N-length filter. % The filtering type is defined by TYPE = 'max' or 'min'. This function % uses the van Herk algorithm for min/max filters that demands only 3 % min/max calculations per element, independently of the filter size. % % If X is a 2D matrix, each row will be filtered separately. % % Y = VANHERK(...,'col') performs the filtering on the columns of X. % % Y = VANHERK(...,'shape') returns the subset of the filtering specified % by 'shape' : % 'full' - Returns the full filtering result, % 'same' - (default) Returns the central filter area that is the % same size as X, % 'valid' - Returns only the area where no filter elements are outside % the image. % % X can be uint8 or double. If X is uint8 the processing is quite faster, so % dont't use X as double, unless it is really necessary. % % Initialization [direc, shape] = parse_inputs(varargin{:}); if strcmp(direc,'col') X = X'; end if strcmp(TYPE,'max') maxfilt = 1; elseif strcmp(TYPE,'min') maxfilt = 0; else error([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.']) end % Correcting X size fixsize = 0; addel = 0; if mod(size(X,2),N) ~= 0 fixsize = 1; addel = N-mod(size(X,2),N); if maxfilt f = [ X zeros(size(X,1), addel) ]; else f = [X repmat(X(:,end),1,addel)]; end else f = X; end lf = size(f,2); lx = size(X,2); clear X % Declaring aux. mat. g = f; h = g; % Filling g & h (aux. mat.) ig = 1:N:size(f,2); ih = ig + N - 1; g(:,ig) = f(:,ig); h(:,ih) = f(:,ih); if maxfilt for i = 2 : N igold = ig; ihold = ih; ig = ig + 1; ih = ih - 1; g(:,ig) = max(f(:,ig),g(:,igold)); h(:,ih) = max(f(:,ih),h(:,ihold)); end else for i = 2 : N igold = ig; ihold = ih; ig = ig + 1; ih = ih - 1; g(:,ig) = min(f(:,ig),g(:,igold)); h(:,ih) = min(f(:,ih),h(:,ihold)); end end clear f % Comparing g & h if strcmp(shape,'full') ig = [ N : 1 : lf ]; ih = [ 1 : 1 : lf-N+1 ]; if fixsize if maxfilt Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ]; else Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ]; end else if maxfilt Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end) ]; else Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end) ]; end end elseif strcmp(shape,'same') if fixsize if addel > (N-1)/2 disp('hoi') ig = [ N : 1 : lf - addel + floor((N-1)/2) ]; ih = [ 1 : 1 : lf-N+1 - addel + floor((N-1)/2)]; if maxfilt Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) ]; else Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) ]; end else ig = [ N : 1 : lf ]; ih = [ 1 : 1 : lf-N+1 ]; if maxfilt Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ]; else Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ]; end end else % not fixsize (addel=0, lf=lx) ig = [ N : 1 : lx ]; ih = [ 1 : 1 : lx-N+1 ]; if maxfilt Y = [ g(:,N-ceil((N-1)/2):N-1) max( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ]; else Y = [ g(:,N-ceil((N-1)/2):N-1) min( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ]; end end elseif strcmp(shape,'valid') ig = [ N : 1 : lx]; ih = [ 1 : 1: lx-N+1]; if maxfilt Y = [ max( g(:,ig), h(:,ih) ) ]; else Y = [ min( g(:,ig), h(:,ih) ) ]; end end if strcmp(direc,'col') Y = Y'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [direc, shape] = parse_inputs(varargin) direc = 'lin'; shape = 'same'; flag = [0 0]; % [dir shape] for i = 1 : nargin t = varargin{i}; if strcmp(t,'col') & flag(1) == 0 direc = 'col'; flag(1) = 1; elseif strcmp(t,'full') & flag(2) == 0 shape = 'full'; flag(2) = 1; elseif strcmp(t,'same') & flag(2) == 0 shape = 'same'; flag(2) = 1; elseif strcmp(t,'valid') & flag(2) == 0 shape = 'valid'; flag(2) = 1; else error(['Too many / Unkown parameter : ' t ]) end end
github
zhxing001/DIP_exercise-master
maxfilt2.m
.m
DIP_exercise-master/matlab/defog_hekaiming/maxfilt2.m
1,784
utf_8
30164e098eb4173079a7fe2779af8e60
function Y = maxfilt2(X,varargin) % MAXFILT2 Two-dimensional max filter % % Y = MAXFILT2(X,[M N]) performs two-dimensional maximum % filtering on the image X using an M-by-N window. The result % Y contains the maximun value in the M-by-N neighborhood around % each pixel in the original image. % This function uses the van Herk algorithm for max filters. % % Y = MAXFILT2(X,M) is the same as Y = MAXFILT2(X,[M M]) % % Y = MAXFILT2(X) uses a 3-by-3 neighborhood. % % Y = MAXFILT2(..., 'shape') returns a subsection of the 2D % filtering specified by 'shape' : % 'full' - Returns the full filtering result, % 'same' - (default) Returns the central filter area that is the % same size as X, % 'valid' - Returns only the area where no filter elements are outside % the image. % % See also : MINFILT2, VANHERK % % Initialization [S, shape] = parse_inputs(varargin{:}); % filtering Y = vanherk(X,S(1),'max',shape); Y = vanherk(Y,S(2),'max','col',shape); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [S, shape] = parse_inputs(varargin) shape = 'same'; flag = [0 0]; % size shape for i = 1 : nargin t = varargin{i}; if strcmp(t,'full') & flag(2) == 0 shape = 'full'; flag(2) = 1; elseif strcmp(t,'same') & flag(2) == 0 shape = 'same'; flag(2) = 1; elseif strcmp(t,'valid') & flag(2) == 0 shape = 'valid'; flag(2) = 1; elseif flag(1) == 0 S = t; flag(1) = 1; else error(['Too many / Unkown parameter : ' t ]) end end if flag(1) == 0 S = [3 3]; end if length(S) == 1; S(2) = S(1); end if length(S) ~= 2 error('Wrong window size parameter.') end
github
zhxing001/DIP_exercise-master
minfilt2.m
.m
DIP_exercise-master/matlab/defog_hekaiming/minfilt2.m
1,784
utf_8
0100bdead43e5b8aad8f8e1e40699621
function Y = minfilt2(X,varargin) % MINFILT2 Two-dimensional min filter % % Y = MINFILT2(X,[M N]) performs two-dimensional minimum % filtering on the image X using an M-by-N window. The result % Y contains the minimun value in the M-by-N neighborhood around % each pixel in the original image. % This function uses the van Herk algorithm for min filters. % % Y = MINFILT2(X,M) is the same as Y = MINFILT2(X,[M M]) % % Y = MINFILT2(X) uses a 3-by-3 neighborhood. % % Y = MINFILT2(..., 'shape') returns a subsection of the 2D % filtering specified by 'shape' : % 'full' - Returns the full filtering result, % 'same' - (default) Returns the central filter area that is the % same size as X, % 'valid' - Returns only the area where no filter elements are outside % the image. % % See also : MAXFILT2, VANHERK % % Initialization [S, shape] = parse_inputs(varargin{:}); % filtering Y = vanherk(X,S(1),'min',shape); Y = vanherk(Y,S(2),'min','col',shape); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [S, shape] = parse_inputs(varargin) shape = 'same'; flag = [0 0]; % size shape for i = 1 : nargin t = varargin{i}; if strcmp(t,'full') & flag(2) == 0 shape = 'full'; flag(2) = 1; elseif strcmp(t,'same') & flag(2) == 0 shape = 'same'; flag(2) = 1; elseif strcmp(t,'valid') & flag(2) == 0 shape = 'valid'; flag(2) = 1; elseif flag(1) == 0 S = t; flag(1) = 1; else error(['Too many / Unkown parameter : ' t ]) end end if flag(1) == 0 S = [3 3]; end if length(S) == 1; S(2) = S(1); end if length(S) ~= 2 error('Wrong window size parameter.') end
github
zhxing001/DIP_exercise-master
buildWpyr.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/buildWpyr.m
2,605
utf_8
16663cdfba931a8f5e2ae6a4477253d0
% [PYR, INDICES] = buildWpyr(IM, HEIGHT, FILT, EDGES) % % Construct a separable orthonormal QMF/wavelet pyramid on matrix (or vector) IM. % % HEIGHT (optional) specifies the number of pyramid levels to build. Default % is maxPyrHt(IM,FILT). You can also specify 'auto' to use this value. % % FILT (optional) can be a string naming a standard filter (see % namedFilter), or a vector which will be used for (separable) % convolution. Filter can be of even or odd length, but should be symmetric. % Default = 'qmf9'. EDGES specifies edge-handling, and % defaults to 'reflect1' (see corrDn). % % PYR is a vector containing the N pyramid subbands, ordered from fine % to coarse. INDICES is an Nx2 matrix containing the sizes of % each subband. This is compatible with the MatLab Wavelet toolbox. % Eero Simoncelli, 6/96. function [pyr,pind] = buildWpyr(im, ht, filt, edges) if (nargin < 1) error('First argument (IM) is required'); end %------------------------------------------------------------ %% OPTIONAL ARGS: if (exist('filt') ~= 1) filt = 'qmf9'; end if (exist('edges') ~= 1) edges= 'reflect1'; end if isstr(filt) filt = namedFilter(filt); end if ( (size(filt,1) > 1) & (size(filt,2) > 1) ) error('FILT should be a 1D filter (i.e., a vector)'); else filt = filt(:); end hfilt = modulateFlip(filt); % Stagger sampling if filter is odd-length: if (mod(size(filt,1),2) == 0) stag = 2; else stag = 1; end im_sz = size(im); max_ht = maxPyrHt(im_sz, size(filt,1)); if ( (exist('ht') ~= 1) | (ht == 'auto') ) ht = max_ht; else if (ht > max_ht) error(sprintf('Cannot build pyramid higher than %d levels.',max_ht)); end end if (ht <= 0) pyr = im(:); pind = im_sz; else if (im_sz(2) == 1) lolo = corrDn(im, filt, edges, [2 1], [stag 1]); hihi = corrDn(im, hfilt, edges, [2 1], [2 1]); elseif (im_sz(1) == 1) lolo = corrDn(im, filt', edges, [1 2], [1 stag]); hihi = corrDn(im, hfilt', edges, [1 2], [1 2]); else lo = corrDn(im, filt, edges, [2 1], [stag 1]); hi = corrDn(im, hfilt, edges, [2 1], [2 1]); lolo = corrDn(lo, filt', edges, [1 2], [1 stag]); lohi = corrDn(hi, filt', edges, [1 2], [1 stag]); % horizontal hilo = corrDn(lo, hfilt', edges, [1 2], [1 2]); % vertical hihi = corrDn(hi, hfilt', edges, [1 2], [1 2]); % diagonal end [npyr,nind] = buildWpyr(lolo, ht-1, filt, edges); if ((im_sz(1) == 1) | (im_sz(2) == 1)) pyr = [hihi(:); npyr]; pind = [size(hihi); nind]; else pyr = [lohi(:); hilo(:); hihi(:); npyr]; pind = [size(lohi); size(hilo); size(hihi); nind]; end end
github
zhxing001/DIP_exercise-master
pyrBand.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/pyrBand.m
395
utf_8
39c1e3772426a1362119d302d9767a24
% RES = pyrBand(PYR, INDICES, BAND_NUM) % % Access a subband from a pyramid (gaussian, laplacian, QMF/wavelet, % or steerable). Subbands are numbered consecutively, from finest % (highest spatial frequency) to coarsest (lowest spatial frequency). % Eero Simoncelli, 6/96. function res = pyrBand(pyr, pind, band) res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) );
github
zhxing001/DIP_exercise-master
buildFullSFpyr2.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/buildFullSFpyr2.m
3,031
utf_8
4a1191e10f08e0d219040bdc7864a575
% [PYR, INDICES, STEERMTX, HARMONICS] = buildFullSFpyr2(IM, HEIGHT, ORDER, TWIDTH) % % Construct a steerable pyramid on matrix IM, in the Fourier domain. % Unlike the standard transform, subdivides the highpass band into % orientations. function [pyr,pind,steermtx,harmonics] = buildFullSFpyr2(im, ht, order, twidth) %----------------------------------------------------------------- %% DEFAULTS: max_ht = floor(log2(min(size(im)))+1); if (exist('ht') ~= 1) ht = max_ht; else if (ht > max_ht) error(sprintf('Cannot build pyramid higher than %d levels.',max_ht)); end end if (exist('order') ~= 1) order = 3; elseif ((order > 15) | (order < 0)) fprintf(1,'Warning: ORDER must be an integer in the range [0,15]. Truncating.\n'); order = min(max(order,0),15); else order = round(order); end nbands = order+1; if (exist('twidth') ~= 1) twidth = 1; elseif (twidth <= 0) fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n'); twidth = 1; end %----------------------------------------------------------------- %% Steering stuff: if (mod((nbands),2) == 0) harmonics = [0:(nbands/2)-1]'*2 + 1; else harmonics = [0:(nbands-1)/2]'*2; end steermtx = steer2HarmMtx(harmonics, pi*[0:nbands-1]/nbands, 'even'); %----------------------------------------------------------------- dims = size(im); ctr = ceil((dims+0.5)/2); [xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ... ([1:dims(1)]-ctr(1))./(dims(1)/2) ); angle = atan2(yramp,xramp); log_rad = sqrt(xramp.^2 + yramp.^2); log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1); log_rad = log2(log_rad); %% Radial transition function (a raised cosine in log-frequency): [Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]); Yrcos = sqrt(Yrcos); YIrcos = sqrt(1.0 - Yrcos.^2); lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); imdft = fftshift(fft2(im)); lo0dft = imdft .* lo0mask; [pyr,pind] = buildSFpyrLevs(lo0dft, log_rad, Xrcos, Yrcos, angle, ht, nbands); %% Split the highpass band into orientations hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; bands = zeros(prod(size(imdft)), nbands); bind = zeros(nbands,2); for b = 1:nbands anglemask = pointOp(angle, Ycosn, Xcosn(1)+pi*(b-1)/nbands, Xcosn(2)-Xcosn(1)); Mask = ((-sqrt(-1))^(nbands-1))*anglemask.*hi0mask; % make real the contents in the HF cross (to avoid information loss in these freqs.) % It distributes evenly these contents among the nbands orientations Mask(1,:) = ones(1,size(im,2))/sqrt(nbands); Mask(2:size(im,1),1) = ones(size(im,1)-1,1)/sqrt(nbands); banddft = imdft .* Mask; band = real(ifft2(fftshift(banddft))); bands(:,b) = real(band(:)); bind(b,:) = size(band); end pyr = [bands(:); pyr]; pind = [bind; pind]; pind = [ [0 0]; pind]; %% Dummy highpass
github
zhxing001/DIP_exercise-master
var2.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/var2.m
376
utf_8
ecdc1380cd3f7549b769d86bc0a25e12
% V = VAR2(MTX,MEAN) % % Sample variance of a matrix. % Passing MEAN (optional) makes the calculation faster. function res = var2(mtx, mn) if (exist('mn') ~= 1) mn = mean2(mtx); end if (isreal(mtx)) res = sum(sum(abs(mtx-mn).^2)) / (prod(size(mtx)) - 1); else res = sum(sum(real(mtx-mn).^2)) + i*sum(sum(imag(mtx-mn).^2)); res = res / (prod(size(mtx)) - 1); end
github
zhxing001/DIP_exercise-master
reconSFpyrLevs.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/reconSFpyrLevs.m
1,945
utf_8
11703edfa70ae1e00ba5819c7497efd3
% RESDFT = reconSFpyrLevs(PYR,INDICES,LOGRAD,XRCOS,YRCOS,ANGLE,NBANDS,LEVS,BANDS) % % Recursive function for reconstructing levels of a steerable pyramid % representation. This is called by reconSFpyr, and is not usually % called directly. % Eero Simoncelli, 5/97. function resdft = reconSFpyrLevs(pyr,pind,log_rad,Xrcos,Yrcos,angle,nbands,levs,bands); lo_ind = nbands+1; dims = pind(1,:); ctr = ceil((dims+0.5)/2); log_rad = log_rad + 1; if any(levs > 1) lodims = ceil((dims-0.5)/2); loctr = ceil((lodims+0.5)/2); lostart = ctr-loctr+1; loend = lostart+lodims-1; nlog_rad = log_rad(lostart(1):loend(1),lostart(2):loend(2)); nangle = angle(lostart(1):loend(1),lostart(2):loend(2)); if (size(pind,1) > lo_ind) nresdft = reconSFpyrLevs( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)),... pind(lo_ind:size(pind,1),:), ... nlog_rad, Xrcos, Yrcos, nangle, nbands,levs-1, bands); else nresdft = fftshift(fft2(pyrBand(pyr,pind,lo_ind))); end YIrcos = sqrt(abs(1.0 - Yrcos.^2)); lomask = pointOp(nlog_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); resdft = zeros(dims); resdft(lostart(1):loend(1),lostart(2):loend(2)) = nresdft .* lomask; else resdft = zeros(dims); end if any(levs == 1) lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1),0); ind = 1; for b = 1:nbands if any(bands == b) anglemask = pointOp(angle,Ycosn,Xcosn(1)+pi*(b-1)/nbands,Xcosn(2)-Xcosn(1)); band = reshape(pyr(ind:ind+prod(dims)-1), dims(1), dims(2)); banddft = fftshift(fft2(band)); resdft = resdft + (i)^(nbands-1) * banddft.*anglemask.*himask; end ind = ind + prod(dims); end end
github
zhxing001/DIP_exercise-master
rcosFn.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/rcosFn.m
1,122
utf_8
36283e0a34f1baf7ea2c5e6cb23aab89
% [X, Y] = rcosFn(WIDTH, POSITION, VALUES) % % Return a lookup table (suitable for use by INTERP1) % containing a "raised cosine" soft threshold function: % % Y = VALUES(1) + (VALUES(2)-VALUES(1)) * % cos^2( PI/2 * (X - POSITION + WIDTH)/WIDTH ) % % WIDTH is the width of the region over which the transition occurs % (default = 1). POSITION is the location of the center of the % threshold (default = 0). VALUES (default = [0,1]) specifies the % values to the left and right of the transition. % Eero Simoncelli, 7/96. function [X, Y] = rcosFn(width,position,values) %------------------------------------------------------------ % OPTIONAL ARGS: if (exist('width') ~= 1) width = 1; end if (exist('position') ~= 1) position = 0; end if (exist('values') ~= 1) values = [0,1]; end %------------------------------------------------------------ sz = 256; %% arbitrary! X = pi * [-sz-1:1] / (2*sz); Y = values(1) + (values(2)-values(1)) * cos(X).^2; % Make sure end values are repeated, for extrapolation... Y(1) = Y(2); Y(sz+3) = Y(sz+2); X = position + (2*width/pi) * (X + pi/4);
github
zhxing001/DIP_exercise-master
vector.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/vector.m
231
utf_8
a3c1b483d801607eaef848381d85f189
% [VEC] = vector(MTX) % % Pack elements of MTX into a column vector. Same as VEC = MTX(:) % Previously named "vectorize" (changed to avoid overlap with Matlab's % "vectorize" function). function vec = vector(mtx) vec = mtx(:);
github
zhxing001/DIP_exercise-master
showIm.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/showIm.m
6,111
utf_8
15fbbf55e2fd54e3f48ca936e23c3f32
% RANGE = showIm (MATRIX, RANGE, ZOOM, LABEL, NSHADES ) % % Display a MatLab MATRIX as a grayscale image in the current figure, % inside the current axes. If MATRIX is complex, the real and imaginary % parts are shown side-by-side, with the same grayscale mapping. % % If MATRIX is a string, it should be the name of a variable bound to a % MATRIX in the base (global) environment. This matrix is displayed as an % image, with the title set to the string. % % RANGE (optional) is a 2-vector specifying the values that map to % black and white, respectively. Passing a value of 'auto' (default) % sets RANGE=[min,max] (as in MatLab's imagesc). 'auto2' sets % RANGE=[mean-2*stdev, mean+2*stdev]. 'auto3' sets % RANGE=[p1-(p2-p1)/8, p2+(p2-p1)/8], where p1 is the 10th percentile % value of the sorted MATRIX samples, and p2 is the 90th percentile % value. % % ZOOM specifies the number of matrix samples per screen pixel. It % will be rounded to an integer, or 1 divided by an integer. A value % of 'same' or 'auto' (default) causes the zoom value to be chosen % automatically to fit the image into the current axes. A value of % 'full' fills the axis region (leaving no room for labels). See % pixelAxes.m. % % If LABEL (optional, default = 1, unless zoom='full') is non-zero, the range % of values that are mapped into the gray colormap and the dimensions % (size) of the matrix and zoom factor are printed below the image. If label % is a string, it is used as a title. % % NSHADES (optional) specifies the number of gray shades, and defaults % to the size of the current colormap. % Eero Simoncelli, 6/96. %%TODO: should use "newplot" function range = showIm( im, range, zoom, label, nshades ); %------------------------------------------------------------ %% OPTIONAL ARGS: if (nargin < 1) error('Requires at least one input argument.'); end MLv = version; if isstr(im) if (strcmp(MLv(1),'4')) error('Cannot pass string arg for MATRIX in MatLab version 4.x'); end label = im; im = evalin('base',im); end if (exist('range') ~= 1) range = 'auto1'; end if (exist('nshades') ~= 1) nshades = size(colormap,1); end nshades = max( nshades, 2 ); if (exist('zoom') ~= 1) zoom = 'auto'; end if (exist('label') ~= 1) if strcmp(zoom,'full') label = 0; % no labeling else label = 1; % just print grayrange & dims end end %------------------------------------------------------------ %% Automatic range calculation: if (strcmp(range,'auto1') | strcmp(range,'auto')) if isreal(im) [mn,mx] = range2(im); else [mn1,mx1] = range2(real(im)); [mn2,mx2] = range2(imag(im)); mn = min(mn1,mn2); mx = max(mx1,mx2); end if any(size(im)==1) pad = (mx-mn)/12; % MAGIC NUMBER: graph padding range = [mn-pad, mx+pad]; else range = [mn,mx]; end elseif strcmp(range,'auto2') if isreal(im) stdev = sqrt(var2(im)); av = mean2(im); else stdev = sqrt((var2(real(im)) + var2(imag(im)))/2); av = (mean2(real(im)) + mean2(imag(im)))/2; end range = [av-2*stdev,av+2*stdev]; % MAGIC NUMBER: 2 stdevs elseif strcmp(range, 'auto3') percentile = 0.1; % MAGIC NUMBER: 0<p<0.5 [N,X] = histo(im); binsz = X(2)-X(1); N = N+1e-10; % Ensure cumsum will be monotonic for call to interp1 cumN = [0, cumsum(N)]/sum(N); cumX = [X(1)-binsz, X] + (binsz/2); ctrRange = interp1(cumN,cumX, [percentile, 1-percentile]); range = mean(ctrRange) + (ctrRange-mean(ctrRange))/(1-2*percentile); elseif isstr(range) error(sprintf('Bad RANGE argument: %s',range)) end if ((range(2) - range(1)) <= eps) range(1) = range(1) - 0.5; range(2) = range(2) + 0.5; end if isreal(im) factor=1; else factor = 1+sqrt(-1); end xlbl_offset = 0; % default value if (~any(size(im)==1)) %% MatLab's "image" rounds when mapping to the colormap, so we compute %% (im-r1)*(nshades-1)/(r2-r1) + 1.5 mult = ((nshades-1) / (range(2)-range(1))); d_im = (mult * im) + factor*(1.5 - range(1)*mult); end if isreal(im) if (any(size(im)==1)) hh = plot( im); axis([1, prod(size(im)), range]); else hh = image( d_im ); axis('off'); zoom = pixelAxes(size(d_im),zoom); end else if (any(size(im)==1)) subplot(2,1,1); hh = plot(real(im)); axis([1, prod(size(im)), range]); subplot(2,1,2); hh = plot(imag(im)); axis([1, prod(size(im)), range]); else subplot(1,2,1); hh = image(real(d_im)); axis('off'); zoom = pixelAxes(size(d_im),zoom); ax = gca; orig_units = get(ax,'Units'); set(ax,'Units','points'); pos1 = get(ax,'Position'); set(ax,'Units',orig_units); subplot(1,2,2); hh = image(imag(d_im)); axis('off'); zoom = pixelAxes(size(d_im),zoom); ax = gca; orig_units = get(ax,'Units'); set(ax,'Units','points'); pos2 = get(ax,'Position'); set(ax,'Units',orig_units); xlbl_offset = (pos1(1)-pos2(1))/2; end end if ~any(size(im)==1) colormap(gray(nshades)); end if ((label ~= 0)) if isstr(label) title(label); h = get(gca,'Title'); orig_units = get(h,'Units'); set(h,'Units','points'); pos = get(h,'Position'); pos(1:2) = pos(1:2) + [xlbl_offset, -3]; % MAGIC NUMBER: y pixel offset set(h,'Position',pos); set(h,'Units',orig_units); end if (~any(size(im)==1)) if (zoom > 1) zformat = sprintf('* %d',round(zoom)); else zformat = sprintf('/ %d',round(1/zoom)); end if isreal(im) format=[' Range: [%.3g, %.3g] \n Dims: [%d, %d] ', zformat]; else format=['Range: [%.3g, %.3g] ---- Dims: [%d, %d]', zformat]; end xlabel(sprintf(format, range(1), range(2), size(im,1), size(im,2))); h = get(gca,'Xlabel'); set(h,'FontSize', 9); % MAGIC NUMBER: font size!!! orig_units = get(h,'Units'); set(h,'Units','points'); pos = get(h,'Position'); pos(1:2) = pos(1:2) + [xlbl_offset, 10]; % MAGIC NUMBER: y offset in points set(h,'Position',pos); set(h,'Units',orig_units); set(h,'Visible','on'); % axis('image') turned the xlabel off... end end return;