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 | christiannkoch/CATANA-master | detect_face_v1.m | .m | CATANA-master/src/face_recognition/facenet/tmp/detect_face_v1.m | 7,954 | utf_8 | 678c2105b8d536f8bbe08d3363b69642 | % MIT License
%
% Copyright (c) 2016 Kaipeng Zhang
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function [total_boxes, points] = detect_face_v1(img,minsize,PNet,RNet,ONet,threshold,fastresize,factor)
%im: input image
%minsize: minimum of faces' size
%pnet, rnet, onet: caffemodel
%threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold
%fastresize: resize img from last scale (using in high-resolution images) if fastresize==true
factor_count=0;
total_boxes=[];
points=[];
h=size(img,1);
w=size(img,2);
minl=min([w h]);
img=single(img);
if fastresize
im_data=(single(img)-127.5)*0.0078125;
end
m=12/minsize;
minl=minl*m;
%creat scale pyramid
scales=[];
while (minl>=12)
scales=[scales m*factor^(factor_count)];
minl=minl*factor;
factor_count=factor_count+1;
end
%first stage
for j = 1:size(scales,2)
scale=scales(j);
hs=ceil(h*scale);
ws=ceil(w*scale);
if fastresize
im_data=imResample(im_data,[hs ws],'bilinear');
else
im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125;
end
PNet.blobs('data').reshape([hs ws 3 1]);
out=PNet.forward({im_data});
boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1));
%inter-scale nms
pick=nms(boxes,0.5,'Union');
boxes=boxes(pick,:);
if ~isempty(boxes)
total_boxes=[total_boxes;boxes];
end
end
numbox=size(total_boxes,1);
if ~isempty(total_boxes)
pick=nms(total_boxes,0.7,'Union');
total_boxes=total_boxes(pick,:);
regw=total_boxes(:,3)-total_boxes(:,1);
regh=total_boxes(:,4)-total_boxes(:,2);
total_boxes=[total_boxes(:,1)+total_boxes(:,6).*regw total_boxes(:,2)+total_boxes(:,7).*regh total_boxes(:,3)+total_boxes(:,8).*regw total_boxes(:,4)+total_boxes(:,9).*regh total_boxes(:,5)];
total_boxes=rerec(total_boxes);
total_boxes(:,1:4)=fix(total_boxes(:,1:4));
[dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h);
end
numbox=size(total_boxes,1);
if numbox>0
%second stage
tempimg=zeros(24,24,3,numbox);
for k=1:numbox
tmp=zeros(tmph(k),tmpw(k),3);
tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:);
if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0
tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear');
else
total_boxes = [];
return;
end;
end
tempimg=(tempimg-127.5)*0.0078125;
RNet.blobs('data').reshape([24 24 3 numbox]);
out=RNet.forward({tempimg});
score=squeeze(out{2}(2,:));
pass=find(score>threshold(2));
total_boxes=[total_boxes(pass,1:4) score(pass)'];
mv=out{1}(:,pass);
if size(total_boxes,1)>0
pick=nms(total_boxes,0.7,'Union');
total_boxes=total_boxes(pick,:);
total_boxes=bbreg(total_boxes,mv(:,pick)');
total_boxes=rerec(total_boxes);
end
numbox=size(total_boxes,1);
if numbox>0
%third stage
total_boxes=fix(total_boxes);
[dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h);
tempimg=zeros(48,48,3,numbox);
for k=1:numbox
tmp=zeros(tmph(k),tmpw(k),3);
tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:);
if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0
tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear');
else
total_boxes = [];
return;
end;
end
tempimg=(tempimg-127.5)*0.0078125;
ONet.blobs('data').reshape([48 48 3 numbox]);
out=ONet.forward({tempimg});
score=squeeze(out{3}(2,:));
points=out{2};
pass=find(score>threshold(3));
points=points(:,pass);
total_boxes=[total_boxes(pass,1:4) score(pass)'];
mv=out{1}(:,pass);
w=total_boxes(:,3)-total_boxes(:,1)+1;
h=total_boxes(:,4)-total_boxes(:,2)+1;
points(1:5,:)=repmat(w',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1;
points(6:10,:)=repmat(h',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1;
if size(total_boxes,1)>0
total_boxes=bbreg(total_boxes,mv(:,:)');
pick=nms(total_boxes,0.7,'Min');
total_boxes=total_boxes(pick,:);
points=points(:,pick);
end
end
end
end
function [boundingbox] = bbreg(boundingbox,reg)
%calibrate bouding boxes
if size(reg,2)==1
reg=reshape(reg,[size(reg,3) size(reg,4)])';
end
w=[boundingbox(:,3)-boundingbox(:,1)]+1;
h=[boundingbox(:,4)-boundingbox(:,2)]+1;
boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h];
end
function [boundingbox reg] = generateBoundingBox(map,reg,scale,t)
%use heatmap to generate bounding boxes
stride=2;
cellsize=12;
boundingbox=[];
map=map';
dx1=reg(:,:,1)';
dy1=reg(:,:,2)';
dx2=reg(:,:,3)';
dy2=reg(:,:,4)';
[y x]=find(map>=t);
a=find(map>=t);
if size(y,1)==1
y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2';
else
score=map(a);
end
reg=[dx1(a) dy1(a) dx2(a) dy2(a)];
if isempty(reg)
reg=reshape([],[0 3]);
end
boundingbox=[y x];
boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg];
end
function pick = nms(boxes,threshold,type)
%NMS
if isempty(boxes)
pick = [];
return;
end
x1 = boxes(:,1);
y1 = boxes(:,2);
x2 = boxes(:,3);
y2 = boxes(:,4);
s = boxes(:,5);
area = (x2-x1+1) .* (y2-y1+1);
[vals, I] = sort(s);
pick = s*0;
counter = 1;
while ~isempty(I)
last = length(I);
i = I(last);
pick(counter) = i;
counter = counter + 1;
xx1 = max(x1(i), x1(I(1:last-1)));
yy1 = max(y1(i), y1(I(1:last-1)));
xx2 = min(x2(i), x2(I(1:last-1)));
yy2 = min(y2(i), y2(I(1:last-1)));
w = max(0.0, xx2-xx1+1);
h = max(0.0, yy2-yy1+1);
inter = w.*h;
if strcmp(type,'Min')
o = inter ./ min(area(i),area(I(1:last-1)));
else
o = inter ./ (area(i) + area(I(1:last-1)) - inter);
end
I = I(find(o<=threshold));
end
pick = pick(1:(counter-1));
end
function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h)
%compute the padding coordinates (pad the bounding boxes to square)
tmpw=total_boxes(:,3)-total_boxes(:,1)+1;
tmph=total_boxes(:,4)-total_boxes(:,2)+1;
numbox=size(total_boxes,1);
dx=ones(numbox,1);dy=ones(numbox,1);
edx=tmpw;edy=tmph;
x=total_boxes(:,1);y=total_boxes(:,2);
ex=total_boxes(:,3);ey=total_boxes(:,4);
tmp=find(ex>w);
edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w;
tmp=find(ey>h);
edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h;
tmp=find(x<1);
dx(tmp)=2-x(tmp);x(tmp)=1;
tmp=find(y<1);
dy(tmp)=2-y(tmp);y(tmp)=1;
end
function [bboxA] = rerec(bboxA)
%convert bboxA to square
bboxB=bboxA(:,1:4);
h=bboxA(:,4)-bboxA(:,2);
w=bboxA(:,3)-bboxA(:,1);
l=max([w h]')';
bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5;
bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5;
bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]);
end
|
github | christiannkoch/CATANA-master | detect_face_v2.m | .m | CATANA-master/src/face_recognition/facenet/tmp/detect_face_v2.m | 9,016 | utf_8 | 0c963a91d4e52c98604dd6ca7a99d837 | % MIT License
%
% Copyright (c) 2016 Kaipeng Zhang
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function [total_boxes, points] = detect_face_v2(img,minsize,PNet,RNet,ONet,LNet,threshold,fastresize,factor)
%im: input image
%minsize: minimum of faces' size
%pnet, rnet, onet: caffemodel
%threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold
%fastresize: resize img from last scale (using in high-resolution images) if fastresize==true
factor_count=0;
total_boxes=[];
points=[];
h=size(img,1);
w=size(img,2);
minl=min([w h]);
img=single(img);
if fastresize
im_data=(single(img)-127.5)*0.0078125;
end
m=12/minsize;
minl=minl*m;
%creat scale pyramid
scales=[];
while (minl>=12)
scales=[scales m*factor^(factor_count)];
minl=minl*factor;
factor_count=factor_count+1;
end
%first stage
for j = 1:size(scales,2)
scale=scales(j);
hs=ceil(h*scale);
ws=ceil(w*scale);
if fastresize
im_data=imResample(im_data,[hs ws],'bilinear');
else
im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125;
end
PNet.blobs('data').reshape([hs ws 3 1]);
out=PNet.forward({im_data});
boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1));
%inter-scale nms
pick=nms(boxes,0.5,'Union');
boxes=boxes(pick,:);
if ~isempty(boxes)
total_boxes=[total_boxes;boxes];
end
end
numbox=size(total_boxes,1);
if ~isempty(total_boxes)
pick=nms(total_boxes,0.7,'Union');
total_boxes=total_boxes(pick,:);
bbw=total_boxes(:,3)-total_boxes(:,1);
bbh=total_boxes(:,4)-total_boxes(:,2);
total_boxes=[total_boxes(:,1)+total_boxes(:,6).*bbw total_boxes(:,2)+total_boxes(:,7).*bbh total_boxes(:,3)+total_boxes(:,8).*bbw total_boxes(:,4)+total_boxes(:,9).*bbh total_boxes(:,5)];
total_boxes=rerec(total_boxes);
total_boxes(:,1:4)=fix(total_boxes(:,1:4));
[dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h);
end
numbox=size(total_boxes,1);
if numbox>0
%second stage
tempimg=zeros(24,24,3,numbox);
for k=1:numbox
tmp=zeros(tmph(k),tmpw(k),3);
tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:);
tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear');
end
tempimg=(tempimg-127.5)*0.0078125;
RNet.blobs('data').reshape([24 24 3 numbox]);
out=RNet.forward({tempimg});
score=squeeze(out{2}(2,:));
pass=find(score>threshold(2));
total_boxes=[total_boxes(pass,1:4) score(pass)'];
mv=out{1}(:,pass);
if size(total_boxes,1)>0
pick=nms(total_boxes,0.7,'Union');
total_boxes=total_boxes(pick,:);
total_boxes=bbreg(total_boxes,mv(:,pick)');
total_boxes=rerec(total_boxes);
end
numbox=size(total_boxes,1);
if numbox>0
%third stage
total_boxes=fix(total_boxes);
[dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h);
tempimg=zeros(48,48,3,numbox);
for k=1:numbox
tmp=zeros(tmph(k),tmpw(k),3);
tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:);
tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear');
end
tempimg=(tempimg-127.5)*0.0078125;
ONet.blobs('data').reshape([48 48 3 numbox]);
out=ONet.forward({tempimg});
score=squeeze(out{3}(2,:));
points=out{2};
pass=find(score>threshold(3));
points=points(:,pass);
total_boxes=[total_boxes(pass,1:4) score(pass)'];
mv=out{1}(:,pass);
bbw=total_boxes(:,3)-total_boxes(:,1)+1;
bbh=total_boxes(:,4)-total_boxes(:,2)+1;
points(1:5,:)=repmat(bbw',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1;
points(6:10,:)=repmat(bbh',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1;
if size(total_boxes,1)>0
total_boxes=bbreg(total_boxes,mv(:,:)');
pick=nms(total_boxes,0.7,'Min');
total_boxes=total_boxes(pick,:);
points=points(:,pick);
end
end
numbox=size(total_boxes,1);
%extended stage
if numbox>0
tempimg=zeros(24,24,15,numbox);
patchw=max([total_boxes(:,3)-total_boxes(:,1)+1 total_boxes(:,4)-total_boxes(:,2)+1]');
patchw=fix(0.25*patchw);
tmp=find(mod(patchw,2)==1);
patchw(tmp)=patchw(tmp)+1;
pointx=ones(numbox,5);
pointy=ones(numbox,5);
for k=1:5
tmp=[points(k,:);points(k+5,:)];
x=fix(tmp(1,:)-0.5*patchw);
y=fix(tmp(2,:)-0.5*patchw);
[dy edy dx edx y ey x ex tmpw tmph]=pad([x' y' x'+patchw' y'+patchw'],w,h);
for j=1:numbox
tmpim=zeros(tmpw(j),tmpw(j),3);
tmpim(dy(j):edy(j),dx(j):edx(j),:)=img(y(j):ey(j),x(j):ex(j),:);
tempimg(:,:,(k-1)*3+1:(k-1)*3+3,j)=imResample(tmpim,[24 24],'bilinear');
end
end
LNet.blobs('data').reshape([24 24 15 numbox]);
tempimg=(tempimg-127.5)*0.0078125;
out=LNet.forward({tempimg});
score=squeeze(out{3}(2,:));
for k=1:5
tmp=[points(k,:);points(k+5,:)];
%do not make a large movement
temp=find(abs(out{k}(1,:)-0.5)>0.35);
if ~isempty(temp)
l=length(temp);
out{k}(:,temp)=ones(2,l)*0.5;
end
temp=find(abs(out{k}(2,:)-0.5)>0.35);
if ~isempty(temp)
l=length(temp);
out{k}(:,temp)=ones(2,l)*0.5;
end
pointx(:,k)=(tmp(1,:)-0.5*patchw+out{k}(1,:).*patchw)';
pointy(:,k)=(tmp(2,:)-0.5*patchw+out{k}(2,:).*patchw)';
end
for j=1:numbox
points(:,j)=[pointx(j,:)';pointy(j,:)'];
end
end
end
end
function [boundingbox] = bbreg(boundingbox,reg)
%calibrate bouding boxes
if size(reg,2)==1
reg=reshape(reg,[size(reg,3) size(reg,4)])';
end
w=[boundingbox(:,3)-boundingbox(:,1)]+1;
h=[boundingbox(:,4)-boundingbox(:,2)]+1;
boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h];
end
function [boundingbox reg] = generateBoundingBox(map,reg,scale,t)
%use heatmap to generate bounding boxes
stride=2;
cellsize=12;
boundingbox=[];
map=map';
dx1=reg(:,:,1)';
dy1=reg(:,:,2)';
dx2=reg(:,:,3)';
dy2=reg(:,:,4)';
[y x]=find(map>=t);
a=find(map>=t);
if size(y,1)==1
y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2';
else
score=map(a);
end
reg=[dx1(a) dy1(a) dx2(a) dy2(a)];
if isempty(reg)
reg=reshape([],[0 3]);
end
boundingbox=[y x];
boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg];
end
function pick = nms(boxes,threshold,type)
%NMS
if isempty(boxes)
pick = [];
return;
end
x1 = boxes(:,1);
y1 = boxes(:,2);
x2 = boxes(:,3);
y2 = boxes(:,4);
s = boxes(:,5);
area = (x2-x1+1) .* (y2-y1+1);
[vals, I] = sort(s);
pick = s*0;
counter = 1;
while ~isempty(I)
last = length(I);
i = I(last);
pick(counter) = i;
counter = counter + 1;
xx1 = max(x1(i), x1(I(1:last-1)));
yy1 = max(y1(i), y1(I(1:last-1)));
xx2 = min(x2(i), x2(I(1:last-1)));
yy2 = min(y2(i), y2(I(1:last-1)));
w = max(0.0, xx2-xx1+1);
h = max(0.0, yy2-yy1+1);
inter = w.*h;
if strcmp(type,'Min')
o = inter ./ min(area(i),area(I(1:last-1)));
else
o = inter ./ (area(i) + area(I(1:last-1)) - inter);
end
I = I(find(o<=threshold));
end
pick = pick(1:(counter-1));
end
function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h)
%compute the padding coordinates (pad the bounding boxes to square)
tmpw=total_boxes(:,3)-total_boxes(:,1)+1;
tmph=total_boxes(:,4)-total_boxes(:,2)+1;
numbox=size(total_boxes,1);
dx=ones(numbox,1);dy=ones(numbox,1);
edx=tmpw;edy=tmph;
x=total_boxes(:,1);y=total_boxes(:,2);
ex=total_boxes(:,3);ey=total_boxes(:,4);
tmp=find(ex>w);
edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w;
tmp=find(ey>h);
edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h;
tmp=find(x<1);
dx(tmp)=2-x(tmp);x(tmp)=1;
tmp=find(y<1);
dy(tmp)=2-y(tmp);y(tmp)=1;
end
function [bboxA] = rerec(bboxA)
%convert bboxA to square
bboxB=bboxA(:,1:4);
h=bboxA(:,4)-bboxA(:,2);
w=bboxA(:,3)-bboxA(:,1);
l=max([w h]')';
bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5;
bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5;
bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]);
end
|
github | optimaltransport/optimaltransport.github.io-master | load_image.m | .m | optimaltransport.github.io-master/_site/code/toolbox/load_image.m | 19,798 | utf_8 | df61d87c209e587d6199fa36bbe979bf | function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'twodisks'
M = zeros(n);
options.center = [.25 .25];
M = load_image('disk', n, options);
options.center = [.75 .75];
M = M + load_image('disk', n, options);
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyre
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github | optimaltransport/optimaltransport.github.io-master | Hungarian.m | .m | optimaltransport.github.io-master/_site/code/toolbox/Hungarian.m | 9,328 | utf_8 | 51e60bc9f1f362bfdc0b4f6d67c44e80 | function [Matching,Cost] = Hungarian(Perf)
%
% [MATCHING,COST] = Hungarian_New(WEIGHTS)
%
% A function for finding a minimum edge weight matching given a MxN Edge
% weight matrix WEIGHTS using the Hungarian Algorithm.
%
% An edge weight of Inf indicates that the pair of vertices given by its
% position have no adjacent edge.
%
% MATCHING return a MxN matrix with ones in the place of the matchings and
% zeros elsewhere.
%
% COST returns the cost of the minimum matching
% Written by: Alex Melin 30 June 2006
% Initialize Variables
Matching = zeros(size(Perf));
% Condense the Performance Matrix by removing any unconnected vertices to
% increase the speed of the algorithm
% Find the number in each column that are connected
num_y = sum(~isinf(Perf),1);
% Find the number in each row that are connected
num_x = sum(~isinf(Perf),2);
% Find the columns(vertices) and rows(vertices) that are isolated
x_con = find(num_x~=0);
y_con = find(num_y~=0);
% Assemble Condensed Performance Matrix
P_size = max(length(x_con),length(y_con));
P_cond = zeros(P_size);
P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con);
if isempty(P_cond)
Cost = 0;
return
end
% Ensure that a perfect matching exists
% Calculate a form of the Edge Matrix
Edge = P_cond;
Edge(P_cond~=Inf) = 0;
% Find the deficiency(CNUM) in the Edge Matrix
cnum = min_line_cover(Edge);
% Project additional vertices and edges so that a perfect matching
% exists
Pmax = max(max(P_cond(P_cond~=Inf)));
P_size = length(P_cond)+cnum;
P_cond = ones(P_size)*Pmax;
P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con);
%*************************************************
% MAIN PROGRAM: CONTROLS WHICH STEP IS EXECUTED
%*************************************************
exit_flag = 1;
stepnum = 1;
while exit_flag
switch stepnum
case 1
[P_cond,stepnum] = step1(P_cond);
case 2
[r_cov,c_cov,M,stepnum] = step2(P_cond);
case 3
[c_cov,stepnum] = step3(M,P_size);
case 4
[M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M);
case 5
[M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov);
case 6
[P_cond,stepnum] = step6(P_cond,r_cov,c_cov);
case 7
exit_flag = 0;
end
end
% Remove all the virtual satellites and targets and uncondense the
% Matching to the size of the original performance matrix.
Matching(x_con,y_con) = M(1:length(x_con),1:length(y_con));
Cost = sum(sum(Perf(Matching==1)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Find the smallest number of zeros in each row
% and subtract that minimum from its row
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [P_cond,stepnum] = step1(P_cond)
P_size = length(P_cond);
% Loop throught each row
for ii = 1:P_size
rmin = min(P_cond(ii,:));
P_cond(ii,:) = P_cond(ii,:)-rmin;
end
stepnum = 2;
%**************************************************************************
% STEP 2: Find a zero in P_cond. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
function [r_cov,c_cov,M,stepnum] = step2(P_cond)
% Define variables
P_size = length(P_cond);
r_cov = zeros(P_size,1); % A vector that shows if a row is covered
c_cov = zeros(P_size,1); % A vector that shows if a column is covered
M = zeros(P_size); % A mask that shows if a position is starred or primed
for ii = 1:P_size
for jj = 1:P_size
if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0
M(ii,jj) = 1;
r_cov(ii) = 1;
c_cov(jj) = 1;
end
end
end
% Re-initialize the cover vectors
r_cov = zeros(P_size,1); % A vector that shows if a row is covered
c_cov = zeros(P_size,1); % A vector that shows if a column is covered
stepnum = 3;
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
function [c_cov,stepnum] = step3(M,P_size)
c_cov = sum(M,1);
if sum(c_cov) == P_size
stepnum = 7;
else
stepnum = 4;
end
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
function [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M)
P_size = length(P_cond);
zflag = 1;
while zflag
% Find the first uncovered zero
row = 0; col = 0; exit_flag = 1;
ii = 1; jj = 1;
while exit_flag
if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0
row = ii;
col = jj;
exit_flag = 0;
end
jj = jj + 1;
if jj > P_size; jj = 1; ii = ii+1; end
if ii > P_size; exit_flag = 0; end
end
% If there are no uncovered zeros go to step 6
if row == 0
stepnum = 6;
zflag = 0;
Z_r = 0;
Z_c = 0;
else
% Prime the uncovered zero
M(row,col) = 2;
% If there is a starred zero in that row
% Cover the row and uncover the column containing the zero
if sum(find(M(row,:)==1)) ~= 0
r_cov(row) = 1;
zcol = find(M(row,:)==1);
c_cov(zcol) = 0;
else
stepnum = 5;
zflag = 0;
Z_r = row;
Z_c = col;
end
end
end
%**************************************************************************
% STEP 5: Construct a series of alternating primed and starred zeros as
% follows. Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
function [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov)
zflag = 1;
ii = 1;
while zflag
% Find the index number of the starred zero in the column
rindex = find(M(:,Z_c(ii))==1);
if rindex > 0
% Save the starred zero
ii = ii+1;
% Save the row of the starred zero
Z_r(ii,1) = rindex;
% The column of the starred zero is the same as the column of the
% primed zero
Z_c(ii,1) = Z_c(ii-1);
else
zflag = 0;
end
% Continue if there is a starred zero in the column of the primed zero
if zflag == 1;
% Find the column of the primed zero in the last starred zeros row
cindex = find(M(Z_r(ii),:)==2);
ii = ii+1;
Z_r(ii,1) = Z_r(ii-1);
Z_c(ii,1) = cindex;
end
end
% UNSTAR all the starred zeros in the path and STAR all primed zeros
for ii = 1:length(Z_r)
if M(Z_r(ii),Z_c(ii)) == 1
M(Z_r(ii),Z_c(ii)) = 0;
else
M(Z_r(ii),Z_c(ii)) = 1;
end
end
% Clear the covers
r_cov = r_cov.*0;
c_cov = c_cov.*0;
% Remove all the primes
M(M==2) = 0;
stepnum = 3;
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
function [P_cond,stepnum] = step6(P_cond,r_cov,c_cov)
a = find(r_cov == 0);
b = find(c_cov == 0);
minval = min(min(P_cond(a,b)));
P_cond(find(r_cov == 1),:) = P_cond(find(r_cov == 1),:) + minval;
P_cond(:,find(c_cov == 0)) = P_cond(:,find(c_cov == 0)) - minval;
stepnum = 4;
function cnum = min_line_cover(Edge)
% Step 2
[r_cov,c_cov,M,stepnum] = step2(Edge);
% Step 3
[c_cov,stepnum] = step3(M,length(Edge));
% Step 4
[M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(Edge,r_cov,c_cov,M);
% Calculate the deficiency
cnum = length(Edge)-sum(r_cov)-sum(c_cov); |
github | optimaltransport/optimaltransport.github.io-master | imageplot.m | .m | optimaltransport.github.io-master/_site/code/toolbox/imageplot.m | 2,996 | utf_8 | bb6359ff3ad5e82264a744d41ba24582 | function h1 = imageplot(M,str, a,b,c)
% imageplot - diplay an image and a title
%
% Example of usages:
% imageplot(M);
% imageplot(M,title);
% imageplot(M,title,1,2,1); % to make subplot(1,2,1);
%
% imageplot(M,options);
%
% If you want to display several images:
% imageplot({M1 M2}, {'title1', 'title2'});
%
% Copyright (c) 2007 Gabriel Peyre
if nargin<2
str = [];
end
options.null = 0;
if isstruct(str)
options = str;
str = '';
end
nbdims = nb_dims(M);
if iscell(M)
q = length(M);
if nargin<5
c = 1;
end
if nargin<4
a = ceil(q/4);
end
if nargin<3
b = ceil(q/a);
end
if (c-1+q)>(a*b)
warning('a and c parameters not large enough');
a = ceil((c-1+q)/4);
b = ceil((c-1+q)/a);
end
for i=1:q
if iscell(str)
str1 = str{i};
else
str1 = str;
end
h{i} = imageplot(M{i},str1, a,b,c-1+i);
end
global axlist;
if not(isempty(axlist))
linkaxes(axlist, 'xy');
end
if nargout>0
if exist('h')
h1 = h;
else
h1 = [];
end
end
return;
end
if nargin==5
global axlist;
global imageplot_size;
if c==1 || isempty(imageplot_size) || imageplot_size~=size(M,1)
clear axlist;
global axlist;
axlist = [];
imageplot_size = size(M,1);
end
axlist(end+1) = subplot(a,b,c);
end
if nbdims==1
h = plot(M); axis tight;
elseif size(M,3)<=3
% gray-scale or color image
if size(M,3)==2
M = cat(3,M, zeros(size(M,1),size(M,2)));
end
if not(isreal(M))
if size(M,3)==1
% turn into color matrix
M = cat(3, real(M), imag(M), zeros(size(M,1),size(M,2)));
else
warning('Complex data');
M = real(M);
end
end
if size(M,3)==1
colormap gray(256);
else
colormap jet(256);
end
h = imagesc(rescale(M)); axis image; axis off;
else
if not(isfield(options, 'center') )
options.center = .5; % here a value in [0,1]
end
if not(isfield(options, 'sigma'))
options.sigma = .08; % control the width of the non-transparent region
end
a = compute_alpha_map('gaussian', options); % you can plot(a) to see the alphamap
% volumetric image
h = vol3d('cdata',rescale(M),'texture','2D');
view(3);
axis tight; % daspect([1 1 .4])
colormap bone(256);
% alphamap('rampup');
% alphamap(.06 .* alphamap);
vol3d(h);
end
if not(isempty(str))
title(str);
end
if nargout>0
if exist('h')
h1 = h;
else
h1 = [];
end
end
if nargin==5 && c==a*b
linkaxes(axlist, 'xy');
end
function d = nb_dims(x)
% nb_dims - debugged version of ndims.
%
% d = nb_dims(x);
%
% Copyright (c) 2004 Gabriel Peyre
if isempty(x)
d = 0;
return;
end
d = ndims(x);
if d==2 && (size(x,1)==1 || size(x,2)==1)
d = 1;
end
|
github | optimaltransport/optimaltransport.github.io-master | pdftops.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/pdftops.m | 6,161 | utf_8 | 5edac4bbbdae30223cb246a4ec7313d6 | function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops (e.g. '-help').
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
% Call pdftops
[varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]);
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
else
paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
end
for a = 1:numel(paths)
path_ = paths{a};
if check_store_xpdf_path(path_)
return
end
end
% Ask the user to enter the path
errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
errMsg1 = [errMsg1 url1];
%if strncmp(computer,'MAC',3) % Is a Mac
% % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
% uiwait(warndlg(errMsg1))
%end
% Provide an alternative possible explanation as per issue #137
errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
errMsg2 = [errMsg2 url1];
state = 0;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
switch answer
case 'Install pdftops'
web('-browser',url1);
case 'Issue #137'
web('-browser',url2);
state = 1;
case 'Locate pdftops'
base = uigetdir('/', errMsg1);
if isequal(base, 0)
% User hit cancel or closed window
break
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break
end
end
if check_store_xpdf_path(path_)
return
end
otherwise % User hit Cancel or closed window
break
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system([xpdf_command(path_) '-h']); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
% Display the error message if the pdftops executable exists but fails for some reason
if ~good && exist(path_,'file') % file exists but generates an error
fprintf('Error running %s:\n', path_);
fprintf(2,'%s\n\n',message);
end
end
function cmd = xpdf_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
% Avoids an error on Linux with outdated MATLAB lib files
% R20XXa/bin/glnxa64/libtiff.so.X
% R20XXa/sys/os/glnxa64/libstdc++.so.X
shell_cmd = 'export LD_LIBRARY_PATH=""; ';
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github | optimaltransport/optimaltransport.github.io-master | crop_borders.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/crop_borders.m | 5,133 | utf_8 | b744bf935914cfa6d9ff82140b48291e | function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
% Issue #175: there used to be a 1px minimal padding in case of crop, now removed
%{
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
bcol(:) = nan; % make the 1px padding transparent
end
%}
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github | optimaltransport/optimaltransport.github.io-master | isolate_axes.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/isolate_axes.m | 4,851 | utf_8 | 611d9727e84ad6ba76dcb3543434d0ce | function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | im2gif.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/im2gif.m | 6,234 | utf_8 | 8ee74d7d94e524410788276aa41dd5f1 | %IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | read_write_entire_textfile.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/read_write_entire_textfile.m | 961 | utf_8 | 775aa1f538c76516c7fb406a4f129320 | %READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github | optimaltransport/optimaltransport.github.io-master | pdf2eps.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/pdf2eps.m | 1,522 | utf_8 | 4c8f0603619234278ed413670d24bdb6 | %PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github | optimaltransport/optimaltransport.github.io-master | print2array.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/print2array.m | 10,376 | utf_8 | a2022c32ae3efa6007a326692227bd39 | function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
% 11/12/16: Fixed cropping issue reported by Harry D.
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% First try to print directly to tif file
try
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
if err, rethrow(ex); end
catch % error - try to print to EPS and then using Ghostscript to TIF
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
end
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to create a TIF image of the figure and read it into an array
function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
err = false;
ex = [];
% Temporarily set the paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset the paper size
set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | optimaltransport/optimaltransport.github.io-master | append_pdfs.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/append_pdfs.m | 2,759 | utf_8 | 9b52be41aff48bea6f27992396900640 | %APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github | optimaltransport/optimaltransport.github.io-master | using_hg2.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/using_hg2.m | 1,100 | utf_8 | 47ca10d86740c27b9f6b397373ae16cd | %USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = ~verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github | optimaltransport/optimaltransport.github.io-master | eps2pdf.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/eps2pdf.m | 8,793 | utf_8 | 474e976cf6454d5d7850baf14494fedf | function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, ' or maybe you have another gs executable in your system''s path\n');
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | optimaltransport/optimaltransport.github.io-master | ghostscript.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/ghostscript.m | 7,902 | utf_8 | ff62a40d651197dbea5d3c39998b3bad | function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github | optimaltransport/optimaltransport.github.io-master | fix_lines.m | .m | optimaltransport.github.io-master/_site/code/toolbox/export_fig/fix_lines.m | 6,441 | utf_8 | ffda929ebad8144b1e72d528fa5d9460 | %FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github | optimaltransport/optimaltransport.github.io-master | nbECGM.m | .m | optimaltransport.github.io-master/_site/code/toolbox/toolbox-lsap/nbECGM.m | 737 | utf_8 | 12c013e9e8fa1ded80b1fdb944a77e4f | % -----------------------------------------------------------
% file: nbECGM.m
% -----------------------------------------------------------
% authors: Sebastien Bougleux (UNICAEN) and Luc Brun (ENSICAEN)
% institution: Normandie Univ, CNRS - ENSICAEN - UNICAEN, GREYC UMR 6072
% -----------------------------------------------------------
% This file is part of LSAPE.
% LSAPE is free software: you can redistribute it and/or modify
% it under the terms of the CeCILL-C License. See README file
% for more details.
% -----------------------------------------------------------
function nb = nbECGM(nbU,nbV)
nb = 0;
for p=0:min(nbU,nbV)
nb = nb + factorial(p) * nchoosek(nbU,p) * nchoosek(nbV,p);
end
end
|
github | optimaltransport/optimaltransport.github.io-master | clip_polygons.m | .m | optimaltransport.github.io-master/_site/code/semi-discrete/power_bounded/clip_polygons.m | 5,541 | utf_8 | 592aa9651423258f116f55eb000f0f9d | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function is to clip 2 polygons with at least one of them is convex.
% The algorithm uses Sutherland-Hodgman algorithm.
% Conditions:
% * The clipping polygon must be convex and the subject polygon can be non-convex.
% * All coordinates must be ordered in CW direction
% * The last point is not the first point
% Input:
% * xc: array that specifies the x-coordinate of the clipping polygon (px1)
% * yc: array that specifies the y-coordinate of the clipping polygon (px1)
% * xs: array that specifies the x-coordinate of the subject polygon (px1)
% * ys: array that specifies the y-coordinate of the subject polygon (px1)
% Output:
% * xp: array that specifies the x-coordinate of the resulted polygon (px1)
% * yp: array that specifies the y-coordinate of the resulted polygon (px1)
% Extended:
% * can include jacobian vector, so xc, yc, xs, ys, and xp, yp will have dimension of (px3)
% * the rows are: x : [xA, dxA/dxi, dxA/dyi; xB, dxB/dxi, dxB/dyi; ...]
% * the rows are: y : [yA, dyA/dxi, dyA/dyi; yB, dyB/dxi, dyB/dyi, ...]
function [xp, yp] = clip_polygons(xc, yc, xs, ys)
if (size(xc,2) == 1)
ixpos = 1;
iypos = 2;
else
ixpos = 1;
iypos = 4;
end;
% make the coordinates (x,y) for each polygon
% if with jacobian, it becomes: [xA, dxA/dxi, dxA/dyi, yA, dyA/dxi, dyA/dyi; ...]
clippingPolygon = [xc, yc];
subjectPolygon = [xs, ys];
outputList = subjectPolygon;
for (i = [1:size(clippingPolygon,1)])
% break if there are no point left
if (length(outputList) == 0) break; end;
% get the edge of the clipping polygon
if (i == size(clippingPolygon,1)) ip1 = 1;
else ip1 = i+1; end;
clipEdge = [clippingPolygon(i,:); clippingPolygon(ip1,:) - clippingPolygon(i,:)];
% get the vector pointing inside
insideVector = [clipEdge(2,iypos), -clipEdge(2,ixpos)];
% copy the output list and clear it
inputList = outputList;
outputList = [];
S = inputList(end,:);
for (iE = [1:size(inputList,1)])
E = inputList(iE,:);
SEedge = [S; S-E];
% check if E is inside the clipEdge
if (isInside(E, clipEdge, insideVector, ixpos, iypos))
% if (dot(E([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector >= 0)
% check if S is not inside the clipEdge
if (~isInside(S, clipEdge, insideVector, ixpos, iypos))
% if (dot(S([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) < 0)
% add the intersection from S to E with the clipEdge
outputList(end+1,:) = getIntersection(SEedge, clipEdge, ixpos, iypos);
% A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
% b = [det(SEedge); det(clipEdge)];
% intersection = A \ b;
% outputList(end+1,:) = intersection';
end
outputList(end+1,:) = E;
% check if S is inside the clipEdge
elseif (isInside(S, clipEdge, insideVector, ixpos, iypos))
% elseif (dot(S([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) >= 0)
% add the intersection from S to E with the clipEdge
outputList(end+1,:) = getIntersection(SEedge, clipEdge, ixpos, iypos);
% A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
% b = [det(SEedge); det(clipEdge)];
% intersection = A \ b;
% outputList(end+1,:) = intersection';
end
S = E;
end
end
if (length(outputList) == 0)
xp = [];
yp = [];
else
xp = outputList(:,ixpos:iypos-1);
yp = outputList(:,iypos:end);
end
end
function ret = isInside(E, clipEdge, insideVector, ixpos, iypos)
ret = (dot(E([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) >= 0);
end
function intersection = getIntersection(SEedge, clipEdge, ixpos, iypos)
A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
b = [det2(SEedge(:,[ixpos,iypos])); det2(clipEdge(:,[ixpos,iypos]))];
xy = solve(A, b);
if (iypos == 4)
Ax = [SEedge(2,iypos+1), -SEedge(2,ixpos+1); clipEdge(2,iypos+1), -clipEdge(2,ixpos+1)];
bx = [det2(SEedge([1,7;4,10])) + det2(SEedge([3,9;2,8])); det2(clipEdge([1,7;4,10])) + det2(clipEdge([3,9;2,8]))];
dxydx = solve(A, (bx - Ax*xy));
Ay = [SEedge(2,iypos+2), -SEedge(2,ixpos+2); clipEdge(2,iypos+2), -clipEdge(2,ixpos+2)];
by = [det2(SEedge([1,7;6,12])) + det2(SEedge([5,11;2,8])); det2(clipEdge([1,7;6,12])) + det2(clipEdge([5,11;2,8]))];
dxydy = solve(A, (by - Ay*xy));
intersection = [xy(1) dxydx(1) dxydy(1) xy(2) dxydx(2) dxydy(2)];
else
intersection = xy';
end
end
function r = det2(A)
r = A(1)*A(4) - A(2)*A(3);
end
function r = solve(A,b)
r = [ A(4)*b(1)-A(3)*b(2) ; A(1)*b(2)-A(2)*b(1) ] / ( A(1)*A(4) - A(2)*A(3) );
end
|
github | optimaltransport/optimaltransport.github.io-master | power_bounded.m | .m | optimaltransport.github.io-master/_site/code/semi-discrete/power_bounded/power_bounded.m | 3,177 | utf_8 | 99a86a17bcfa7985a83c06b198ec3d17 | % POWER_BOUNDED computes the power cells about the points (x,y) inside
% the bounding box (must be a rectangle or a square) crs. If crs is not supplied, an
% axis-aligned box containing (x,y) is used.
% It is optimised to work fast on large number of sites (e.g. 10000 sites or more)
% Input:
% * x, y: coordinate of the Voronoi point (numPoints x 1)
% * wts: weights of each point (numPoints x 1)
% * crs: vortices of the bounding box in cw order (numVert x 2)
% Output:
% * V: x,y-coordinate of vertices of the power cells
% * C: indices of the Voronoi cells from V
% See Matlab's voronoin for more information about the output
% Made by: Aaron Becker, [email protected], and Muhammad Kasim, [email protected]
function [V,C] = power_bounded(x,y, wts, crs)
bnd=[min(x) max(x) min(y) max(y)]; %data bounds
if nargin < 3
crs=double([bnd(1) bnd(4);bnd(2) bnd(4);bnd(2) bnd(3);bnd(1) bnd(3);bnd(1) bnd(4)]);
end
rgx = max(crs(:,1))-min(crs(:,1));
rgy = max(crs(:,2))-min(crs(:,2));
rg = max(rgx,rgy);
midx = (max(crs(:,1))+min(crs(:,1)))/2;
midy = (max(crs(:,2))+min(crs(:,2)))/2;
% add 4 additional edges
xA = [x; midx + [0;0;-5*rg;+5*rg]];
yA = [y; midy + [-5*rg;+5*rg;0;0]];
if (all(wts == 0))
[vi,ci] = voronoin([xA,yA]);
else
[vi,ci] = powerDiagram2([xA,yA], [wts;zeros(4,1)]);
end
% remove the last 4 cells
C = ci(1:end-4);
V = vi;
% use Polybool to crop the cells
%Polybool for restriction of polygons to domain.
maxX = max(crs(:,1)); minX = min(crs(:,1));
maxY = max(crs(:,2)); minY = min(crs(:,2));
for ij=1:length(C)
% thanks to http://www.mathworks.com/matlabcentral/fileexchange/34428-voronoilimit
Cij = C{ij};
if (length(Cij) == 0) continue; end;
% first convert the contour coordinate to clockwise order:
pts = V(Cij,:);
K = convhull(pts);
K = K(end-1:-1:1);
C{ij} = Cij(K);
X2 = pts(K,1);
Y2 = pts(K,2);
% if all points are inside the bounding box, then skip it
if (all((X2 <= maxX) & (X2 >= minX) & (Y2 <= maxY) & (Y2 >= minY))) continue; end;
[xb, yb] = clip_polygons(crs(:,1),crs(:,2),X2,Y2);
% xb = xb'; yb = yb';
ix=nan(1,length(xb));
for il=1:length(xb)
if any(V(:,1)==xb(il)) && any(V(:,2)==yb(il))
ix1=find(V(:,1)==xb(il));
ix2=find(V(:,2)==yb(il));
for ib=1:length(ix1)
if any(ix1(ib)==ix2)
ix(il)=ix1(ib);
end
end
if isnan(ix(il))==1
lv=length(V);
V(lv+1,1)=xb(il);
V(lv+1,2)=yb(il);
ix(il)=lv+1;
end
else
lv=length(V);
V(lv+1,1)=xb(il);
V(lv+1,2)=yb(il);
ix(il)=lv+1;
end
end
C{ij} = ix;
end
end
|
github | optimaltransport/optimaltransport.github.io-master | powerDiagram2.m | .m | optimaltransport.github.io-master/_site/code/semi-discrete/power_bounded/powerDiagram2.m | 3,501 | utf_8 | 71c539ee242af8fdf9cc6868db097d8a | % This function obtains the power diagram specified by sites E with weights wts.
% It is optimised to work fast on large number of sites (e.g. 10000 sites or more).
% Only works for 2 dimensions.
% Input:
% * E: a matrix that specifies the sites coordinates (Npts x 2)
% * wts: a column vector that specifies the sites' weights (Npts x 1)
% Output:
% * V: list of points' coordinates that makes the power diagram vertices.
% * CE: cells that contains index of coordinate in V that makes the power diagram of a specified site.
% Thanks to: Arlind Nocaj and Ulrik Brandes (http://onlinelibrary.wiley.com/doi/10.1111/j.1467-8659.2012.03078.x/pdf)
% and Frederick McCollum (http://uk.mathworks.com/matlabcentral/fileexchange/44385-power-diagrams)
% Made by: Muhammad Kasim ([email protected])
function [V, CE] = powerDiagram2(E, wts)
%%%%%%%%%%%%%%%%%%%% lift the sites and extend to 3 dimensions %%%%%%%%%%%%%%%%%%%%
E = [E, sum(E.^2,2)-wts];
%%%%%%%%%%%%%%%%%%%% get the convex hull index %%%%%%%%%%%%%%%%%%%%
C = convhulln(E);
%%%%%%%%%%%%%%%%%%%% get the lower hull %%%%%%%%%%%%%%%%%%%%
% centre of the convex hull
centre = mean(E, 1);
% get the normals
vec1 = zeros([size(C,1), size(E,2)]);
vec2 = zeros([size(C,1), size(E,2)]);
for (i = [1:size(E,2)])
EiC = E(C+(i-1)*size(E,1));
vec1(:,i) = EiC(:,2) - EiC(:,1);
vec2(:,i) = EiC(:,3) - EiC(:,1);
end
normals = cross(vec1, vec2, 2);
vec1 = []; vec2 = []; % remove the memory
% get the middle point of each facet
midPoints = zeros([size(C,1), size(E,2)]);
for (i = [1:size(E,2)])
EiC = E(C+(i-1)*size(E,1));
midPoints(:,i) = mean(EiC,2);
end
EiC = []; % remove the memory
% check the projections of normals to midPoints-centre vector
dot = sum(bsxfun(@minus, centre, midPoints) .* normals, 2);
outward = (dot < 0);
% make sure all normals are pointing inwards
normals(outward,:) = -normals(outward,:);
% get the lower hull & upper hull
lowerIdx = (normals(:,end) > 0);
upperIdx = (normals(:,end) <= 0);
CUp = C(upperIdx,:);
C = C(lowerIdx,:);
normals = normals(lowerIdx,:);
midPoints = midPoints(lowerIdx,:);
%%%%%%%%%%%%%%%%%%%% invert the facet from dual space to the real space %%%%%%%%%%%%%%%%%%%%
normalsZ = bsxfun(@rdivide, normals, -normals(:,end)); % normalise the normals to have normals(z) = -1
a = normalsZ(:,1);
b = normalsZ(:,2);
% c = midPoints(:,3) - a.*midPoints(:,1) - b.*midPoints(:,2);
V = [a/2, b/2]; % this is the vertices for the power diagrams
V = [Inf, Inf; V];
%%%%%%%%%%%%%%%%%%%% assign each point to the vertices %%%%%%%%%%%%%%%%%%%%
% CE = arrayfun(@(x) mod(find(C == x)'-1, size(C,1)) + 1, [1:size(E,1)], 'UniformOutput', 0);
CE = cell(size(E,1),1);
for (col = [1:size(C,2)])
for (row = [1:size(C,1)])
i = C(row,col);
CE{i} = [CE{i}, row+1]; % + 1 because there is Inf at the first row
end
end
% select which one is on border
onBorders = zeros([size(E,1),1]);
for (col = [1:size(CUp,2)])
for (row = [1:size(CUp,1)])
i = CUp(row,col);
if (onBorders(i)) continue; end;
onBorders(i) = 1;
CE{i} = [CE{i}, 1];
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | load_image.m | .m | optimaltransport.github.io-master/code/toolbox/load_image.m | 19,798 | utf_8 | df61d87c209e587d6199fa36bbe979bf | function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'twodisks'
M = zeros(n);
options.center = [.25 .25];
M = load_image('disk', n, options);
options.center = [.75 .75];
M = M + load_image('disk', n, options);
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyre
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github | optimaltransport/optimaltransport.github.io-master | Hungarian.m | .m | optimaltransport.github.io-master/code/toolbox/Hungarian.m | 9,328 | utf_8 | 51e60bc9f1f362bfdc0b4f6d67c44e80 | function [Matching,Cost] = Hungarian(Perf)
%
% [MATCHING,COST] = Hungarian_New(WEIGHTS)
%
% A function for finding a minimum edge weight matching given a MxN Edge
% weight matrix WEIGHTS using the Hungarian Algorithm.
%
% An edge weight of Inf indicates that the pair of vertices given by its
% position have no adjacent edge.
%
% MATCHING return a MxN matrix with ones in the place of the matchings and
% zeros elsewhere.
%
% COST returns the cost of the minimum matching
% Written by: Alex Melin 30 June 2006
% Initialize Variables
Matching = zeros(size(Perf));
% Condense the Performance Matrix by removing any unconnected vertices to
% increase the speed of the algorithm
% Find the number in each column that are connected
num_y = sum(~isinf(Perf),1);
% Find the number in each row that are connected
num_x = sum(~isinf(Perf),2);
% Find the columns(vertices) and rows(vertices) that are isolated
x_con = find(num_x~=0);
y_con = find(num_y~=0);
% Assemble Condensed Performance Matrix
P_size = max(length(x_con),length(y_con));
P_cond = zeros(P_size);
P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con);
if isempty(P_cond)
Cost = 0;
return
end
% Ensure that a perfect matching exists
% Calculate a form of the Edge Matrix
Edge = P_cond;
Edge(P_cond~=Inf) = 0;
% Find the deficiency(CNUM) in the Edge Matrix
cnum = min_line_cover(Edge);
% Project additional vertices and edges so that a perfect matching
% exists
Pmax = max(max(P_cond(P_cond~=Inf)));
P_size = length(P_cond)+cnum;
P_cond = ones(P_size)*Pmax;
P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con);
%*************************************************
% MAIN PROGRAM: CONTROLS WHICH STEP IS EXECUTED
%*************************************************
exit_flag = 1;
stepnum = 1;
while exit_flag
switch stepnum
case 1
[P_cond,stepnum] = step1(P_cond);
case 2
[r_cov,c_cov,M,stepnum] = step2(P_cond);
case 3
[c_cov,stepnum] = step3(M,P_size);
case 4
[M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M);
case 5
[M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov);
case 6
[P_cond,stepnum] = step6(P_cond,r_cov,c_cov);
case 7
exit_flag = 0;
end
end
% Remove all the virtual satellites and targets and uncondense the
% Matching to the size of the original performance matrix.
Matching(x_con,y_con) = M(1:length(x_con),1:length(y_con));
Cost = sum(sum(Perf(Matching==1)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Find the smallest number of zeros in each row
% and subtract that minimum from its row
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [P_cond,stepnum] = step1(P_cond)
P_size = length(P_cond);
% Loop throught each row
for ii = 1:P_size
rmin = min(P_cond(ii,:));
P_cond(ii,:) = P_cond(ii,:)-rmin;
end
stepnum = 2;
%**************************************************************************
% STEP 2: Find a zero in P_cond. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
function [r_cov,c_cov,M,stepnum] = step2(P_cond)
% Define variables
P_size = length(P_cond);
r_cov = zeros(P_size,1); % A vector that shows if a row is covered
c_cov = zeros(P_size,1); % A vector that shows if a column is covered
M = zeros(P_size); % A mask that shows if a position is starred or primed
for ii = 1:P_size
for jj = 1:P_size
if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0
M(ii,jj) = 1;
r_cov(ii) = 1;
c_cov(jj) = 1;
end
end
end
% Re-initialize the cover vectors
r_cov = zeros(P_size,1); % A vector that shows if a row is covered
c_cov = zeros(P_size,1); % A vector that shows if a column is covered
stepnum = 3;
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
function [c_cov,stepnum] = step3(M,P_size)
c_cov = sum(M,1);
if sum(c_cov) == P_size
stepnum = 7;
else
stepnum = 4;
end
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
function [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M)
P_size = length(P_cond);
zflag = 1;
while zflag
% Find the first uncovered zero
row = 0; col = 0; exit_flag = 1;
ii = 1; jj = 1;
while exit_flag
if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0
row = ii;
col = jj;
exit_flag = 0;
end
jj = jj + 1;
if jj > P_size; jj = 1; ii = ii+1; end
if ii > P_size; exit_flag = 0; end
end
% If there are no uncovered zeros go to step 6
if row == 0
stepnum = 6;
zflag = 0;
Z_r = 0;
Z_c = 0;
else
% Prime the uncovered zero
M(row,col) = 2;
% If there is a starred zero in that row
% Cover the row and uncover the column containing the zero
if sum(find(M(row,:)==1)) ~= 0
r_cov(row) = 1;
zcol = find(M(row,:)==1);
c_cov(zcol) = 0;
else
stepnum = 5;
zflag = 0;
Z_r = row;
Z_c = col;
end
end
end
%**************************************************************************
% STEP 5: Construct a series of alternating primed and starred zeros as
% follows. Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
function [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov)
zflag = 1;
ii = 1;
while zflag
% Find the index number of the starred zero in the column
rindex = find(M(:,Z_c(ii))==1);
if rindex > 0
% Save the starred zero
ii = ii+1;
% Save the row of the starred zero
Z_r(ii,1) = rindex;
% The column of the starred zero is the same as the column of the
% primed zero
Z_c(ii,1) = Z_c(ii-1);
else
zflag = 0;
end
% Continue if there is a starred zero in the column of the primed zero
if zflag == 1;
% Find the column of the primed zero in the last starred zeros row
cindex = find(M(Z_r(ii),:)==2);
ii = ii+1;
Z_r(ii,1) = Z_r(ii-1);
Z_c(ii,1) = cindex;
end
end
% UNSTAR all the starred zeros in the path and STAR all primed zeros
for ii = 1:length(Z_r)
if M(Z_r(ii),Z_c(ii)) == 1
M(Z_r(ii),Z_c(ii)) = 0;
else
M(Z_r(ii),Z_c(ii)) = 1;
end
end
% Clear the covers
r_cov = r_cov.*0;
c_cov = c_cov.*0;
% Remove all the primes
M(M==2) = 0;
stepnum = 3;
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
function [P_cond,stepnum] = step6(P_cond,r_cov,c_cov)
a = find(r_cov == 0);
b = find(c_cov == 0);
minval = min(min(P_cond(a,b)));
P_cond(find(r_cov == 1),:) = P_cond(find(r_cov == 1),:) + minval;
P_cond(:,find(c_cov == 0)) = P_cond(:,find(c_cov == 0)) - minval;
stepnum = 4;
function cnum = min_line_cover(Edge)
% Step 2
[r_cov,c_cov,M,stepnum] = step2(Edge);
% Step 3
[c_cov,stepnum] = step3(M,length(Edge));
% Step 4
[M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(Edge,r_cov,c_cov,M);
% Calculate the deficiency
cnum = length(Edge)-sum(r_cov)-sum(c_cov); |
github | optimaltransport/optimaltransport.github.io-master | imageplot.m | .m | optimaltransport.github.io-master/code/toolbox/imageplot.m | 2,996 | utf_8 | bb6359ff3ad5e82264a744d41ba24582 | function h1 = imageplot(M,str, a,b,c)
% imageplot - diplay an image and a title
%
% Example of usages:
% imageplot(M);
% imageplot(M,title);
% imageplot(M,title,1,2,1); % to make subplot(1,2,1);
%
% imageplot(M,options);
%
% If you want to display several images:
% imageplot({M1 M2}, {'title1', 'title2'});
%
% Copyright (c) 2007 Gabriel Peyre
if nargin<2
str = [];
end
options.null = 0;
if isstruct(str)
options = str;
str = '';
end
nbdims = nb_dims(M);
if iscell(M)
q = length(M);
if nargin<5
c = 1;
end
if nargin<4
a = ceil(q/4);
end
if nargin<3
b = ceil(q/a);
end
if (c-1+q)>(a*b)
warning('a and c parameters not large enough');
a = ceil((c-1+q)/4);
b = ceil((c-1+q)/a);
end
for i=1:q
if iscell(str)
str1 = str{i};
else
str1 = str;
end
h{i} = imageplot(M{i},str1, a,b,c-1+i);
end
global axlist;
if not(isempty(axlist))
linkaxes(axlist, 'xy');
end
if nargout>0
if exist('h')
h1 = h;
else
h1 = [];
end
end
return;
end
if nargin==5
global axlist;
global imageplot_size;
if c==1 || isempty(imageplot_size) || imageplot_size~=size(M,1)
clear axlist;
global axlist;
axlist = [];
imageplot_size = size(M,1);
end
axlist(end+1) = subplot(a,b,c);
end
if nbdims==1
h = plot(M); axis tight;
elseif size(M,3)<=3
% gray-scale or color image
if size(M,3)==2
M = cat(3,M, zeros(size(M,1),size(M,2)));
end
if not(isreal(M))
if size(M,3)==1
% turn into color matrix
M = cat(3, real(M), imag(M), zeros(size(M,1),size(M,2)));
else
warning('Complex data');
M = real(M);
end
end
if size(M,3)==1
colormap gray(256);
else
colormap jet(256);
end
h = imagesc(rescale(M)); axis image; axis off;
else
if not(isfield(options, 'center') )
options.center = .5; % here a value in [0,1]
end
if not(isfield(options, 'sigma'))
options.sigma = .08; % control the width of the non-transparent region
end
a = compute_alpha_map('gaussian', options); % you can plot(a) to see the alphamap
% volumetric image
h = vol3d('cdata',rescale(M),'texture','2D');
view(3);
axis tight; % daspect([1 1 .4])
colormap bone(256);
% alphamap('rampup');
% alphamap(.06 .* alphamap);
vol3d(h);
end
if not(isempty(str))
title(str);
end
if nargout>0
if exist('h')
h1 = h;
else
h1 = [];
end
end
if nargin==5 && c==a*b
linkaxes(axlist, 'xy');
end
function d = nb_dims(x)
% nb_dims - debugged version of ndims.
%
% d = nb_dims(x);
%
% Copyright (c) 2004 Gabriel Peyre
if isempty(x)
d = 0;
return;
end
d = ndims(x);
if d==2 && (size(x,1)==1 || size(x,2)==1)
d = 1;
end
|
github | optimaltransport/optimaltransport.github.io-master | pdftops.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/pdftops.m | 6,161 | utf_8 | 5edac4bbbdae30223cb246a4ec7313d6 | function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops (e.g. '-help').
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
% Call pdftops
[varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]);
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
else
paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
end
for a = 1:numel(paths)
path_ = paths{a};
if check_store_xpdf_path(path_)
return
end
end
% Ask the user to enter the path
errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
errMsg1 = [errMsg1 url1];
%if strncmp(computer,'MAC',3) % Is a Mac
% % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
% uiwait(warndlg(errMsg1))
%end
% Provide an alternative possible explanation as per issue #137
errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
errMsg2 = [errMsg2 url1];
state = 0;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
switch answer
case 'Install pdftops'
web('-browser',url1);
case 'Issue #137'
web('-browser',url2);
state = 1;
case 'Locate pdftops'
base = uigetdir('/', errMsg1);
if isequal(base, 0)
% User hit cancel or closed window
break
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break
end
end
if check_store_xpdf_path(path_)
return
end
otherwise % User hit Cancel or closed window
break
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system([xpdf_command(path_) '-h']); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
% Display the error message if the pdftops executable exists but fails for some reason
if ~good && exist(path_,'file') % file exists but generates an error
fprintf('Error running %s:\n', path_);
fprintf(2,'%s\n\n',message);
end
end
function cmd = xpdf_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
% Avoids an error on Linux with outdated MATLAB lib files
% R20XXa/bin/glnxa64/libtiff.so.X
% R20XXa/sys/os/glnxa64/libstdc++.so.X
shell_cmd = 'export LD_LIBRARY_PATH=""; ';
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github | optimaltransport/optimaltransport.github.io-master | crop_borders.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/crop_borders.m | 5,133 | utf_8 | b744bf935914cfa6d9ff82140b48291e | function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
% Issue #175: there used to be a 1px minimal padding in case of crop, now removed
%{
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
bcol(:) = nan; % make the 1px padding transparent
end
%}
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github | optimaltransport/optimaltransport.github.io-master | isolate_axes.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/isolate_axes.m | 4,851 | utf_8 | 611d9727e84ad6ba76dcb3543434d0ce | function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | im2gif.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/im2gif.m | 6,234 | utf_8 | 8ee74d7d94e524410788276aa41dd5f1 | %IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | read_write_entire_textfile.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/read_write_entire_textfile.m | 961 | utf_8 | 775aa1f538c76516c7fb406a4f129320 | %READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github | optimaltransport/optimaltransport.github.io-master | pdf2eps.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/pdf2eps.m | 1,522 | utf_8 | 4c8f0603619234278ed413670d24bdb6 | %PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github | optimaltransport/optimaltransport.github.io-master | print2array.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/print2array.m | 10,376 | utf_8 | a2022c32ae3efa6007a326692227bd39 | function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
% 11/12/16: Fixed cropping issue reported by Harry D.
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% First try to print directly to tif file
try
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
if err, rethrow(ex); end
catch % error - try to print to EPS and then using Ghostscript to TIF
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
end
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to create a TIF image of the figure and read it into an array
function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
err = false;
ex = [];
% Temporarily set the paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset the paper size
set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | optimaltransport/optimaltransport.github.io-master | append_pdfs.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/append_pdfs.m | 2,759 | utf_8 | 9b52be41aff48bea6f27992396900640 | %APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github | optimaltransport/optimaltransport.github.io-master | using_hg2.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/using_hg2.m | 1,100 | utf_8 | 47ca10d86740c27b9f6b397373ae16cd | %USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = ~verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github | optimaltransport/optimaltransport.github.io-master | eps2pdf.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/eps2pdf.m | 8,793 | utf_8 | 474e976cf6454d5d7850baf14494fedf | function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, ' or maybe you have another gs executable in your system''s path\n');
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | optimaltransport/optimaltransport.github.io-master | ghostscript.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/ghostscript.m | 7,902 | utf_8 | ff62a40d651197dbea5d3c39998b3bad | function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github | optimaltransport/optimaltransport.github.io-master | fix_lines.m | .m | optimaltransport.github.io-master/code/toolbox/export_fig/fix_lines.m | 6,441 | utf_8 | ffda929ebad8144b1e72d528fa5d9460 | %FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github | optimaltransport/optimaltransport.github.io-master | nbECGM.m | .m | optimaltransport.github.io-master/code/toolbox/toolbox-lsap/nbECGM.m | 737 | utf_8 | 12c013e9e8fa1ded80b1fdb944a77e4f | % -----------------------------------------------------------
% file: nbECGM.m
% -----------------------------------------------------------
% authors: Sebastien Bougleux (UNICAEN) and Luc Brun (ENSICAEN)
% institution: Normandie Univ, CNRS - ENSICAEN - UNICAEN, GREYC UMR 6072
% -----------------------------------------------------------
% This file is part of LSAPE.
% LSAPE is free software: you can redistribute it and/or modify
% it under the terms of the CeCILL-C License. See README file
% for more details.
% -----------------------------------------------------------
function nb = nbECGM(nbU,nbV)
nb = 0;
for p=0:min(nbU,nbV)
nb = nb + factorial(p) * nchoosek(nbU,p) * nchoosek(nbV,p);
end
end
|
github | optimaltransport/optimaltransport.github.io-master | distinguishable_colors.m | .m | optimaltransport.github.io-master/code/semi-discrete-sgd/distinguishable_colors.m | 5,753 | utf_8 | 57960cf5d13cead2f1e291d1288bccb2 | function colors = distinguishable_colors(n_colors,bg,func)
% DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct
%
% When plotting a set of lines, you may want to distinguish them by color.
% By default, Matlab chooses a small set of colors and cycles among them,
% and so if you have more than a few lines there will be confusion about
% which line is which. To fix this problem, one would want to be able to
% pick a much larger set of distinct colors, where the number of colors
% equals or exceeds the number of lines you want to plot. Because our
% ability to distinguish among colors has limits, one should choose these
% colors to be "maximally perceptually distinguishable."
%
% This function generates a set of colors which are distinguishable
% by reference to the "Lab" color space, which more closely matches
% human color perception than RGB. Given an initial large list of possible
% colors, it iteratively chooses the entry in the list that is farthest (in
% Lab space) from all previously-chosen entries. While this "greedy"
% algorithm does not yield a global maximum, it is simple and efficient.
% Moreover, the sequence of colors is consistent no matter how many you
% request, which facilitates the users' ability to learn the color order
% and avoids major changes in the appearance of plots when adding or
% removing lines.
%
% Syntax:
% colors = distinguishable_colors(n_colors)
% Specify the number of colors you want as a scalar, n_colors. This will
% generate an n_colors-by-3 matrix, each row representing an RGB
% color triple. If you don't precisely know how many you will need in
% advance, there is no harm (other than execution time) in specifying
% slightly more than you think you will need.
%
% colors = distinguishable_colors(n_colors,bg)
% This syntax allows you to specify the background color, to make sure that
% your colors are also distinguishable from the background. Default value
% is white. bg may be specified as an RGB triple or as one of the standard
% "ColorSpec" strings. You can even specify multiple colors:
% bg = {'w','k'}
% or
% bg = [1 1 1; 0 0 0]
% will only produce colors that are distinguishable from both white and
% black.
%
% colors = distinguishable_colors(n_colors,bg,rgb2labfunc)
% By default, distinguishable_colors uses the image processing toolbox's
% color conversion functions makecform and applycform. Alternatively, you
% can supply your own color conversion function.
%
% Example:
% c = distinguishable_colors(25);
% figure
% image(reshape(c,[1 size(c)]))
%
% Example using the file exchange's 'colorspace':
% func = @(x) colorspace('RGB->Lab',x);
% c = distinguishable_colors(25,'w',func);
% Copyright 2010-2011 by Timothy E. Holy
% Parse the inputs
if (nargin < 2)
bg = [1 1 1]; % default white background
else
if iscell(bg)
% User specified a list of colors as a cell aray
bgc = bg;
for i = 1:length(bgc)
bgc{i} = parsecolor(bgc{i});
end
bg = cat(1,bgc{:});
else
% User specified a numeric array of colors (n-by-3)
bg = parsecolor(bg);
end
end
% Generate a sizable number of RGB triples. This represents our space of
% possible choices. By starting in RGB space, we ensure that all of the
% colors can be generated by the monitor.
n_grid = 30; % number of grid divisions along each axis in RGB space
x = linspace(0,1,n_grid);
[R,G,B] = ndgrid(x,x,x);
rgb = [R(:) G(:) B(:)];
if (n_colors > size(rgb,1)/3)
error('You can''t readily distinguish that many colors');
end
% Convert to Lab color space, which more closely represents human
% perception
if (nargin > 2)
lab = func(rgb);
bglab = func(bg);
else
C = makecform('srgb2lab');
lab = applycform(rgb,C);
bglab = applycform(bg,C);
end
% If the user specified multiple background colors, compute distances
% from the candidate colors to the background colors
mindist2 = inf(size(rgb,1),1);
for i = 1:size(bglab,1)-1
dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg
dist2 = sum(dX.^2,2); % square distance
mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color
end
% Iteratively pick the color that maximizes the distance to the nearest
% already-picked color
colors = zeros(n_colors,3);
lastlab = bglab(end,:); % initialize by making the "previous" color equal to background
for i = 1:n_colors
dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list
dist2 = sum(dX.^2,2); % square distance
mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color
[~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors
colors(i,:) = rgb(index,:); % save for output
lastlab = lab(index,:); % prepare for next iteration
end
end
function c = parsecolor(s)
if ischar(s)
c = colorstr2rgb(s);
elseif isnumeric(s) && size(s,2) == 3
c = s;
else
error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.');
end
end
function c = colorstr2rgb(c)
% Convert a color string to an RGB value.
% This is cribbed from Matlab's whitebg function.
% Why don't they make this a stand-alone function?
rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0];
cspec = 'rgbwcmyk';
k = find(cspec==c(1));
if isempty(k)
error('MATLAB:InvalidColorString','Unknown color string.');
end
if k~=3 || length(c)==1,
c = rgbspec(k,:);
elseif length(c)>2,
if strcmpi(c(1:3),'bla')
c = [0 0 0];
elseif strcmpi(c(1:3),'blu')
c = [0 0 1];
else
error('MATLAB:UnknownColorString', 'Unknown color string.');
end
end
end
|
github | optimaltransport/optimaltransport.github.io-master | clip_polygons.m | .m | optimaltransport.github.io-master/code/semi-discrete/power_bounded/clip_polygons.m | 5,541 | utf_8 | 592aa9651423258f116f55eb000f0f9d | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function is to clip 2 polygons with at least one of them is convex.
% The algorithm uses Sutherland-Hodgman algorithm.
% Conditions:
% * The clipping polygon must be convex and the subject polygon can be non-convex.
% * All coordinates must be ordered in CW direction
% * The last point is not the first point
% Input:
% * xc: array that specifies the x-coordinate of the clipping polygon (px1)
% * yc: array that specifies the y-coordinate of the clipping polygon (px1)
% * xs: array that specifies the x-coordinate of the subject polygon (px1)
% * ys: array that specifies the y-coordinate of the subject polygon (px1)
% Output:
% * xp: array that specifies the x-coordinate of the resulted polygon (px1)
% * yp: array that specifies the y-coordinate of the resulted polygon (px1)
% Extended:
% * can include jacobian vector, so xc, yc, xs, ys, and xp, yp will have dimension of (px3)
% * the rows are: x : [xA, dxA/dxi, dxA/dyi; xB, dxB/dxi, dxB/dyi; ...]
% * the rows are: y : [yA, dyA/dxi, dyA/dyi; yB, dyB/dxi, dyB/dyi, ...]
function [xp, yp] = clip_polygons(xc, yc, xs, ys)
if (size(xc,2) == 1)
ixpos = 1;
iypos = 2;
else
ixpos = 1;
iypos = 4;
end;
% make the coordinates (x,y) for each polygon
% if with jacobian, it becomes: [xA, dxA/dxi, dxA/dyi, yA, dyA/dxi, dyA/dyi; ...]
clippingPolygon = [xc, yc];
subjectPolygon = [xs, ys];
outputList = subjectPolygon;
for (i = [1:size(clippingPolygon,1)])
% break if there are no point left
if (length(outputList) == 0) break; end;
% get the edge of the clipping polygon
if (i == size(clippingPolygon,1)) ip1 = 1;
else ip1 = i+1; end;
clipEdge = [clippingPolygon(i,:); clippingPolygon(ip1,:) - clippingPolygon(i,:)];
% get the vector pointing inside
insideVector = [clipEdge(2,iypos), -clipEdge(2,ixpos)];
% copy the output list and clear it
inputList = outputList;
outputList = [];
S = inputList(end,:);
for (iE = [1:size(inputList,1)])
E = inputList(iE,:);
SEedge = [S; S-E];
% check if E is inside the clipEdge
if (isInside(E, clipEdge, insideVector, ixpos, iypos))
% if (dot(E([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector >= 0)
% check if S is not inside the clipEdge
if (~isInside(S, clipEdge, insideVector, ixpos, iypos))
% if (dot(S([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) < 0)
% add the intersection from S to E with the clipEdge
outputList(end+1,:) = getIntersection(SEedge, clipEdge, ixpos, iypos);
% A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
% b = [det(SEedge); det(clipEdge)];
% intersection = A \ b;
% outputList(end+1,:) = intersection';
end
outputList(end+1,:) = E;
% check if S is inside the clipEdge
elseif (isInside(S, clipEdge, insideVector, ixpos, iypos))
% elseif (dot(S([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) >= 0)
% add the intersection from S to E with the clipEdge
outputList(end+1,:) = getIntersection(SEedge, clipEdge, ixpos, iypos);
% A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
% b = [det(SEedge); det(clipEdge)];
% intersection = A \ b;
% outputList(end+1,:) = intersection';
end
S = E;
end
end
if (length(outputList) == 0)
xp = [];
yp = [];
else
xp = outputList(:,ixpos:iypos-1);
yp = outputList(:,iypos:end);
end
end
function ret = isInside(E, clipEdge, insideVector, ixpos, iypos)
ret = (dot(E([ixpos,iypos]) - clipEdge(1,[ixpos,iypos]), insideVector) >= 0);
end
function intersection = getIntersection(SEedge, clipEdge, ixpos, iypos)
A = [SEedge(2,iypos), -SEedge(2,ixpos); clipEdge(2,iypos), -clipEdge(2,ixpos)];
b = [det2(SEedge(:,[ixpos,iypos])); det2(clipEdge(:,[ixpos,iypos]))];
xy = solve(A, b);
if (iypos == 4)
Ax = [SEedge(2,iypos+1), -SEedge(2,ixpos+1); clipEdge(2,iypos+1), -clipEdge(2,ixpos+1)];
bx = [det2(SEedge([1,7;4,10])) + det2(SEedge([3,9;2,8])); det2(clipEdge([1,7;4,10])) + det2(clipEdge([3,9;2,8]))];
dxydx = solve(A, (bx - Ax*xy));
Ay = [SEedge(2,iypos+2), -SEedge(2,ixpos+2); clipEdge(2,iypos+2), -clipEdge(2,ixpos+2)];
by = [det2(SEedge([1,7;6,12])) + det2(SEedge([5,11;2,8])); det2(clipEdge([1,7;6,12])) + det2(clipEdge([5,11;2,8]))];
dxydy = solve(A, (by - Ay*xy));
intersection = [xy(1) dxydx(1) dxydy(1) xy(2) dxydx(2) dxydy(2)];
else
intersection = xy';
end
end
function r = det2(A)
r = A(1)*A(4) - A(2)*A(3);
end
function r = solve(A,b)
r = [ A(4)*b(1)-A(3)*b(2) ; A(1)*b(2)-A(2)*b(1) ] / ( A(1)*A(4) - A(2)*A(3) );
end
|
github | optimaltransport/optimaltransport.github.io-master | power_bounded.m | .m | optimaltransport.github.io-master/code/semi-discrete/power_bounded/power_bounded.m | 3,177 | utf_8 | 99a86a17bcfa7985a83c06b198ec3d17 | % POWER_BOUNDED computes the power cells about the points (x,y) inside
% the bounding box (must be a rectangle or a square) crs. If crs is not supplied, an
% axis-aligned box containing (x,y) is used.
% It is optimised to work fast on large number of sites (e.g. 10000 sites or more)
% Input:
% * x, y: coordinate of the Voronoi point (numPoints x 1)
% * wts: weights of each point (numPoints x 1)
% * crs: vortices of the bounding box in cw order (numVert x 2)
% Output:
% * V: x,y-coordinate of vertices of the power cells
% * C: indices of the Voronoi cells from V
% See Matlab's voronoin for more information about the output
% Made by: Aaron Becker, [email protected], and Muhammad Kasim, [email protected]
function [V,C] = power_bounded(x,y, wts, crs)
bnd=[min(x) max(x) min(y) max(y)]; %data bounds
if nargin < 3
crs=double([bnd(1) bnd(4);bnd(2) bnd(4);bnd(2) bnd(3);bnd(1) bnd(3);bnd(1) bnd(4)]);
end
rgx = max(crs(:,1))-min(crs(:,1));
rgy = max(crs(:,2))-min(crs(:,2));
rg = max(rgx,rgy);
midx = (max(crs(:,1))+min(crs(:,1)))/2;
midy = (max(crs(:,2))+min(crs(:,2)))/2;
% add 4 additional edges
xA = [x; midx + [0;0;-5*rg;+5*rg]];
yA = [y; midy + [-5*rg;+5*rg;0;0]];
if (all(wts == 0))
[vi,ci] = voronoin([xA,yA]);
else
[vi,ci] = powerDiagram2([xA,yA], [wts;zeros(4,1)]);
end
% remove the last 4 cells
C = ci(1:end-4);
V = vi;
% use Polybool to crop the cells
%Polybool for restriction of polygons to domain.
maxX = max(crs(:,1)); minX = min(crs(:,1));
maxY = max(crs(:,2)); minY = min(crs(:,2));
for ij=1:length(C)
% thanks to http://www.mathworks.com/matlabcentral/fileexchange/34428-voronoilimit
Cij = C{ij};
if (length(Cij) == 0) continue; end;
% first convert the contour coordinate to clockwise order:
pts = V(Cij,:);
K = convhull(pts);
K = K(end-1:-1:1);
C{ij} = Cij(K);
X2 = pts(K,1);
Y2 = pts(K,2);
% if all points are inside the bounding box, then skip it
if (all((X2 <= maxX) & (X2 >= minX) & (Y2 <= maxY) & (Y2 >= minY))) continue; end;
[xb, yb] = clip_polygons(crs(:,1),crs(:,2),X2,Y2);
% xb = xb'; yb = yb';
ix=nan(1,length(xb));
for il=1:length(xb)
if any(V(:,1)==xb(il)) && any(V(:,2)==yb(il))
ix1=find(V(:,1)==xb(il));
ix2=find(V(:,2)==yb(il));
for ib=1:length(ix1)
if any(ix1(ib)==ix2)
ix(il)=ix1(ib);
end
end
if isnan(ix(il))==1
lv=length(V);
V(lv+1,1)=xb(il);
V(lv+1,2)=yb(il);
ix(il)=lv+1;
end
else
lv=length(V);
V(lv+1,1)=xb(il);
V(lv+1,2)=yb(il);
ix(il)=lv+1;
end
end
C{ij} = ix;
end
end
|
github | optimaltransport/optimaltransport.github.io-master | powerDiagram2.m | .m | optimaltransport.github.io-master/code/semi-discrete/power_bounded/powerDiagram2.m | 3,501 | utf_8 | 71c539ee242af8fdf9cc6868db097d8a | % This function obtains the power diagram specified by sites E with weights wts.
% It is optimised to work fast on large number of sites (e.g. 10000 sites or more).
% Only works for 2 dimensions.
% Input:
% * E: a matrix that specifies the sites coordinates (Npts x 2)
% * wts: a column vector that specifies the sites' weights (Npts x 1)
% Output:
% * V: list of points' coordinates that makes the power diagram vertices.
% * CE: cells that contains index of coordinate in V that makes the power diagram of a specified site.
% Thanks to: Arlind Nocaj and Ulrik Brandes (http://onlinelibrary.wiley.com/doi/10.1111/j.1467-8659.2012.03078.x/pdf)
% and Frederick McCollum (http://uk.mathworks.com/matlabcentral/fileexchange/44385-power-diagrams)
% Made by: Muhammad Kasim ([email protected])
function [V, CE] = powerDiagram2(E, wts)
%%%%%%%%%%%%%%%%%%%% lift the sites and extend to 3 dimensions %%%%%%%%%%%%%%%%%%%%
E = [E, sum(E.^2,2)-wts];
%%%%%%%%%%%%%%%%%%%% get the convex hull index %%%%%%%%%%%%%%%%%%%%
C = convhulln(E);
%%%%%%%%%%%%%%%%%%%% get the lower hull %%%%%%%%%%%%%%%%%%%%
% centre of the convex hull
centre = mean(E, 1);
% get the normals
vec1 = zeros([size(C,1), size(E,2)]);
vec2 = zeros([size(C,1), size(E,2)]);
for (i = [1:size(E,2)])
EiC = E(C+(i-1)*size(E,1));
vec1(:,i) = EiC(:,2) - EiC(:,1);
vec2(:,i) = EiC(:,3) - EiC(:,1);
end
normals = cross(vec1, vec2, 2);
vec1 = []; vec2 = []; % remove the memory
% get the middle point of each facet
midPoints = zeros([size(C,1), size(E,2)]);
for (i = [1:size(E,2)])
EiC = E(C+(i-1)*size(E,1));
midPoints(:,i) = mean(EiC,2);
end
EiC = []; % remove the memory
% check the projections of normals to midPoints-centre vector
dot = sum(bsxfun(@minus, centre, midPoints) .* normals, 2);
outward = (dot < 0);
% make sure all normals are pointing inwards
normals(outward,:) = -normals(outward,:);
% get the lower hull & upper hull
lowerIdx = (normals(:,end) > 0);
upperIdx = (normals(:,end) <= 0);
CUp = C(upperIdx,:);
C = C(lowerIdx,:);
normals = normals(lowerIdx,:);
midPoints = midPoints(lowerIdx,:);
%%%%%%%%%%%%%%%%%%%% invert the facet from dual space to the real space %%%%%%%%%%%%%%%%%%%%
normalsZ = bsxfun(@rdivide, normals, -normals(:,end)); % normalise the normals to have normals(z) = -1
a = normalsZ(:,1);
b = normalsZ(:,2);
% c = midPoints(:,3) - a.*midPoints(:,1) - b.*midPoints(:,2);
V = [a/2, b/2]; % this is the vertices for the power diagrams
V = [Inf, Inf; V];
%%%%%%%%%%%%%%%%%%%% assign each point to the vertices %%%%%%%%%%%%%%%%%%%%
% CE = arrayfun(@(x) mod(find(C == x)'-1, size(C,1)) + 1, [1:size(E,1)], 'UniformOutput', 0);
CE = cell(size(E,1),1);
for (col = [1:size(C,2)])
for (row = [1:size(C,1)])
i = C(row,col);
CE{i} = [CE{i}, row+1]; % + 1 because there is Inf at the first row
end
end
% select which one is on border
onBorders = zeros([size(E,1),1]);
for (col = [1:size(CUp,2)])
for (row = [1:size(CUp,1)])
i = CUp(row,col);
if (onBorders(i)) continue; end;
onBorders(i) = 1;
CE{i} = [CE{i}, 1];
end
end
end
|
github | leopoldofr/swarmdrones-master | main.m | .m | swarmdrones-master/main.m | 12,129 | utf_8 | 0e6858631559d3f7cf39ffdfc5f131fc | % ### Program to simulate drone swarm moving together according to Javier
% Alonso-Mora et al's algorithm
% (https://web.stanford.edu/~schwager/MyPapers/Alonso-MoraEtAlICRA16FormationNavigation.pdf)
% ### Warning:
% - On an unix computer (my distrib is Linux Mint) you must launch Matlab with the -softwareopengl option or
% you will have stange warnings while rendering the drone with plot()
% The plugins installed are geom3d and intersectionHull. I modified the
% convexHull one
tic
startSimulation();
toc
function []= startSimulation()
%Main function
nbDrones = 8; % The number of drones for the simulation
simulationFrames = 20; % Time of simulation, in frames
rangeDrones = 2000; % Viewport size rangeDrones x rangeDrones
goalPoint = point( 3500, 1000, 0); % The objective point to reach
comRange = 1000; % Wireless communication range for a drone
clc();
delete(findall(0,'Type','figure'))
allDrones=init(nbDrones, goalPoint,rangeDrones, comRange);
drawWholeSimulation(simulationFrames, allDrones, rangeDrones, comRange, goalPoint)
end
function allDrones=init(nbDrones, goalPoint, rangeDrones, comRange)
%Initialize the drone swarm with nbDrones drones and random coordinates
allDrones=cell(1,nbDrones);
offset = 0.3;
for i=1:nbDrones
p = point(rand()*rangeDrones * offset + (offset*rangeDrones), rand()*rangeDrones * offset + (offset * rangeDrones), 1);%rand()*rangeDrones * offset + (offset*rangeDrones));
allDrones{i}=drone(i,4,1.0,1000, p, goalPoint,comRange);
end
end
function [] = drawWholeSimulation(simulationFrames, allDrones, rangeDrones, comRange, goal)
%Run and draw the whole simulation
%Options parameters for the simulation
renderComRange = true; %Render the circle for the range communication of all drones
randomizeComDrones = true; %Add Randomization to the communication range of each drone
randomizeComDronesPurcent = [comRange, 0.1]; %[avg, purcent] plus purcent est élevé, plus il y a de perturbations
%Delete the previous figures
delete(findall(0,'Type','figure'));
fig1 = figure;
set(fig1, 'Position', get(0,'Screensize'))
%Initialisation
obstacles = generateObstacles(5);
for i=1:simulationFrames
%Randomize the communication range at each frame
if randomizeComDrones == true
randomComDrones(allDrones, randomizeComDronesPurcent);
end
%Algorithm 1 => Convex Hull
calculateConvexHull(allDrones);
%Algorithm 2 => Intersection of the vision of each drone
calculateIntersection(allDrones);
%Last step, calculate the optimal formation
% TODO
drawSingleFrame(allDrones, rangeDrones,renderComRange, goal, obstacles);
pause(0.15); % On my current computer a short pause is necessary to render the convexHull result. It doesn't render if there is no pause
clf()
moveDrones(allDrones);
reinitPolytopesDrones(allDrones);
end
end
function h = drawSingleFrame(allDrones, rangeDrones, renderComRange, goal, obstacles)
%Draw a single frame to display drones
%It displays the convex hull of the drones, the intersection hull
%It can display the communication range
nbdrones = size(allDrones,2);
h = [];
colors = ['m' 'c' 'b' 'r' 'k' 'g' 'r'];
for i=1:nbdrones
pos = allDrones{i}.getPosition();
p = pos.getCoords();
b = mod(i,size(colors));
b = b(2);
if b == 0
b = 1;
end
color = strcat(colors(b),'o');
h = plot(p(1), p(2), color);
hold on;
end
%Prepare the plot (title, labels, xlim,...)
xlabel("coord X");
ylabel("coord Y");
zlabel("coord Z");
xlim([0 rangeDrones*2]);
ylim([0 rangeDrones]);
zlim([0 rangeDrones/2]);
pbaspect([2 1 0.5]); % Ratio of the axis for a better display
title("Swarm drone moving (in progress)");
grid on;
zoom on;
%Render each drone as a point
for i =1:size(allDrones,2)
cv = allDrones{i}.getConvexHull2D();
X = cv.getX();
Y = cv.getY();
K = cv.getK();
plot(X(K),Y(K),'r-',X,Y,'b*')
%Render (if option renderComRange is set to true) the communication
%circle around each drone
if renderComRange == true
x = allDrones{i}.getPosition().getX();
y = allDrones{i}.getPosition().getY();
r = allDrones{i}.getComRange();
ang=0:0.01:2*pi;
xp=r*cos(ang);
yp=r*sin(ang);
plot(x+xp,y+yp, 'k--');
end
%Render the current polytope of each drone
V = allDrones{i}.getPolytope();
scatter3(V(:,1),V(:,2),V(:,3),'b');
alpha(.2);
end
%Rendering the goal point
plot(goal.getX(),goal.getY(), '*r');
text(goal.getX() + 20,goal.getY(), 'Objectif');
%Uncomment the following line to view the viewport in 3D
%view(3)
displayObstacles(obstacles)
end
function [] = moveDrones(allDrones)
%Move randomly the drones for now
%It chooses a random X and Y and move the drones
nbDrones = size(allDrones,2);
for i=1:nbDrones
drone = allDrones{i};
coords = drone.getPosition().getCoords();
coords2 = coords +[(rand()-0.5)*50 (rand()-0.5)*50 1];
p2 = point(coords2(1), coords2(2), coords2(3));
drone.setPosition(p2);
end
end
function calculateConvexHull(allDrones)
%Calculate the convex hull for all drones
%allDrones is a drone array
nbDrones = size(allDrones,2);
for i = 1:nbDrones
cd = allDrones{i}.getPosition().getCoords();
init_cv_hull = convexHull2D(1,cd(1),cd(2));
init_tmp_cv_hull = convexHull2D();
allDrones{i}.setConvexHull2D(init_cv_hull);
allDrones{i}.setTmpConvexHull2D(init_tmp_cv_hull);
end
for i = 1:nbDrones
sendConvexHull(allDrones, i);
receiveConvexHull(allDrones, i);
end
end
function sendConvexHull(allDrones,i)
%A drone send it's difference between the k-1 an k nth convexhulls
%differences
tmpConvexHull = allDrones{i}.getTmpConvexHull2D();
convexHull = allDrones{i}.getConvexHull2D();
%Calculate the difference
tmp = diff(convexHull,tmpConvexHull);
tmp = convexHull2D(1,tmp(:,1),tmp(:,2));
K = getDronesInRange(allDrones,i);
for j=K
allDrones{j}.setTmpConvexHull2D(tmp);
end
end
function receiveConvexHull(allDrones, i)
%Each drone is going to calculate its update
K = getDronesInRange(allDrones,i);
for j = K
tcv = allDrones{j}.getTmpConvexHull2D();
cv = allDrones{j}.getConvexHull2D();
diffcv = diff(cv, tcv);
%le drone i calcule sa mise à jour et update sa convex hull
tmp = mergeHull(allDrones{i}.getConvexHull2D(), diffcv);
allDrones{i}.setConvexHull2D(tmp);
end
end
function ret = diff(cv,tcv)
% Function that calculates the difference between two convexHull2D
% object an returns an array of its X Y, both columns vectors
% It returns the new values
XY1 = cat(2,cv.getX(),cv.getY());
XY2 = cat(2,tcv.getX(),tcv.getY());
if(size(XY2,1) == 0)
ret = cat(2,cv.getX(), cv.getY());
else
ret = setdiff(XY1,XY2,'rows');
end
end
function ret = mergeHull(current,old)
%Takes an update and merge it
%An update is just a two entry array of columns X,Y (parameter old)
X = cat(1,current.getX(), old(:,1));
Y = cat(1,current.getY(), old(:,2));
%Here we remove all dupplicates
XY = unique(cat(2,X,Y), 'rows');
X = XY(:,1);
Y = XY(:,2);
if size(X,1) <= 2
ret = convexHull2D(size(X,1), X, Y);
elseif size(X,1) > 2
K = convhull(X,Y);
ret = convexHull2D(K,X,Y);
end
end
function K = getDronesInRange(allDrones, d)
%get indices of drones in the range of the drone number d in 3D
%return an array of indices
%The function does not include the drone d in the array
K = zeros(1,8);
c1 = allDrones{d}.getPosition();
for i=1:size(allDrones,2)
if not(i == d)
c2 = allDrones{i}.getPosition();
x = power(c2.getX() - c1.getX(),2);
y = power(c2.getY() - c1.getY(),2);
z = power(c2.getZ() - c1.getZ(),2);
dist = sqrt(x+y+z);
if dist < (allDrones{d}.getComRange() + allDrones{i}.getComRange())
K(i) = i;
end
end
end
K = K(K~=0);
end
function randomComDrones(allDrones, rcdp)
%Randomize the drones communications according to the parameter rcdp
for i=1:size(allDrones,2)
r = rcdp(1) + (rcdp(1) * rcdp(2)) - rand()*(rcdp(1) * rcdp(2) * 2);
allDrones{i}.setComRange(r);
end
end
function []= calculateIntersection(allDrones)
%Calculate the intersection of the polytope for each drone
for j=1:8
for i=1:size(allDrones,2)
sendPolytopeDrones(allDrones, i);
receivePolytopeDrones(allDrones, i);
end
end
end
function []=sendPolytopeDrones(allDrones, i)
%Function that will calculate the
if size(allDrones{i}.getPolytope(),1) == 0
[vertices, ~, ~] = createSoccerBall; % '~' means that this return value won't be useful
T = createTranslation3d(allDrones{i}.getPosition.getX(),allDrones{i}.getPosition().getY(),1);
S = createScaling3d(allDrones{i}.getComRange());
tr = composeTransforms3d(S,T);
vertices = transformPoint3d(vertices,tr);
allDrones{i}.setPolytope(vertices);
end
vertices = allDrones{i}.getPolytope();
K = getDronesInRange(allDrones, i);
for k=K
allDrones{k}.setPolyInter(vertices);
end
end
function []=receivePolytopeDrones(allDrones, i)
%A drone will compute it's own polytope with the temporary one and then
%it will store the new one as it's new polytope
for k=getDronesInRange(allDrones,i)
if(size(allDrones{k}.getPolytope(),1) == 0)
[V, ~, ~] = createSoccerBall;
T = createTranslation3d(allDrones{k}.getPosition.getX(),allDrones{k}.getPosition().getY(),1);
S = createScaling3d(allDrones{k}.getComRange());
tr = composeTransforms3d(S,T);
V = transformPoint3d(V,tr);
allDrones{k}.setPolytope(V);
end
V = intersectionHull('vert', allDrones{k}.getPolytope(), 'vert', allDrones{k}.getPolyInter());
V = V.vert;
allDrones{k}.setPolytope(V);
V = intersectionHull('vert', allDrones{i}.getPolytope(), 'vert', V);
V = unique(V.vert,'rows');
allDrones{i}.setPolytope(V);
end
end
function reinitPolytopesDrones(allDrones)
%Function that reinitialize the drones polytopes for the next frame
for i=1:size(allDrones,2)
allDrones{i}.setPolytope([]);
allDrones{i}.setPolyInter([]);
end
end
function ret =generateObstacles(nb)
%In construction...
%Configuration
range = 300;
%We randomly choose one of these for a single obstacle
tab = ["cube","octa","soccer"];
if nb <= 0
ret = [];
else
ret = cell(nb);
for i=1:nb
x = round(1+rand(1)*(size(tab,2)-1));
type = tab{x};
ret{i} = obstacle(type, range);
end
end
end
function displayObstacles(obstacles)
%Display all obstacles on the plot
for i=1:size(obstacles,2)
plotpoly(obstacles{i}.getPolytope());
end
end
|
github | leopoldofr/swarmdrones-master | plotpoly.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/plotpoly.m | 3,247 | utf_8 | bbba5c5246510a7ee12e7e9c69f1d147 | %PLOTPOLY plot 2-D projection of N-D polytope
% PLOTPOLY(M) projects a matrix of vertices into a 2-D shadow of edges
% PLOTPOLY(M, 'infinity') projects from infinity (default)
% PLOTPOLY(M, 'nearby') projects from a closer point in space
% PLOTPOLY(M, 'tumble') tumbles randomly and projects from infinity
% M(i,:) is the coordinates of the i-th vertex.
% Color and line width are used to show depth.
%
function plotpoly(p, flag)
if nargin == 1
flag = 'infinity'; % default
end
[s,f] = edges(p); % start,finish
mz = max(abs(p(3,:))); % z scale
if size(p,2) >= 4; mw = max(abs(p(4,:))); end
clip = @(vec) min(max(vec,0),1); % black and white
hold on
%axis equal
%axis off
switch flag
case 'infinity'
fromInfinity; % display
case 'nearby'
fromNearby; % display
case 'tumble'
tumble; % display
axis manual
end
%hold off
return;
% tumble until stopped with ^C
function tumble
mx = max(abs(p(:)))*1.5;
axis([-mx mx -mx mx]); % fix the axes
nd = size(p,2);
a = rand(nd)/25; % about 1 degree
for reps = 1:inf
dr = ndrotate(a);
for i=1:10
cla; % clear previous
fromInfinity; % new edges
drawnow;
p = p*dr; % new position
pause(0.03); % leave some cycles
end
a = a + (rand-0.5)/100; % change direction
end
end
% a function to plot 2-D shadow of edges
function fromInfinity % nested
for k=numel(s):-1:1 % all edges
e1 = [p(s(k),1) p(f(k),1)]; % x ends
e2 = [p(s(k),2) p(f(k),2)]; % y ends
e3 = [p(s(k),3) p(f(k),3)];
if size(p,2) == 3 % 3-D figures
z = p(s(k),3) + p(f(k),3); % 2*mx : -2*mx
h = ((z+2*mz)/mz)/4; % 1 : 0
h = 1-h; % 0 : 1
c = clip([h h h]); % black is nearest
w = 2-h;
else % 4-D figures
z = p(s(k),3) + p(f(k),3); % 2*mx to -2*mx dim=3
w = p(s(k),4) + p(f(k),4); % 2*mx to -2*mx dim=4
h1 = ((z+2*mz)/mz)/4; % 1 : 0
h2 = 1-h1; % 0 : 1
h3 = ((w+2*mw)/mw)/4; % 1 : 0
c = clip(1.2*[h1*.9 .4*h3 h2]);
w = 1;
end
plot3(e1, e2, e3, 'color', c, 'linewidth', w);
end
end
% a function to plot 2-D shadow of edges
function fromNearby % nested
hold on % plot it
axis equal
nearby = mx+.1;
toscreen = 40;
for k=1:numel(s) % all edges
y = [p(s(k),1) p(f(k),1)]; % x ends
z = [p(s(k),2) p(f(k),2)]; % y ends
x = [p(s(k),3) p(f(k),3)]; % z ends
sx = x.*toscreen./(nearby-z);
sy = y.*toscreen./(nearby-z);
plot(sx, sy);
end
hold off
end
end
|
github | leopoldofr/swarmdrones-master | buckytumble.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/buckytumble.m | 2,568 | utf_8 | f58c2ec254562217c75a4f0ee5b19720 | %BUCKYTUMBLE shows tumbling Bucky Ball
% BUCKYTUMBLE -- display the Bucky Ball, slowly tumbling in space
%
% Bill McKeeman
function buckytumble
gr = (1+sqrt(5))/2; % golden ration
d = @(a,b) a + b*gr; % vertex function
bb = perms(... % Bucky Ball vertices
[d(0,0), d(0,3), d(1,0) % truncated icosahedron
d(1,0), d(0,2), d(2,1)
d(2,0), d(0,1), d(1,2)]/2, 'cycles', 'signs', 'unique');
[s,f] = edges(bb); % start,finish
mx = max(abs(bb(:)))*1.2; % frame the picture
mz = max(abs(bb(3,:))); % z scale
clip = @(vec) min(max(vec,0),1); % black and white
axis([-mx mx -mx mx]); % fix the axes
axis equal
axis off
bg = .8*[1 1 1]; % background grey
set(gcf, 'color', bg);
hold on
tumble; % plot it
hold off
return;
function [s,f] = edges(p)
m = size(p,1);
d = inf(m); % distance matrix
for i=1:m
for j=i+1:m
seg = p(i,:)-p(j,:); % vertex pairs
d(i,j) = sqrt(seg*seg'); % distance between
end
end
es = min(d(:)); % nearest neighbors
TOL = es/10000;
[s,f] = find(abs(d-es)<TOL); % compensate for roundoff
end
% tumble until stopped with ^C
function tumble
nd = size(bb,2);
a = rand(nd)/25; % about 1 degree
p = bb; % rotatable vertex set
for reps = 1:inf
dr = ndrotate(a);
for i=1:100 % 100, then change direction
cla; % clear previous
fromInfinity(p); % new edges
drawnow;
p = p*dr; % new position
pause(0.03); % leave some cycles
end
a = a + (rand-0.5)/100; % change direction
end
end
% a function to plot 2-D shadow of edges
function fromInfinity(p)
for k = 1:numel(s) % all edges
e1 = [p(s(k),1) p(f(k),1)]; % x end
e2 = [p(s(k),2) p(f(k),2)]; % y end
z = p(s(k),3) + p(f(k),3); % 2*mx : -2*mx
h = ((z+2*mz)/mz)/4; % 1 : 0
h = 1-h; % 0 : 1
c = clip([h h h]); % black is nearest
w = 2-h;
plot(e1, e2, 'color', c, 'linewidth', w);
end
end
end
|
github | leopoldofr/swarmdrones-master | ndrotate.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/ndrotate.m | 833 | utf_8 | 01659156846c852569c78ba42571de04 | %NDROTATE rotate cartesian coordinates in N-D space
% NDROTATE(M) builds a rotation matrix from a matrix of angles.
% M(i,j) is the i-to-j rotation angle (radians)
% M(i,i) is ignored.
% Examples:
% ndrotate([0, pi/6]) is
% 0.8660 -0.5000
% 0.5000 0.8660
% ndrotate([0, pi/6; pi/4, 0]) is
% 0.9659 0.2588
% -0.2588 0.9659
% Use:
% cube = allsigns([1 1 1]/2);
% rotatedcube = cube*ndrotate([0, 1, 2; .5 0 .3]);
%
function res = ndrotate(angles)
[m,n] = size(angles);
res = eye(n);
for i=1:m
for j=1:n
if i ~= j && angles(i,j) ~= 0
tmp = eye(n);
tmp(i,i) = cos(angles(i,j));
tmp(j,j) = tmp(i,i);
tmp(i,j) = -sin(angles(i,j));
tmp(j,i) = -tmp(i,j);
res = res*tmp;
end
end
end
|
github | leopoldofr/swarmdrones-master | faces.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/faces.m | 972 | utf_8 | 15c7cfd5c14ee3f15645e675c7ff3bb2 | %FACES find the faces defined by angles
% FACES(A) finds the plane equations
% Angles are triple of vertices.
% The three points are used to compute the linear plane equation
% Roundoff is removed by picking a representative value for each.
% Multiple solutions are singled up by unique('rows')
%
function f = faces(a,v)
TOL = 1.e-7;
m = size(a,1);
n = size(v,2);
planes = [];
for i=1:m % all angles
planes(i,:) = v(a(i,:),:)\ones(n,1);
end
[ps, pi] = sort(planes(:)); % collect like items
pd = diff(ps) < TOL; % find transitions
tmp = ps(1); % head of "equal" list
for i=1:numel(pd) % use std rep for each value
if pd(i)
planes(pi(i+1)) = tmp; % use unique value
else
tmp = ps(i+1); % new head of "equal"
end
end
size(planes)
f = unique(planes,'rows');
|
github | leopoldofr/swarmdrones-master | angles.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/angles.m | 262 | utf_8 | 64650015f8c3a1b4451b9ba640b22f07 | %ANGLES find the angles of an edge set
% ANGLES(E) finds vertex triples
%
function a = angles(e)
m = size(e,1);
a = [];
for i=1:m
for j=i+1:m
t = unique([e(i,:), e(j,:)]);
if numel(t)==3; a(end+1,:) = t; end
end
end
|
github | leopoldofr/swarmdrones-master | nedge.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/nedge.m | 183 | utf_8 | 846d9345b6f607687f267b25f000dc59 | %NEDGE counts the edges of a polytope
% NEDGE(M) finds the closest vertices, then reports all pairs at
% this distance.
function ect = nedge(p)
ect = size(edges(p),1);
|
github | leopoldofr/swarmdrones-master | tumble.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/tumble.m | 2,350 | utf_8 | f9cf85ac5ce1add1dbd1740c414b5563 | %BUCKYTUMBLE shows tumbling Bucky Ball
% BUCKYTUMBLE -- display the Bucky Ball, slowly tumbling in space
%
% Bill McKeeman
function buckytumble
gr = (1+sqrt(5))/2; % golden ration
d = @(a,b) a + b*gr; % vertex function
bg = .8*[1 1 1]; % background grey
set(gcf, 'color', bg);
bb = perms(... % Bucky Ball vertices
[d(0,0), d(0,3), d(1,0)
d(1,0), d(0,2), d(2,1)
d(2,0), d(0,1), d(1,2)]/2, 'cycles', 'signs', 'unique');
mx = max(abs(bb(:)))*1.2; % frame the picture
axis([-mx mx -mx mx]); % fix the axes
tumble(bb); % plot it
return;
% tumble until stopped with ^C
function tumble(p)
mx = max(abs(p(:)))*1.5;
axis([-mx mx -mx mx]); % fix the axes
nd = size(p,2);
a = rand(nd)/25; % about 1 degree
for reps = 1:inf
dr = ndrotate(a);
for i=1:100 % 100, then change direction
cla; % clear previous
fromInfinity; % new edges
drawnow;
p = p*dr; % new position
pause(0.03); % leave some cycles
end
a = a + (rand-0.5)/100; % change direction
end
end
% plot 2-D shadow of edges
function fromInfinity % nested
for k=numel(s):-1:1 % all edges
e1 = [p(s(k),1) p(f(k),1)]; % x ends
e2 = [p(s(k),2) p(f(k),2)]; % y end
z = p(s(k),3) + p(f(k),3); % 2*mx : -2*mx
h = ((z+2*mz)/mz)/4; % 1 : 0
h = 1-h; % 0 : 1
c = clip([h h h]); % black is nearest
w = 2-h;
plot(e1, e2, 'color', c, 'linewidth', w);
end
end
% turn angles into orthogonal matrix
function res = ndrotate(angles)
[m,n] = size(angles);
res = eye(n);
for i=1:m
for j=1:n
if i ~= j && angles(i,j) ~= 0
tmp = eye(n);
tmp(i,i) = cos(angles(i,j));
tmp(j,j) = tmp(i,i);
tmp(i,j) = -sin(angles(i,j));
tmp(j,i) = -tmp(i,j);
res = res*tmp;
end
end
end
end
end
|
github | leopoldofr/swarmdrones-master | edges.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/edges.m | 541 | utf_8 | 109266fddb2008ce2d5f0d99156d9cf3 | %EDGES find the edges of a vertex set
% EDGES(M) finds the closest vertices, then reports all pairs at
% this distance.
function [s,f] = edges(p)
m = size(p,1);
d = inf(m); % distance matrix
for i=1:m
for j=i+1:m
seg = p(i,:)-p(j,:); % vertex pairs
d(i,j) = sqrt(seg*seg'); % distance between
end
end
es = min(d(:)); % nearest neighbors
TOL = es/10000;
[s,f] = find(abs(d-es)<TOL); % compensate for roundoff
|
github | leopoldofr/swarmdrones-master | nface.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/nface.m | 171 | utf_8 | fbb71132c1dc1621fb92052ab2a86da2 | %NFACE counts the faces of a polyhedron
% NFACE(M) uses Euler's formula V-E+F=2
%
function fct = nface(p)
vct = size(p,1);
ect = nedge(p);
fct = ect-vct+2; |
github | leopoldofr/swarmdrones-master | perms.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/perms.m | 8,816 | utf_8 | a845fad56b4630d9a22cfc6a9f46ab79 | %PERMS all different permutations of matrix rows
% PERMS(M) extends mXn matrix M to one containing all permutations of
% values for each row.
% PERMS(M) gives all permutations (default).
%
% Flags:
% PERMS(M, 'even') gives even permutations.
% PERMS(M, 'odd') gives odd permutations.
% PERMS(M, 'all') gives all permutations (default).
% PERMS(M, 'cycles') gives all end-around shifts.
% PERMS(M, 'signs') gives all changes of sign.
% PERMS(M, 'unique') sorts the result and removes repeated rows.
% Flags 'signs' and/or 'unique' can be used with other flags.
% Flags 'all', 'even', 'odd' and 'cycles' are mutually exclusive.
% class(M) is the same as class(perms(M, flags)).
% The result of perms is acceptable input to another call of perms.
% perms 'unique' is idempotent. I.e.,
% t = perms(M, flag, 'unique') is the same as
% t = perms(t, flag, 'unique')
% Flag 'unique' is computationally expensive. Avoid it if you can.
% PERMS is memory limited. When the application permits it, use a
% smaller input data type (such as int8).
%
% Examples:
% perms(1:2) is [1 2; 2 1]
% perms(1:3, 'even') is [3 1 2; 1 2 3; 2 3 1]
% perms((1:3)/2, 'odd') is [1.5 1.0 0.5; 0.5 1.5 1.0; 1.0 0.5 1.5]
% perms(1:2, 'signs') is [-1 -2; -1 2; 1 -2; 1 2]
% perms([1 0 0],'unique') is [0 0 1; 0 1 0; 1 0 0]
% perms([1 1; 2 1]) is [1 1; 1 2; 2 1]
% perms('abc', 'cycles') is ['abc'; 'cab'; 'bca']
%
% Class support for input M:
% numeric, sparse, char, logical, complex
% Note: the 'signs' flag can be applied to all numeric classes
% except unsigned ints and (temporarily) 64-bit ints.
%
% See also RANDPERM NCHOOSEK
function M = perms(M, varargin) % outer function
% get input bounds
if numel(M) == 0, return; end
if ndims(M) ~= 2,
error('MATLAB:perms:input', 'requires mXn input');
end
% process flags
fPerm=1; fOdd=2; fEven=3; fCycle=4; fSign=5; fUnique=6;
opt = false(1,6);
for arg = 1:nargin-1
switch lower(varargin{arg})
case 'all', opt(fPerm) = true;
case 'odd', opt(fOdd) = true;
case 'even', opt(fEven) = true;
case 'cycles', opt(fCycle) = true;
case 'signs', opt(fSign) = true;
case 'unique', opt(fUnique) = true;
otherwise, error('MATLAB:perms:badflag', 'unknown flag');
end
end
if ~any(opt(fPerm:fSign)); opt(fPerm) = true; end % default
% avoid meaningless combinations of flags
if sum(opt(fPerm:fCycle)) > 1
error('MATLAB:perms:badflag', 'conflicting flags');
end
% compute basic permutations, result in M
[nr, nc] = size(M); % input vectors
if opt(fPerm), allPerms(fPerm);
elseif opt(fOdd), allPerms(fOdd);
elseif opt(fEven), allPerms(fEven);
elseif opt(fCycle), allCycles;
end
% compute all sign variations
[nr, nc] = size(M); % might have changed
if opt(fSign), allSigns; end
% discard repeated entries, get canonical order
if opt(fUnique), M = unique(M, 'rows'); end
return % that's all folks
%--------- end of execution in main function --------------------
function allPerms(flag) % nesting level 1
% temporarily make types numeric
if islogical(M), w = uint8(M);
elseif ischar(M), w = uint16(M);
else w = M;
end
% permute 1:nc
if flag == fPerm,
makePerms; q = pa{nc};
else
makeEvenOdd;
if flag == fOdd, q = odd{nc}; else q = even{nc}; end
end
md = size(q,1);
% do the work
res = zeros(md*nr, nc, class(w)); % place for result
for i=1:nr
z = w(i,:); % one vector at a time
res((i-1)*md+1:i*md, :) = z(q); % permuted i-th input
end
% cleanup and deliver result
if islogical(M), M = logical(res);
elseif ischar(M), M = char(res);
elseif issparse(M), M = sparse(res);
else M = res; % result in M
end
return; % from allPerms
% ----------- end of execution in allPerms --------------------
% Build up standard permutation matrices: These matrices are always the
% same (permutations of 1:n) for any data. The permutation matrices are
% class uint8 to save storage.
function makePerms % nesting level 2
pa = {1}; % all perms, res in pa{}
for i = 2:nc % the rest
c = pa{i-1};
[bh, bw] = size(c); % block height & width
o = ones(bh, 1, 'uint8');
nh = bh*i; % new height
nw = bw+1; % new width
b = zeros(nh, nw, 'uint8'); % new block
b(1:bh, :) = [i*o, c]; % just a copy
for j=1:i-1
d = c;
d(c==j) = i; % substitute i for j
b(j*bh+1:(j+1)*bh, :) = [j*o, d];
end
pa{end+1} = b;
end
return; % from makePerms
end
% ------------------- end makePerms ----------------------
% Build up even and odd permutation matrices: These matrices are always
% the same for any input data. The class is uint8 to save storage.
function makeEvenOdd % nesting level 2
even{1} = uint8(1); % res in even{}, odd{}
odd{1} = uint8(1);
even{2} = uint8([1 2]);
odd{2} = uint8([2 1]);
for i=3:nc
od = odd{i-1};
ev = even{i-1};
[bh, bw] = size(od);
o = ones(bh, 1, 'uint8');
z = zeros(bh*i, bw+1, 'uint8');% new block
td = z;
te = z;
td(1:bh,:) = [i*o, od]; % just extend odd
te(1:bh,:) = [i*o, ev]; % just extend even
for j=1:i-1
t = ev; % for new odd
t(ev==j) = i; % substitute i for j
td(j*bh+1:(j+1)*bh, :) = [j*o, t];
t = od; % for new even
t(od==j) = i; % substitute i for j
te(j*bh+1:(j+1)*bh, :) = [j*o, t];
end
odd{end+1} = td; % save for later use
even{end+1} = te;
end
return; % from makeEvenOdd
end
% ------------------ end makeEvenOdd ---------------------
end
% --------------------- end allPerms -----------------------------
function allCycles % nesting level 1
md = nc;
mr = nr*md;
% force numeric type for zeros()
if ischar(M), w = uint16(M);
elseif islogical(M), w = uint8(M);
else w = M;
end
res = zeros(mr, nc, class(w)); % preallocate result
% do the work
for i=1:nr
s = 1+(i-1)*md;
bl = s:i*md;
res(bl,1:nc) = repmat(w(i,:), md, 1);
for r = s+1:s+nc-1
res(r, [2:end, 1]) = res(r-1, :); % end around
end
end
% restore input type
if islogical(M), M = logical(res);
elseif ischar(M), M = char(res);
elseif issparse(M), M = sparse(res);
else M = res;
end
return; % from allcycles
end
% ----------------- end allcycles ----------------------------
function allSigns % nesting level 1
if ~isnumeric(M)
error('MATLAB:perms:signs', 'requires numeric argument');
end
r = class(M);
if r(1) == 'u'
error('MATLAB:perms:signedarg', 'requires signed argument');
end
md = 2^nc; % all signs
mr = nr*md; % result size
% allocate result
p = zeros(mr, nc, class(M)); % worst case
% do the work
for i=1:nr % one input row at a time
tmp = repmat(M(i,:), md, 1); % block of data
step = md;
for j=1:nc % for each column
sgn = 1;
step = step/2;
rep = md/step;
for k = 0:rep-1 % for each block
sgn = -sgn;
for m = 1:step
row = k*step+m;
tmp(row,j) = sgn*tmp(row,j);
end
end
end
p(md*(i-1)+1:i*md,:) = tmp;
end
M = p; % report result
end
% ----------------------- end allSigns ----------------
end
%------------------------ end perms ------------------
|
github | leopoldofr/swarmdrones-master | vertices.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/vertices.m | 3,263 | utf_8 | 3d3d000bd078539847457004c69a2030 | % FILE: vertices.m
% PURPOSE: mXn array of vertices for named polytopes
% center on the origin with unit edge
% NAMES: nnntttt where nnn is the number of ttt is unambiguous
% name Schlafli popular
% 3edge s3 (triangle)
% 5edge s5 (pentagon)
% 4face s34 tetrahedron (start of simplex series)
% 6face s43 cube (start of measure series)
% 8face s34 octahedron (start of cross series)
% 12face s53 dodecahedron
% 20face s35 icosahedron
% 5cell s333 hypertetrahedron (4-simplex)
% 16cell s334 hyperoctahedron (4-cross)
% 8cell s433 hypercube (4-measure)
% 24cell s343 (unique and nameless)
% 120cell s533 hyperdodecahedron
% 600cell s355 hypericosahedron
function v = vertices(varargin)
if nargin == 1 % figure name
name = varargin{1};
elseif nargin == 2 % d,nf description
switch varargin{1}
case {2, '2'}, bound = 'edge';
case {3, '3'}, bound = 'face';
case {4, '4'}, bound = 'cell';
otherwise, error('no such dimension');
end
count = varargin{2};
if ~ischar(count), count = num2str(count); end
name = [count bound];
end
if numel(name) > 4 && strcmp(name(end-3:end), 'edge')
vct = str2double(name(1:end-4)); % polygon
a = 2*pi*(1:vct)/vct;
v = [sin(a); cos(a)]';
e = v(1,:) - v(2,:); % an edge
v = v/sqrt(e*e'); % unit edges
else
r2 = sqrt(2);
r5 = sqrt(5);
gr = (1+r5)/2; % golden ratio
switch name
case {'4face', 'tetrahedron', 's33', '3simplex'}
v = perms([1 0 0 0]/r2, 'cycles');
case {'6face', 'cube', 's43', '3measure'}
v = perms([1 1 1]/2, 'signs');
case {'8face', 'octahedron', 's34', '3cross'}
v = perms([1 0 0]/r2, 'cycles', 'signs', 'unique');
case {'12face', 'dodecahedron', 's53'}
v1 = perms([0 1 gr^2], 'cycles');
v = perms([v1; [1 1 1]*gr]/2, 'signs', 'unique');
case {'20face', 'icosahedron', 's35'}
v = perms([1 0 gr]/2, 'cycles', 'signs', 'unique');
case {'5cell', 'hypertetrahedron', 's333', '4simplex'}
v = perms([1 0 0 0 0]/r2, 'cycles');
case {'8cell', 'hypercube', 's433', '4measure'}
v = perms([1 1 1 1]/2, 'signs');
case {'16cell', 'hyperoctahedron', 's334', '4cross'}
v = perms([1 0 0 0]/r2, 'cycles', 'signs', 'unique');
case {'24cell', 's343'}
v = perms([1 1 0 0]/r2, 'signs', 'all', 'unique'); % 24 cell
case {'120cell', 'hyperdodecahedron', 's533'}
vs1 = perms([...
2 2 0 0;
r5 1 1 1;
gr gr gr gr^-2;
gr^2 gr^-1 gr^-1 gr^-1], 'unique');
vs2 = perms([...
gr^2 gr^-2 1 0;
r5 gr^-1 gr 0;
2 1 gr gr^-1], 'even');
v = perms([vs1; vs2]*gr^2/2, 'signs', 'unique'); % 120 cell
case {'600cell', 'hypericosahedron', 's335'}
vs1 = perms([2 0 0 0; 1 1 1 1], 'cycles');
vs2 = perms([gr 1 gr^-1 0], 'even');
v = perms([vs1; vs2]*gr/2, 'signs', 'unique'); % 600 cell
otherwise,
error(['bad input ' name]);
end
end
|
github | leopoldofr/swarmdrones-master | polyhedron.m | .m | swarmdrones-master/Add-Ons/Collections/Polytopes/code/polyhedron.m | 2,042 | utf_8 | 095fc8fc1a38ab7565bd3a842b2d1306 | % FILE: polyhedron.m
% PURPOSE: general object representation of regular polytope
function poly = polyhedron(name);
TOL = 1.0E-6;
v = vertices(name);
dim = size(v, 2);
nv = size(v, 1); % vertex count
% edge-square matrix
d = zeros(nv);
for i=1:nv
for j=i+1:nv
ev = v(i,:)-v(j,:);
d(i,j) = sum(ev.*ev); % edge^2
end
end
e2 = d(d(:)~=0); % nonzero edge^2 s
me = min(e2); % smallest
edge = sqrt(me); % edge length
v = v./edge; % scale to unit edge
% find edges
[i,j] = find(abs(me - d) < TOL);
e = reshape([i, j], numel(i), 2); % edges
ne = size(e,1); % edge count
% vertex connectivity
c = inf(nv);
for i=1:nv
c(i,i)=0; % distance 0
end
for i=1:ne
j = e(i,1); k = e(i,2);
c(j,k) = 1; c(k,j) = 1; % distance 0&1
end
angles = [];
for i=1:nv
nbr = [];
for j=1:nv
if c(i,j) == 1
nbr(end+1) = j; % neighbors
end
end
lim=numel(nbr); % how many neighbors
for j=1:lim % all pairs of ne...
for k=j+1:lim
angles(end+1,:) = sort([i, nbr(j), nbr(k)]);
end
end
end
angles = unique(angles, 'rows');
size(angles,1)
planes = [];
for i=1:size(angles,1) % all angles
planes(i,:) = v(angles(i,:),:)\ones(dim,1);
end
[ps, pi] = sort(planes(:)); % collect like items
pd = diff(ps) < TOL; % find transitions
tmp = ps(1); % head of "equal" list
for i=1:numel(pd) % use std rep for each value
if pd(i)
planes(pi(i+1)) = tmp; % use unique value
else
tmp = ps(i+1); % new head of "equal"
end
end
planes = unique(planes, 'rows'); % single up the vectors
poly.vertices = v;
poly.edges = edges;
poly.planes = planes
|
github | leopoldofr/swarmdrones-master | vert2lcon.m | .m | swarmdrones-master/Add-Ons/Collections/Analyze N-dimensional Polyhedra in terms of Vertices or (In)Equalities/code/vert2lcon.m | 5,797 | utf_8 | f6cb0590d7d8c589aae28abde08d3b9e | function [A,b,Aeq,beq]=vert2lcon(V,tol)
%An extension of Michael Kleder's vert2con function, used for finding the
%linear constraints defining a polyhedron in R^n given its vertices. This
%wrapper extends the capabilities of vert2con to also handle cases where the
%polyhedron is not solid in R^n, i.e., where the polyhedron is defined by
%both equality and inequality constraints.
%
%SYNTAX:
%
% [A,b,Aeq,beq]=vert2lcon(V,TOL)
%
%The rows of the N x n matrix V are a series of N vertices of a polyhedron
%in R^n. TOL is a rank-estimation tolerance (Default = 1e-10).
%
%Any point x inside the polyhedron will/must satisfy
%
% A*x <= b
% Aeq*x = beq
%
%up to machine precision issues.
%
%
%EXAMPLE:
%
%Consider V=eye(3) corresponding to the 3D region defined
%by x+y+z=1, x>=0, y>=0, z>=0.
%
%
% >>[A,b,Aeq,beq]=vert2lcon(eye(3))
%
%
% A =
%
% 0.4082 -0.8165 0.4082
% 0.4082 0.4082 -0.8165
% -0.8165 0.4082 0.4082
%
%
% b =
%
% 0.4082
% 0.4082
% 0.4082
%
%
% Aeq =
%
% 0.5774 0.5774 0.5774
%
%
% beq =
%
% 0.5774
%%initial stuff
if nargin<2, tol=1e-10; end
[M,N]=size(V);
if M==1
A=[];b=[];
Aeq=eye(N); beq=V(:);
return
end
p=V(1,:).';
X=bsxfun(@minus,V.',p);
%In the following, we need Q to be full column rank
%and we prefer E compact.
if M>N %X is wide
[Q, R, E] = qr(X,0); %economy-QR ensures that E is compact.
%Q automatically full column rank since X wide
else%X is tall, hence non-solid polytope
[Q, R, P]=qr(X); %non-economy-QR so that Q is full-column rank.
[~,E]=max(P); %No way to get E compact. This is the alternative.
clear P
end
diagr = abs(diag(R));
if nnz(diagr)
%Rank estimation
r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation
iE=1:length(E);
iE(E)=iE;
Rsub=R(1:r,iE).';
if r>1
[A,b]=vert2con(Rsub,tol);
elseif r==1
A=[1;-1];
b=[max(Rsub);-min(Rsub)];
end
A=A*Q(:,1:r).';
b=bsxfun(@plus,b,A*p);
if r<N
Aeq=Q(:,r+1:end).';
beq=Aeq*p;
else
Aeq=[];
beq=[];
end
else %Rank=0. All points are identical
A=[]; b=[];
Aeq=eye(N);
beq=p;
end
% ibeq=abs(beq);
% ibeq(~beq)=1;
%
% Aeq=bsxfun(@rdivide,Aeq,ibeq);
% beq=beq./ibeq;
function [A,b] = vert2con(V,tol)
% VERT2CON - convert a set of points to the set of inequality constraints
% which most tightly contain the points; i.e., create
% constraints to bound the convex hull of the given points
%
% [A,b] = vert2con(V)
%
% V = a set of points, each ROW of which is one point
% A,b = a set of constraints such that A*x <= b defines
% the region of space enclosing the convex hull of
% the given points
%
% For n dimensions:
% V = p x n matrix (p vertices, n dimensions)
% A = m x n matrix (m constraints, n dimensions)
% b = m x 1 vector (m constraints)
%
% NOTES: (1) In higher dimensions, duplicate constraints can
% appear. This program detects duplicates at up to 6
% digits of precision, then returns the unique constraints.
% (2) See companion function CON2VERT.
% (3) ver 1.0: initial version, June 2005.
% (4) ver 1.1: enhanced redundancy checks, July 2005
% (5) Written by Michael Kleder,
%
%Modified by Matt Jacobson - March 29,2011
%
k = convhulln(V);
c = mean(V(unique(k),:));
V = bsxfun(@minus,V,c);
A = nan(size(k,1),size(V,2));
dim=size(V,2);
ee=ones(size(k,2),1);
rc=0;
for ix = 1:size(k,1)
F = V(k(ix,:),:);
if lindep(F,tol) == dim
rc=rc+1;
A(rc,:)=F\ee;
end
end
A=A(1:rc,:);
b=ones(size(A,1),1);
b=b+A*c';
% eliminate duplicate constraints:
[A,b]=rownormalize(A,b);
[discard,I]=unique( round([A,b]*1e6),'rows');
A=A(I,:); % NOTE: rounding is NOT done for actual returned results
b=b(I);
return
function [A,b]=rownormalize(A,b)
%Modifies A,b data pair so that norm of rows of A is either 0 or 1
if isempty(A), return; end
normsA=sqrt(sum(A.^2,2));
idx=normsA>0;
A(idx,:)=bsxfun(@rdivide,A(idx,:),normsA(idx));
b(idx)=b(idx)./normsA(idx);
function [r,idx,Xsub]=lindep(X,tol)
%Extract a linearly independent set of columns of a given matrix X
%
% [r,idx,Xsub]=lindep(X)
%
%in:
%
% X: The given input matrix
% tol: A rank estimation tolerance. Default=1e-10
%
%out:
%
% r: rank estimate
% idx: Indices (into X) of linearly independent columns
% Xsub: Extracted linearly independent columns of X
if ~nnz(X) %X has no non-zeros and hence no independent columns
Xsub=[]; idx=[];
return
end
if nargin<2, tol=1e-10; end
[Q, R, E] = qr(X,0);
diagr = abs(diag(R));
%Rank estimation
r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation
if nargout>1
idx=sort(E(1:r));
%idx=E(1:r);
idx=idx(:);
end
if nargout>2
Xsub=X(:,idx);
end |
github | leopoldofr/swarmdrones-master | lcon2vert.m | .m | swarmdrones-master/Add-Ons/Collections/Analyze N-dimensional Polyhedra in terms of Vertices or (In)Equalities/code/lcon2vert.m | 14,604 | utf_8 | 4cf3229f4ffd4ec8ca0d01178ba81e80 | function [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL,checkbounds)
%An extension of Michael Kleder's con2vert function, used for finding the
%vertices of a bounded polyhedron in R^n, given its representation as a set
%of linear constraints. This wrapper extends the capabilities of con2vert to
%also handle cases where the polyhedron is not solid in R^n, i.e., where the
%polyhedron is defined by both equality and inequality constraints.
%
%SYNTAX:
%
% [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL)
%
%The rows of the N x n matrix V are a series of N vertices of the polyhedron
%in R^n, defined by the linear constraints
%
% A*x <= b
% Aeq*x = beq
%
%By default, Aeq=beq=[], implying no equality constraints. The output "nr"
%lists non-redundant inequality constraints, and "nre" lists non-redundant
%equality constraints.
%
%The optional TOL argument is a tolerance used for both rank-estimation and
%for testing feasibility of the equality constraints. Default=1e-10.
%The default can also be obtained by passing TOL=[];
%
%
%EXAMPLE:
%
%The 3D region defined by x+y+z=1, x>=0, y>=0, z>=0
%is described by the following constraint data.
%
%
% A =
%
% 0.4082 -0.8165 0.4082
% 0.4082 0.4082 -0.8165
% -0.8165 0.4082 0.4082
%
%
% b =
%
% 0.4082
% 0.4082
% 0.4082
%
%
% Aeq =
%
% 0.5774 0.5774 0.5774
%
%
% beq =
%
% 0.5774
%
%
% >> V=lcon2vert(A,b,Aeq,beq)
%
% V =
%
% 1.0000 0.0000 0.0000
% 0.0000 0.0000 1.0000
% -0.0000 1.0000 0.0000
%
%
%%initial argument parsing
nre=[];
nr=[];
if nargin<5 || isempty(TOL), TOL=1e-10; end
if nargin<6, checkbounds=true; end
switch nargin
case 0
error 'At least 1 input argument required'
case 1
b=[]; Aeq=[]; beq=[];
case 2
Aeq=[]; beq=[];
case 3
beq=[];
error 'Since argument Aeq specified, beq must also be specified'
end
b=b(:); beq=beq(:);
if xor(isempty(A), isempty(b))
error 'Since argument A specified, b must also be specified'
end
if xor(isempty(Aeq), isempty(beq))
error 'Since argument Aeq specified, beq must also be specified'
end
nn=max(size(A,2)*~isempty(A),size(Aeq,2)*~isempty(Aeq));
if ~isempty(A) && ~isempty(Aeq) && ( size(A,2)~=nn || size(Aeq,2)~=nn)
error 'A and Aeq must have the same number of columns if both non-empty'
end
inequalityConstrained=~isempty(A);
equalityConstrained=~isempty(Aeq);
[A,b]=rownormalize(A,b);
[Aeq,beq]=rownormalize(Aeq,beq);
if equalityConstrained && nargout>2
[discard,nre]=lindep([Aeq,beq].',TOL);
if ~isempty(nre) %reduce the equality constraints
Aeq=Aeq(nre,:);
beq=beq(nre);
else
equalityConstrained=false;
end
end
%%Find 1 solution to equality constraints within tolerance
if equalityConstrained
Neq=null(Aeq);
x0=pinv(Aeq)*beq;
if norm(Aeq*x0-beq)>TOL*norm(beq), %infeasible
nre=[]; nr=[]; %All constraints redundant for empty polytopes
V=[];
return;
elseif isempty(Neq)
V=x0(:).';
nre=(1:nn).'; %Equality constraints determine everything.
nr=[];%All inequality constraints are therefore redundant.
return
end
rkAeq= nn - size(Neq,2);
end
%%
if inequalityConstrained && equalityConstrained
AAA=A*Neq;
bbb=b-A*x0;
elseif inequalityConstrained
AAA=A;
bbb=b;
elseif equalityConstrained && ~inequalityConstrained
error('Non-bounding constraints detected. (Consider box constraints on variables.)')
end
nnn=size(AAA,2);
if nnn==1 %Special case
idxu=sign(AAA)==1;
idxl=sign(AAA)==-1;
idx0=sign(AAA)==0;
Q=bbb./AAA;
U=Q;
U(~idxu)=inf;
L=Q;
L(~idxl)=-inf;
[ub,uloc]=min(U);
[lb,lloc]=max(L);
if ~all(bbb(idx0)>=0) || ub<lb %infeasible
V=[]; nr=[]; nre=[];
return
elseif ~isfinite(ub) || ~isfinite(lb)
error('Non-bounding constraints detected. (Consider box constraints on variables.)')
end
Zt=[lb;ub];
if nargout>1
nr=unique([lloc,uloc]); nr=nr(:);
end
else
if nargout>1
[Zt,nr]=con2vert(AAA,bbb,TOL,checkbounds);
else
Zt=con2vert(AAA,bbb,TOL,checkbounds);
end
end
if equalityConstrained && ~isempty(Zt)
V=bsxfun(@plus,Zt*Neq.',x0(:).');
else
V=Zt;
end
if isempty(V),
nr=[]; nre=[];
end
function [V,nr] = con2vert(A,b,TOL,checkbounds)
% CON2VERT - convert a convex set of constraint inequalities into the set
% of vertices at the intersections of those inequalities;i.e.,
% solve the "vertex enumeration" problem. Additionally,
% identify redundant entries in the list of inequalities.
%
% V = con2vert(A,b)
% [V,nr] = con2vert(A,b)
%
% Converts the polytope (convex polygon, polyhedron, etc.) defined by the
% system of inequalities A*x <= b into a list of vertices V. Each ROW
% of V is a vertex. For n variables:
% A = m x n matrix, where m >= n (m constraints, n variables)
% b = m x 1 vector (m constraints)
% V = p x n matrix (p vertices, n variables)
% nr = list of the rows in A which are NOT redundant constraints
%
% NOTES: (1) This program employs a primal-dual polytope method.
% (2) In dimensions higher than 2, redundant vertices can
% appear using this method. This program detects redundancies
% at up to 6 digits of precision, then returns the
% unique vertices.
% (3) Non-bounding constraints give erroneous results; therefore,
% the program detects non-bounding constraints and returns
% an error. You may wish to implement large "box" constraints
% on your variables if you need to induce bounding. For example,
% if x is a person's height in feet, the box constraint
% -1 <= x <= 1000 would be a reasonable choice to induce
% boundedness, since no possible solution for x would be
% prohibited by the bounding box.
% (4) This program requires that the feasible region have some
% finite extent in all dimensions. For example, the feasible
% region cannot be a line segment in 2-D space, or a plane
% in 3-D space.
% (5) At least two dimensions are required.
% (6) See companion function VERT2CON.
% (7) ver 1.0: initial version, June 2005
% (8) ver 1.1: enhanced redundancy checks, July 2005
% (9) Written by Michael Kleder
%
%Modified by Matt Jacobson - March 30, 2011
%
%%%3/4/2012 Improved boundedness test - unfortunately slower than Michael Kleder's
if checkbounds
[aa,bb,aaeq,bbeq]=vert2lcon(A,TOL);
if any(bb<=0) || ~isempty(bbeq)
error('Non-bounding constraints detected. (Consider box constraints on variables.)')
end
clear aa bb aaeq bbeq
end
dim=size(A,2);
%%%Matt J initialization
if strictinpoly(b,TOL)
c=zeros(dim,1);
else
slackfun=@(c)b-A*c;
%Initializer0
c = pinv(A)*b; %02/17/2012 -replaced with pinv()
s=slackfun(c);
if ~approxinpoly(s,TOL) %Initializer1
c=Initializer1(TOL,A,b,c);
s=slackfun(c);
end
if ~approxinpoly(s,TOL) %Attempt refinement
%disp 'It is unusually difficult to find an interior point of your polytope. This may take some time... '
%disp ' '
c=Initializer2(TOL,A,b,c);
%[c,fval]=Initializer1(TOL,A,b,c,10000);
s=slackfun(c);
end
if ~approxinpoly(s,TOL)
%error('Unable to locate a point near the interior of the feasible region.')
V=[];
nr=[];
return
end
if ~strictinpoly(s,TOL) %Added 02/17/2012 to handle initializers too close to polytope surface
%disp 'Recursing...'
idx=( abs(s)<=max(s)*TOL );
Amod=A; bmod=b;
Amod(idx,:)=[];
bmod(idx)=[];
Aeq=A(idx,:); %pick the nearest face to c
beq=b(idx);
faceVertices=lcon2vert(Amod,bmod,Aeq,beq,TOL,1);
if isempty(faceVertices)
disp 'Something''s wrong. Couldn''t find face vertices. Possibly polyhedron is unbounded.'
keyboard
end
c=faceVertices(1,:).'; %Take any vertex - find local recession cone vector
s=slackfun(c);
idx=( abs(s)<=max(s)*TOL );
Asub=A(idx,:); bsub=b(idx,:);
[aa,bb,aaeq,bbeq]=vert2lcon(Asub);
aa=[aa;aaeq;-aaeq];
bb=[bb;bbeq;-bbeq];
clear aaeq bbeq
[bmin,idx]=min(bb);
if bmin>=-TOL
disp 'Something''s wrong. We should have found a recession vector (bb<0).'
keyboard
end
Aeq2=null(aa(idx,:)).';
beq2=Aeq2*c; %find intersection of polytope with line through facet centroid.
linetips = lcon2vert(A,b,Aeq2,beq2,TOL,1);
if size(linetips,1)<2
disp 'Failed to identify line segment through interior.'
disp 'Possibly {x: Aeq*x=beq} has weak intersection with interior({x: Ax<=b}).'
keyboard
end
lineCentroid=mean(linetips);%Relies on boundedness
clear aa bb
c=lineCentroid(:);
s=slackfun(c);
end
b = s;
end
%%%end Matt J initialization
D=bsxfun(@rdivide,A,b);
k = convhulln(D);
nr = unique(k(:));
G = zeros(size(k,1),dim);
ee=ones(size(k,2),1);
discard=false( 1, size(k,1) );
for ix = 1:size(k,1) %02/17/2012 - modified
F = D(k(ix,:),:);
if lindep(F,TOL)<dim;
discard(ix)=1;
continue;
end
G(ix,:)=F\ee;
end
G(discard,:)=[];
V = bsxfun(@plus, G, c.');
[discard,I]=unique( round(V*1e6),'rows');
V=V(I,:);
return
function [c,fval]=Initializer1(TOL, A,b,c,maxIter)
thresh=-10*max(eps(b));
if nargin>4
[c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c,optimset('MaxIter',maxIter));
else
[c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c);
end
return
function c=Initializer2(TOL,A,b,c)
%norm( (I-A*pinv(A))*(s-b) ) subj. to s>=0
maxIter=100000;
[mm,nn]=size(A);
Ap=pinv(A);
Aaug=speye(mm)-A*Ap;
Aaugt=Aaug.';
M=Aaugt*Aaug;
C=sum(abs(M),2);
C(C<=0)=min(C(C>0));
slack=b-A*c;
slack(slack<0)=0;
% relto=norm(b);
% relto =relto + (relto==0);
%
% relres=norm(A*c-b)/relto;
IterThresh=maxIter;
s=slack;
ii=0;
%for ii=1:maxIter
while ii<=2*maxIter %HARDCODE
ii=ii+1;
if ii>IterThresh,
%warning 'This is taking a lot of iterations'
IterThresh=IterThresh+maxIter;
end
s=s-Aaugt*(Aaug*(s-b))./C;
s(s<0)=0;
c=Ap*(b-s);
%slack=b-A*c;
%relres=norm(slack)/relto;
%if all(0<slack,1)||relres<1e-6||ii==maxIter, break; end
end
return
function [r,idx,Xsub]=lindep(X,tol)
%Extract a linearly independent set of columns of a given matrix X
%
% [r,idx,Xsub]=lindep(X)
%
%in:
%
% X: The given input matrix
% tol: A rank estimation tolerance. Default=1e-10
%
%out:
%
% r: rank estimate
% idx: Indices (into X) of linearly independent columns
% Xsub: Extracted linearly independent columns of X
if ~nnz(X) %X has no non-zeros and hence no independent columns
Xsub=[]; idx=[];
return
end
if nargin<2, tol=1e-10; end
[Q, R, E] = qr(X,0);
diagr = abs(diag(R));
%Rank estimation
r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation
if nargout>1
idx=sort(E(1:r));
%idx=E(1:r);
idx=idx(:);
end
if nargout>2
Xsub=X(:,idx);
end
function [A,b]=rownormalize(A,b)
%Modifies A,b data pair so that norm of rows of A is either 0 or 1
if isempty(A), return; end
normsA=sqrt(sum(A.^2,2));
idx=normsA>0;
A(idx,:)=bsxfun(@rdivide,A(idx,:),normsA(idx));
b(idx)=b(idx)./normsA(idx);
function tf=approxinpoly(s,TOL)
smax=max(s);
if smax<=0
tf=false; return
end
tf=all(s>=-smax*TOL);
function tf=strictinpoly(s,TOL)
smax=max(s);
if smax<=0
tf=false; return
end
tf=all(s>=smax*TOL);
|
github | leopoldofr/swarmdrones-master | meshSurfaceArea.m | .m | swarmdrones-master/Add-Ons/Toolboxes/geom3d/code/geom3d/meshes3d/meshSurfaceArea.m | 1,953 | utf_8 | 6c23f572f09acfe17fd0453564093469 | function area = meshSurfaceArea(vertices, edges, faces)
%MESHSURFACEAREA Surface area of a polyhedral mesh
%
% S = meshSurfaceArea(V, F)
% S = meshSurfaceArea(V, E, F)
% Computes the surface area of the mesh specified by vertex array V and
% face array F. Vertex array is a NV-by-3 array of coordinates.
% Face array can be a NF-by-3 or NF-by-4 numeric array, or a Nf-by-1 cell
% array, containing vertex indices of each face.
%
% This functions iterates on faces, extract vertices of the current face,
% and computes the sum of face areas.
%
% This function assumes faces are coplanar and convex. If faces are all
% triangular, the function "trimeshSurfaceArea" should be more efficient.
%
%
% Example
% % compute the surface of a unit cube (should be equal to 6)
% [v f] = createCube;
% meshSurfaceArea(v, f)
% ans =
% 6
%
% See also
% meshes3d, trimeshSurfaceArea, meshVolume, meshFacePolygons,
% polygonArea3d
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2010-10-13, using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.
% check input number
if nargin == 2
faces = edges;
end
% pre-compute normals
normals = normalizeVector3d(faceNormal(vertices, faces));
% init accumulator
area = 0;
if isnumeric(faces)
% iterate on faces in a numeric array
for i = 1:size(faces, 1)
poly = vertices(faces(i, :), :);
area = area + polyArea3d(poly, normals(i,:));
end
else
% iterate on faces in a cell array
for i = 1:length(faces)
poly = vertices(faces{i}, :);
area = area + polyArea3d(poly, normals(i,:));
end
end
function a = polyArea3d(v, normal)
nv = size(v, 1);
v0 = repmat(v(1,:), nv, 1);
products = sum(cross(v-v0, v([2:end 1], :)-v0, 2), 1);
a = abs(dot(products, normal, 2))/2;
|
github | leopoldofr/swarmdrones-master | mergeCoplanarFaces.m | .m | swarmdrones-master/Add-Ons/Toolboxes/geom3d/code/geom3d/meshes3d/mergeCoplanarFaces.m | 10,111 | utf_8 | 28a4d5c9c038ed1d5250c1babe495a14 | function varargout = mergeCoplanarFaces(nodes, varargin)
%MERGECOPLANARFACES Merge coplanar faces of a polyhedral mesh
%
% [NODES FACES] = mergeCoplanarFaces(NODES, FACES)
% [NODES EDGES FACES] = mergeCoplanarFaces(NODES, EDGES, FACES)
% NODES is a set of 3D points (as a nNodes-by-3 array),
% and FACES is one of:
% - a nFaces-by-X array containing vertex indices of each face, with each
% face having the same number of vertices,
% - a nFaces-by-1 cell array, each cell containing indices of a face.
% The function groups faces which are coplanar and contiguous, resulting
% in a "lighter" mesh. This can be useful for visualizing binary 3D
% images for example.
%
% FACES = mergeCoplanarFaces(..., PRECISION)
% Adjust the threshold for deciding if two faces are coplanar or
% parallel. Default value is 1e-5.
%
% Example
% [v e iFace] = createCube;
% figure; drawMesh(v, iFace); view(3); axis equal;
% [v2 f2] = mergeCoplanarFaces(v, iFace);
% figure; drawMesh(v, f2);
% view(3); axis equal; view(3);
%
% See also
% meshes3d, drawMesh, minConvexHull, triangulateFaces
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2006-07-05
% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).
% 20/07/2006 add tolerance for coplanarity test
% 21/08/2006 fix small bug due to difference of methods to test
% coplanaritity, sometimes resulting in 3 points of a face not coplanar !
% Also add control on precision
% 14/08/2007 rename minConvexHull->meshReduce, and extend to non convex
% shapes
% 2011-01-14 code clean up
% 2013-02-22 rename from meshReduce to mergeCoplanarFaces
%% Process input arguments
% set up precision
acc = 1e-5;
if ~isempty(varargin)
var = varargin{end};
if length(var) == 1
acc = var;
varargin(end) = [];
end
end
% extract faces and edges
if length(varargin) == 1
faces = varargin{1};
else
faces = varargin{2};
end
%% Initialisations
% number of faces
nNodes = size(nodes, 1);
nFaces = size(faces, 1);
% compute number of vertices of each face
Fn = ones(nFaces, 1) * size(faces, 2);
% compute normal of each faces
normals = faceNormal(nodes, faces);
% initialize empty faces and edges
faces2 = cell(0, 1);
edges2 = zeros(0, 2);
% Processing flag for each face
% 1: face to process, 0: already processed
% in the beginning, every triangle face need to be processed
flag = ones(nFaces, 1);
%% Main iteration
% iterate on each face
for iFace = 1:nFaces
% check if face was already performed
if ~flag(iFace)
continue;
end
% indices of faces with same normal
% ind = find(abs(vectorNorm3d(cross(repmat(normals(iFace, :), [nFaces 1]), normals)))<acc);
ind = find(vectorNorm3d(vectorCross3d(normals(iFace, :), normals)) < acc);
% keep only coplanar faces (test coplanarity of points in both face)
ind2 = false(size(ind));
for j = 1:length(ind)
ind2(j) = isCoplanar(nodes([faces(iFace,:) faces(ind(j),:)], :), acc);
end
ind2 = ind(ind2);
% compute edges of all faces in the plane
planeEdges = zeros(sum(Fn(ind2)), 2);
pos = 1;
for i = 1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
planeEdges(pos:sum(Fn(ind2(1:i))), :) = faceEdges;
pos = sum(Fn(ind2(1:i)))+1;
end
planeEdges = unique(planeEdges, 'rows');
% relabel plane edges
[planeNodes, I, J] = unique(planeEdges(:)); %#ok<ASGLU>
planeEdges2 = reshape(J, size(planeEdges));
% The set of coplanar faces may not necessarily form a single connected
% component. The following computes label of each connected component.
component = grLabel(nodes(planeNodes, :), planeEdges2);
% compute degree (number of adjacent faces) of each edge.
Npe = size(planeEdges, 1);
edgeDegrees = zeros(Npe, 1);
for i = 1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
for j = 1:size(faceEdges, 1)
indEdge = find(sum(ismember(planeEdges, faceEdges(j,:)),2)==2);
edgeDegrees(indEdge) = edgeDegrees(indEdge)+1;
end
end
% extract unique edges and nodes of the plane
planeEdges = planeEdges(edgeDegrees==1, :);
planeEdges2 = planeEdges2(edgeDegrees==1, :);
% find connected component of each edge
planeEdgesComp = zeros(size(planeEdges, 1), 1);
for iEdge = 1:size(planeEdges, 1)
planeEdgesComp(iEdge) = component(planeEdges2(iEdge, 1));
end
% iterate on connected faces
for c = 1:max(component)
% convert to chains of nodes
loops = graph2Contours(nodes, planeEdges(planeEdgesComp==c, :));
% add a simple Polygon for each loop
facePolygon = loops{1};
for l = 2:length(loops)
facePolygon = [facePolygon, NaN, loops{l}]; %#ok<AGROW>
end
faces2{length(faces2)+1, 1} = facePolygon;
% also add news edges
edges2 = unique([edges2; planeEdges], 'rows');
end
% mark processed faces
flag(ind2) = 0;
end
%% Additional processing on nodes
% select only nodes which appear in at least one edge
indNodes = unique(edges2(:));
% for each node, compute index of corresponding new node (or 0 if dropped)
refNodes = zeros(nNodes, 1);
for i = 1:length(indNodes)
refNodes(indNodes(i)) = i;
end
% changes indices of nodes in edges2 array
for i = 1:length(edges2(:))
edges2(i) = refNodes(edges2(i));
end
% changes indices of nodes in faces2 array
for iFace = 1:length(faces2)
face = faces2{iFace};
for i = 1:length(face)
if ~isnan(face(i))
face(i) = refNodes(face(i));
end
end
faces2{iFace} = face;
end
% keep only boundary nodes
nodes2 = nodes(indNodes, :);
%% Process output arguments
if nargout == 1
varargout{1} = faces2;
elseif nargout == 2
varargout{1} = nodes2;
varargout{2} = faces2;
elseif nargout == 3
varargout{1} = nodes2;
varargout{2} = edges2;
varargout{3} = faces2;
end
function labels = grLabel(nodes, edges)
%GRLABEL associate a label to each connected component of the graph
% LABELS = grLabel(NODES, EDGES)
% Returns an array with as many rows as the array NODES, containing index
% number of each connected component of the graph. If the graph is
% totally connected, returns an array of 1.
%
% Example
% nodes = rand(6, 2);
% edges = [1 2;1 3;4 6];
% labels = grLabel(nodes, edges);
% labels =
% 1
% 1
% 1
% 2
% 3
% 2
%
% See also
% getNeighbourNodes
%
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2007-08-14, using Matlab 7.4.0.287 (R2007a)
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.
% init
nNodes = size(nodes, 1);
labels = (1:nNodes)';
% iteration
modif = true;
while modif
modif = false;
for i=1:nNodes
neigh = getNeighbourNodes(i, edges);
neighLabels = labels([i;neigh]);
% check for a modification
if length(unique(neighLabels))>1
modif = true;
end
% put new labels
labels(ismember(labels, neighLabels)) = min(neighLabels);
end
end
% change to have fewer labels
labels2 = unique(labels);
for i = 1:length(labels2)
labels(labels==labels2(i)) = i;
end
function nodes2 = getNeighbourNodes(node, edges)
%GETNEIGHBOURNODES find nodes adjacent to a given node
%
% NEIGHS = getNeighbourNodes(NODE, EDGES)
% NODE: index of the node
% EDGES: the complete edges list
% NEIGHS: the nodes adjacent to the given node.
%
% NODE can also be a vector of node indices, in this case the result is
% the set of neighbors of any input node.
%
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 16/08/2004.
%
% HISTORY
% 10/02/2004 documentation
% 13/07/2004 faster algorithm
% 03/10/2007 can specify several input nodes
[i, j] = find(ismember(edges, node)); %#ok<NASGU>
nodes2 = edges(i,1:2);
nodes2 = unique(nodes2(:));
nodes2 = sort(nodes2(~ismember(nodes2, node)));
function curves = graph2Contours(nodes, edges) %#ok<INUSL>
%GRAPH2CONTOURS convert a graph to a set of contour curves
%
% CONTOURS = GRAPH2CONTOURS(NODES, EDGES)
% NODES, EDGES is a graph representation (type "help graph" for details)
% The algorithm assume every node has degree 2, and the set of edges
% forms only closed loops. The result is a list of indices arrays, each
% array containing consecutive point indices of a contour.
%
% To transform contours into drawable curves, please use :
% CURVES{i} = NODES(CONTOURS{i}, :);
%
%
% NOTE : contours are not oriented. To manage contour orientation, edges
% also need to be oriented. So we must precise generation of edges.
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 05/08/2004.
%
curves = {};
c = 0;
while size(edges,1)>0
% find first point of the curve
n0 = edges(1,1);
curve = n0;
% second point of the curve
n = edges(1,2);
e = 1;
while true
% add current point to the curve
curve = [curve n]; %#ok<AGROW>
% remove current edge from the list
edges = edges((1:size(edges,1))~=e,:);
% find index of edge containing reference to current node
e = find(edges(:,1)==n | edges(:,2)==n);
e = e(1);
% get index of next current node
% (this is the other node of the current edge)
if edges(e,1)==n
n = edges(e,2);
else
n = edges(e,1);
end
% if node is same as start node, loop is closed, and we stop
% node iteration.
if n==n0
break;
end
end
% remove the last edge of the curve from edge list.
edges = edges((1:size(edges,1))~=e,:);
% add the current curve to the list, and start a new curve
c = c+1;
curves{c} = curve; %#ok<AGROW>
end
|
github | leopoldofr/swarmdrones-master | demoRevolutionSurface.m | .m | swarmdrones-master/Add-Ons/Toolboxes/geom3d/code/geom3d/geom3d-demos/demoRevolutionSurface.m | 1,883 | utf_8 | ffbdd22c55d7d5c868fcf22051cb2842 | function demoRevolutionSurface(varargin)
%DEMOREVOLUTIONSURFACE One-line description here, please.
% output = demoRevolutionSurface(input)
%
% Example
% demoRevolutionSurface
%
% See also
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2007-04-20
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.
%% Draw a torus with vertical axis as revolution axis
circle = circleToPolygon([10 0 3], 50);
[x, y, t] = revolutionSurface(circle, linspace(0, 4*pi/3, 50));
figure;
surf(x, y, t);
axis equal;
function varargout = circleToPolygon(circle, varargin)
%CIRCLETOPOLYGON Convert a circle into a series of points
%
% P = circleToPolygon(CIRC, N);
% Converts the circle CIRC into an array of (N+1)-by-2 of double,
% containing x and y positions of vertices.
% CIRC is given as [x0 y0 r], where x0 and y0 are coordinate of center,
% and r is the radius.
% The resulting polygon is closed (first and last vertices are the same).
%
% P = circleToPolygon(CIRCLE);
% uses a default value of N=64 vertices.
%
% Example
% circle = circleToPolygon([10 0 5], 16);
% figure;
% drawPolygon(circle);
%
% See also:
% circles2d, polygons2d, circleArcToPolyline, ellipseToPolygon
%
%
% ---------
% author : David Legland
% created the 06/04/2005.
% Copyright 2010 INRA - Cepia Software Platform.
%
% HISTORY
% 2007-04-20 return a closed polygon with N+1 vertices, use default N=64
% 2011-12-09 rename to 'circleToPolygon'
% determines number of points
N = 64;
if ~isempty(varargin)
N = varargin{1};
end
% create circle
t = linspace(0, 2*pi, N+1)';
x = circle(1) + circle(3) * cos(t);
y = circle(2) + circle(3) * sin(t);
if nargout == 1
varargout{1} = [x y];
elseif nargout == 2
varargout{1} = x;
varargout{2} = y;
end
|
github | carlassmith/exampleGLRT-master | multiWaitbar.m | .m | exampleGLRT-master/helperfunctions/trackHelpers/multiWaitbar.m | 26,088 | utf_8 | b93e10d7d04a7fba7d184cbf99dbe672 | function cancel = multiWaitbar( label, varargin )
%multiWaitbar: add, remove or update an entry on the multi waitbar
%
% multiWaitbar(LABEL,VALUE) adds a waitbar for the specified label, or
% if it already exists updates the value. LABEL must be a string and
% VALUE a number between zero and one or the string 'Close' to remove the
% entry Setting value equal to 0 or 'Reset' will cause the progress bar
% to reset and the time estimate to be re-initialised.
%
% multiWaitbar(LABEL,COMMAND,VALUE,...) passes one or more command/value
% pairs for changing the named waitbar entry. Possible commands include:
% 'Value' Set the value of the named waitbar entry. The
% corresponding value must be a number between 0 and 1.
% 'Increment' Increment the value of the named waitbar entry. The
% corresponding value must be a number between 0 and 1.
% 'Color' Change the color of the named waitbar entry. The
% value must be an RGB triple, e.g. [0.1 0.2 0.3], or a
% single-character color name, e.g. 'r', 'b', 'm'.
% 'Reset' Set the named waitbar entry back to zero and reset its
% timer. No value need be specified.
% 'CanCancel' [on|off] should a "cancel" button be shown for this bar
% (default 'off').
% 'CancelFcn' Function to call in the event that the user cancels.
% 'ResetCancel' Reset the "cancelled" flag for an entry (ie. if you
% decide not to cancel).
% 'Close' Remove the named waitbar entry.
% 'Busy' Puts this waitbar in "busy mode" where a small bar
% bounces back and forth. Return to normal progress display
% using the 'Reset' command.
%
% cancel = multiWaitbar(LABEL,VALUE) also returns whether the user has
% clicked the "cancel" button for this entry (true or false). Two
% mechanisms are provided for cancelling an entry if the 'CanCancel'
% setting is 'on'. The first is just to check the return argument and if
% it is true abort the task. The second is to set a 'CancelFcn' that is
% called when the user clicks the cancel button, much as is done for
% MATLAB's built-in WAITBAR. In either case, you can use the
% 'ResetCancel' command if you don't want to cancel afterall.
%
% multiWaitbar('CLOSEALL') closes the waitbar window.
%
% Example:
% multiWaitbar( 'CloseAll' );
% multiWaitbar( 'Task 1', 0 );
% multiWaitbar( 'Task 2', 0.5, 'Color', 'b' );
% multiWaitbar( 'Task 3', 'Busy');
% multiWaitbar( 'Task 1', 'Value', 0.1 );
% multiWaitbar( 'Task 2', 'Increment', 0.2 );
% multiWaitbar( 'Task 3', 'Reset' ); % Disables "busy" mode
% multiWaitbar( 'Task 3', 'Value', 0.3 );
% multiWaitbar( 'Task 2', 'Close' );
% multiWaitbar( 'Task 3', 'Close' );
% multiWaitbar( 'Task 1', 'Close' );
%
% Example:
% multiWaitbar( 'Task 1', 0, 'CancelFcn', @(a,b) disp( ['Cancel ',a] ) );
% for ii=1:100
% abort = multiWaitbar( 'Task 1', ii/100 );
% if abort
% % Here we would normally ask the user if they're sure
% break
% else
% pause( 1 )
% end
% end
% multiWaitbar( 'Task 1', 'Close' )
%
% Example:
% multiWaitbar( 'CloseAll' );
% multiWaitbar( 'Red...', 7/7, 'Color', [0.8 0.0 0.1] );
% multiWaitbar( 'Orange...', 6/7, 'Color', [1.0 0.4 0.0] );
% multiWaitbar( 'Yellow...', 5/7, 'Color', [0.9 0.8 0.2] );
% multiWaitbar( 'Green...', 4/7, 'Color', [0.2 0.9 0.3] );
% multiWaitbar( 'Blue...', 3/7, 'Color', [0.1 0.5 0.8] );
% multiWaitbar( 'Indigo...', 2/7, 'Color', [0.4 0.1 0.5] );
% multiWaitbar( 'Violet...', 1/7, 'Color', [0.8 0.4 0.9] );
%
% Thanks to Jesse Hopkins for suggesting the "busy" mode.
% Author: Ben Tordoff
% Copyright 2007-2013 The MathWorks Ltd
persistent figh;
cancel = false;
% Check basic inputs
error( nargchk( 1, inf, nargin ) ); %#ok<NCHKN> - kept for backwards compatibility
if ~ischar( label )
error( 'multiWaitbar:BadArg', 'LABEL must be the name of the progress entry (i.e. a string)' );
end
% Try to get hold of the figure
if isempty( figh ) || ~ishandle( figh )
figh = findall( 0, 'Type', 'figure', 'Tag', 'multiWaitbar:Figure' );
if isempty(figh)
figh = iCreateFig();
else
figh = handle( figh(1) );
end
end
% Check for close all and stop early
if any( strcmpi( label, {'CLOSEALL','CLOSE ALL'} ) )
iDeleteFigure(figh);
return;
end
% Make sure we're on-screen
if ~strcmpi( figh.Visible, 'on' )
figh.Visible = 'on';
end
% Get the list of entries and see if this one already exists
entries = getappdata( figh, 'ProgressEntries' );
if isempty(entries)
idx = [];
else
idx = find( strcmp( label, {entries.Label} ), 1, 'first' );
end
bgcol = getappdata( figh, 'DefaultProgressBarBackgroundColor' );
% If it doesn't exist, create it
needs_redraw = false;
entry_added = isempty(idx);
if entry_added
% Create a new entry
defbarcolor = getappdata( figh, 'DefaultProgressBarColor' );
entries = iAddEntry( figh, entries, label, 0, defbarcolor, bgcol );
idx = numel( entries );
end
% Check if the user requested a cancel
if nargout
cancel = entries(idx).Cancel;
end
% Parse the inputs. We shortcut the most common case as an efficiency
force_update = false;
if nargin==2 && isnumeric( varargin{1} )
entries(idx).LastValue = entries(idx).Value;
entries(idx).Value = max( 0, min( 1, varargin{1} ) );
entries(idx).Busy = false;
needs_update = true;
else
[params,values] = iParseInputs( varargin{:} );
needs_update = false;
for ii=1:numel( params )
switch upper( params{ii} )
case 'BUSY'
entries(idx).Busy = true;
needs_update = true;
case 'VALUE'
entries(idx).LastValue = entries(idx).Value;
entries(idx).Value = max( 0, min( 1, values{ii} ) );
entries(idx).Busy = false;
needs_update = true;
case {'INC','INCREMENT'}
entries(idx).LastValue = entries(idx).Value;
entries(idx).Value = max( 0, min( 1, entries(idx).Value + values{ii} ) );
entries(idx).Busy = false;
needs_update = true;
case {'COLOR','COLOUR'}
entries(idx).CData = iMakeColors( values{ii}, 16 );
needs_update = true;
force_update = true;
case {'CANCANCEL'}
if ~ischar( values{ii} ) || ~any( strcmpi( values{ii}, {'on','off'} ) )
error( 'multiWaitbar:BadString', 'Parameter ''CanCancel'' must be a ''on'' or ''off''.' );
end
entries(idx).CanCancel = strcmpi( values{ii}, 'on' );
needs_redraw = true;
case {'CANCELFCN'}
if ~isa( values{ii}, 'function_handle' )
error( 'multiWaitbar:BadFunction', 'Parameter ''CancelFcn'' must be a valid function handle.' );
end
entries(idx).CancelFcn = values{ii};
if ~entries(idx).CanCancel
entries(idx).CanCancel = true;
end
needs_redraw = true;
case {'CLOSE','DONE'}
if ~isempty(idx)
% Remove the selected entry
entries = iDeleteEntry( entries, idx );
end
if isempty( entries )
iDeleteFigure( figh );
% With the window closed, there's nothing else to do
return;
else
needs_redraw = true;
end
% We can't continue after clearing the entry, so jump out
break;
otherwise
error( 'multiWaitbar:BadArg', 'Unrecognised command: ''%s''', params{ii} );
end
end
end
% Now work out what to update/redraw
if needs_redraw
setappdata( figh, 'ProgressEntries', entries );
iRedraw( figh );
% NB: Redraw includes updating all bars, so never need to do both
elseif needs_update
[entries(idx),needs_redraw] = iUpdateEntry( entries(idx), force_update );
setappdata( figh, 'ProgressEntries', entries );
% NB: if anything was updated onscreen, "needs_redraw" is now true.
end
if entry_added || needs_redraw
% If the shape or size has changed, do a full redraw, including events
drawnow();
end
% If we have any "busy" entries, start the timer, otherwise stop it.
myTimer = getappdata( figh, 'BusyTimer' );
if any([entries.Busy])
if strcmpi(myTimer.Running,'off')
start(myTimer);
end
else
if strcmpi(myTimer.Running,'on')
stop(myTimer);
end
end
end % multiWaitbar
%-------------------------------------------------------------------------%
function [params, values] = iParseInputs( varargin )
% Parse the input arguments, extracting a list of commands and values
idx = 1;
params = {};
values = {};
if nargin==0
return;
end
if isnumeric( varargin{1} )
params{idx} = 'Value';
values{idx} = varargin{1};
idx = idx + 1;
end
while idx <= nargin
param = varargin{idx};
if ~ischar( param )
error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' );
end
params{end+1,1} = param; %#ok<AGROW>
values{end+1,1} = []; %#ok<AGROW>
switch upper( param )
case {'DONE','CLOSE'}
% No value needed, and stop
break;
case {'BUSY'}
% No value needed but parsing should continue
idx = idx + 1;
case {'RESET','ZERO','SHOW'}
% All equivalent to saying ('Value', 0)
params{end} = 'Value';
values{end} = 0;
idx = idx + 1;
otherwise
if idx==nargin
error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' );
end
values{end,1} = varargin{idx+1};
idx = idx + 2;
end
end
if isempty( params )
error( 'multiWaitbar:BadSyntax', 'Must specify a value or a command' );
end
end % iParseInputs
%-------------------------------------------------------------------------%
function fobj = iCreateFig()
% Create the progress bar group window
bgcol = get(0,'DefaultUIControlBackgroundColor');
f = figure( ...
'Name', 'Progress', ...
'Tag', 'multiWaitbar:Figure', ...
'Color', bgcol, ...
'MenuBar', 'none', ...
'ToolBar', 'none', ...
'HandleVisibility', 'off', ...
'IntegerHandle', 'off', ...
'Visible', 'off', ...
'NumberTitle', 'off' );
% Resize
fobj = handle( f );
fobj.Position(3:4) = [360 42];
setappdata( fobj, 'ProgressEntries', [] );
% Make sure we have the image
defbarcolor = [0.8 0.0 0.1];
barbgcol = uint8( 255*0.75*bgcol );
setappdata( fobj, 'DefaultProgressBarBackgroundColor', barbgcol );
setappdata( fobj, 'DefaultProgressBarColor', defbarcolor );
setappdata( fobj, 'DefaultProgressBarSize', [350 16] );
% Create the timer to use for "Busy" mode, being sure to delete any
% existing ones
delete( timerfind('Tag', 'MultiWaitbarTimer') );
myTimer = timer( ...
'TimerFcn', @(src,evt) iTimerFcn(f), ...
'Period', 0.02, ...
'ExecutionMode', 'FixedRate', ...
'Tag', 'MultiWaitbarTimer' );
setappdata( fobj, 'BusyTimer', myTimer );
% Setup the resize function after we've finished setting up the figure to
% avoid excessive redraws
fobj.ResizeFcn = @iRedraw;
fobj.CloseRequestFcn = @iCloseFigure;
end % iCreateFig
%-------------------------------------------------------------------------%
function cdata = iMakeColors( baseColor, height )
% Creates a shiny bar from a single base color
lightColor = [1 1 1];
badColorErrorID = 'multiWaitbar:BadColor';
badColorErrorMsg = 'Colors must be a three element vector [R G B] or a single character (''r'', ''g'' etc.)';
if ischar(baseColor)
switch upper(baseColor)
case 'K'
baseColor = [0.1 0.1 0.1];
case 'R'
baseColor = [0.8 0 0];
case 'G'
baseColor = [0 0.6 0];
case 'B'
baseColor = [0 0 0.8];
case 'C'
baseColor = [0.2 0.8 0.9];
case 'M'
baseColor = [0.6 0 0.6];
case 'Y'
baseColor = [0.9 0.8 0.2];
case 'W'
baseColor = [0.9 0.9 0.9];
otherwise
error( badColorErrorID, badColorErrorMsg );
end
else
if numel(baseColor) ~= 3
error( badColorErrorID, badColorErrorMsg );
end
if isa( baseColor, 'uint8' )
baseColor = double( baseColor ) / 255;
elseif isa( baseColor, 'double' )
if any(baseColor>1) || any(baseColor<0)
error( 'multiWaitbar:BadColorValue', 'Color values must be in the range 0 to 1 inclusive.' );
end
else
error( badColorErrorID, badColorErrorMsg );
end
end
% By this point we should have a double precision 3-element vector.
cols = repmat( baseColor, [height, 1] );
breaks = max( 1, round( height * [1 25 50 75 88 100] / 100 ) );
cols(breaks(1),:) = 0.6*baseColor;
cols(breaks(2),:) = lightColor - 0.4*(lightColor-baseColor);
cols(breaks(3),:) = baseColor;
cols(breaks(4),:) = min( baseColor*1.2, 1.0 );
cols(breaks(5),:) = min( baseColor*1.4, 0.95 ) + 0.05;
cols(breaks(6),:) = min( baseColor*1.6, 0.9 ) + 0.1;
y = 1:height;
cols(:,1) = max( 0, min( 1, interp1( breaks, cols(breaks,1), y, 'cubic' ) ) );
cols(:,2) = max( 0, min( 1, interp1( breaks, cols(breaks,2), y, 'cubic' ) ) );
cols(:,3) = max( 0, min( 1, interp1( breaks, cols(breaks,3), y, 'cubic' ) ) );
cdata = uint8( 255 * cat( 3, cols(:,1), cols(:,2), cols(:,3) ) );
end % iMakeColors
%-------------------------------------------------------------------------%
function cdata = iMakeBackground( baseColor, height )
% Creates a shaded background
if isa( baseColor, 'uint8' )
baseColor = double( baseColor ) / 255;
end
ratio = 1 - exp( -0.5-2*(1:height)/height )';
cdata = uint8( 255 * cat( 3, baseColor(1)*ratio, baseColor(2)*ratio, baseColor(3)*ratio ) );
end % iMakeBackground
%-------------------------------------------------------------------------%
function entries = iAddEntry( parent, entries, label, value, color, bgcolor )
% Add a new entry to the progress bar
% Create bar coloring
psize = getappdata( parent, 'DefaultProgressBarSize' );
cdata = iMakeColors( color, 16 );
% Create background image
barcdata = iMakeBackground( bgcolor, psize(2) );
% Work out the size in advance
labeltext = uicontrol( 'Style', 'Text', ...
'String', label, ...
'Parent', parent, ...
'HorizontalAlignment', 'Left' );
etatext = uicontrol( 'Style', 'Text', ...
'String', '', ...
'Parent', parent, ...
'HorizontalAlignment', 'Right' );
progresswidget = uicontrol( 'Style', 'Checkbox', ...
'String', '', ...
'Parent', parent, ...
'Position', [5 5 psize], ...
'CData', barcdata );
cancelwidget = uicontrol( 'Style', 'PushButton', ...
'String', '', ...
'FontWeight', 'Bold', ...
'Parent', parent, ...
'Position', [5 5 16 16], ...
'CData', iMakeCross( 8 ), ...
'Callback', @(src,evt) iCancelEntry( src, label ), ...
'Visible', 'off' );
mypanel = uipanel( 'Parent', parent, 'Units', 'Pixels' );
newentry = struct( ...
'Label', label, ...
'Value', value, ...
'LastValue', inf, ...
'Created', tic(), ...
'LabelText', labeltext, ...
'ETAText', etatext, ...
'ETAString', '', ...
'Progress', progresswidget, ...
'ProgressSize', psize, ...
'Panel', mypanel, ...
'BarCData', barcdata, ...
'CData', cdata, ...
'BackgroundCData', barcdata, ...
'CanCancel', false, ...
'CancelFcn', [], ...
'CancelButton', cancelwidget, ...
'Cancel', false, ...
'Busy', false );
if isempty( entries )
entries = newentry;
else
entries = [entries;newentry];
end
% Store in figure before the redraw
setappdata( parent, 'ProgressEntries', entries );
if strcmpi( get( parent, 'Visible' ), 'on' )
iRedraw( parent, [] );
else
set( parent, 'Visible', 'on' );
end
end % iAddEntry
%-------------------------------------------------------------------------%
function entries = iDeleteEntry( entries, idx )
delete( entries(idx).LabelText );
delete( entries(idx).ETAText );
delete( entries(idx).CancelButton );
delete( entries(idx).Progress );
delete( entries(idx).Panel );
entries(idx,:) = [];
end % iDeleteEntry
%-------------------------------------------------------------------------%
function entries = iCancelEntry( src, name )
figh = ancestor( src, 'figure' );
entries = getappdata( figh, 'ProgressEntries' );
if isempty(entries)
% The entries have been lost - nothing can be done.
return
end
idx = find( strcmp( name, {entries.Label} ), 1, 'first' );
% Set the cancel flag so that the user is told on next update
entries(idx).Cancel = true;
setappdata( figh, 'ProgressEntries', entries );
% If a user function is supplied, call it
if ~isempty( entries(idx).CancelFcn )
feval( entries(idx).CancelFcn, name, 'Cancelled' );
end
end % iCancelEntry
%-------------------------------------------------------------------------%
function [entry,updated] = iUpdateEntry( entry, force )
% Update one progress bar
% Deal with busy entries separately
if entry.Busy
entry = iUpdateBusyEntry(entry);
updated = true;
return;
end
% Some constants
marker_weight = 0.8;
% Check if the label needs updating
updated = force;
val = entry.Value;
lastval = entry.LastValue;
% Now update the bar
psize = entry.ProgressSize;
filled = max( 1, round( val*psize(1) ) );
lastfilled = max( 1, round( lastval*psize(1) ) );
% We do some careful checking so that we only redraw what we have to. This
% makes a small speed difference, but every little helps!
if force || (filled<lastfilled)
% Create the bar background
startIdx = 1;
bgim = entry.BackgroundCData(:,ones( 1, psize(1)-filled ),:);
barim = iMakeBarImage(entry.CData, startIdx, filled);
progresscdata = [barim,bgim];
% Add light/shadow around the markers
markers = round( (0.1:0.1:val)*psize(1) );
markers(markers<startIdx | markers>(filled-2)) = [];
highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)];
for ii=1:numel( markers )
progresscdata(:,markers(ii)+[-1,0],:) = highlight;
end
% Set the image into the checkbox
entry.BarCData = progresscdata;
set( entry.Progress, 'cdata', progresscdata );
updated = true;
elseif filled > lastfilled
% Just need to update the existing data
progresscdata = entry.BarCData;
startIdx = max(1,lastfilled-1);
% Repmat is the obvious way to fill the bar, but BSXFUN is often
% faster. Indexing is obscure but faster still.
progresscdata(:,startIdx:filled,:) = iMakeBarImage(entry.CData, startIdx, filled);
% Add light/shadow around the markers
markers = round( (0.1:0.1:val)*psize(1) );
markers(markers<startIdx | markers>(filled-2)) = [];
highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)];
for ii=1:numel( markers )
progresscdata(:,markers(ii)+[-1,0],:) = highlight;
end
entry.BarCData = progresscdata;
set( entry.Progress, 'CData', progresscdata );
updated = true;
end
% As an optimization, don't update any text if the bar didn't move
if ~updated
return
end
% Now work out the remaining time
minTime = 3; % secs
if val <= 0
% Zero value, so clear the eta
entry.Created = tic();
elapsedtime = 0;
etaString = '';
else
elapsedtime = round(toc( entry.Created )); % in seconds
% Only show the remaining time if we've had time to estimate
if elapsedtime < minTime
% Not enough time has passed since starting, so leave blank
etaString = '';
else
% Calculate a rough ETA
eta = elapsedtime * (1-val) / val;
etaString = iGetTimeString( eta );
end
end
if ~isequal( etaString, entry.ETAString )
set( entry.ETAText, 'String', etaString );
entry.ETAString = etaString;
updated = true;
end
% Update the label too
if elapsedtime > minTime
decval = round( val*100 );
if force || (decval ~= round( lastval*100 ))
labelstr = [entry.Label, sprintf( ' (%d%%)', decval )];
set( entry.LabelText, 'String', labelstr );
updated = true;
end
end
end % iUpdateEntry
function eta = iGetTimeString( remainingtime )
if remainingtime > 172800 % 2 days
eta = sprintf( '%d days', round(remainingtime/86400) );
else
if remainingtime > 7200 % 2 hours
eta = sprintf( '%d hours', round(remainingtime/3600) );
else
if remainingtime > 120 % 2 mins
eta = sprintf( '%d mins', round(remainingtime/60) );
else
% Seconds
remainingtime = round( remainingtime );
if remainingtime > 1
eta = sprintf( '%d secs', remainingtime );
elseif remainingtime == 1
eta = '1 sec';
else
eta = ''; % Nearly done (<1sec)
end
end
end
end
end % iGetTimeString
%-------------------------------------------------------------------------%
function entry = iUpdateBusyEntry( entry )
% Update a "busy" progress bar
% Make sure the widget is still OK
if ~ishandle(entry.Progress)
return
end
% Work out the new position. Since the bar is 0.1 long and needs to bounce,
% the position varies from 0 up to 0.9 then back down again. We achieve
% this with judicious use of "mod" with 1.8.
entry.Value = mod(entry.Value+0.01,1.8);
val = entry.Value;
if val>0.9
% Moving backwards
val = 1.8-val;
end
psize = entry.ProgressSize;
startIdx = max( 1, round( val*psize(1) ) );
endIdx = max( 1, round( (val+0.1)*psize(1) ) );
barLength = endIdx - startIdx + 1;
% Create the image
bgim = entry.BackgroundCData(:,ones( 1, psize(1) ),:);
barim = iMakeBarImage(entry.CData, 1, barLength);
bgim(:,startIdx:endIdx,:) = barim;
% Put it into the widget
entry.BarCData = bgim;
set( entry.Progress, 'CData', bgim );
end % iUpdateBusyEntry
%-------------------------------------------------------------------------%
function barim = iMakeBarImage(strip, startIdx, endIdx)
shadow1_weight = 0.4;
shadow2_weight = 0.7;
barLength = endIdx - startIdx + 1;
% Repmat is the obvious way to fill the bar, but BSXFUN is often
% faster. Indexing is obscure but faster still.
barim = strip(:,ones(1, barLength),:);
% Add highlight to the start of the bar
if startIdx <= 2 && barLength>=2
barim(:,1,:) = 255 - shadow1_weight*(255-strip);
barim(:,2,:) = 255 - shadow2_weight*(255-strip);
end
% Add shadow to the end of the bar
if endIdx>=4 && barLength>=2
barim(:,end,:) = shadow1_weight*strip;
barim(:,end-1,:) = shadow2_weight*strip;
end
end % iMakeBarImage
%-------------------------------------------------------------------------%
function iCloseFigure( fig, evt ) %#ok<INUSD>
% Closing the figure just makes it invisible
set( fig, 'Visible', 'off' );
end % iCloseFigure
%-------------------------------------------------------------------------%
function iDeleteFigure( fig )
% Actually destroy the figure
busyTimer = getappdata( fig, 'BusyTimer' );
stop( busyTimer );
delete( busyTimer );
delete( fig );
end % iDeleteFigure
%-------------------------------------------------------------------------%
function iRedraw( fig, evt ) %#ok<INUSD>
entries = getappdata( fig, 'ProgressEntries' );
fobj = handle( fig );
p = fobj.Position;
% p = get( fig, 'Position' );
border = 5;
textheight = 16;
barheight = 16;
panelheight = 10;
N = max( 1, numel( entries ) );
% Check the height is correct
heightperentry = textheight+barheight+panelheight;
requiredheight = 2*border + N*heightperentry - panelheight;
if ~isequal( p(4), requiredheight )
p(2) = p(2) + p(4) - requiredheight;
p(4) = requiredheight;
% In theory setting the position should re-trigger this callback, but
% in practice it doesn't, probably because we aren't calling "drawnow".
set( fig, 'Position', p )
end
ypos = p(4) - border;
width = p(3) - 2*border;
setappdata( fig, 'DefaultProgressBarSize', [width barheight] );
for ii=1:numel( entries )
set( entries(ii).LabelText, 'Position', [border ypos-textheight width*0.75 textheight] );
set( entries(ii).ETAText, 'Position', [border+width*0.75 ypos-textheight width*0.25 textheight] );
ypos = ypos - textheight;
if entries(ii).CanCancel
set( entries(ii).Progress, 'Position', [border ypos-barheight width-barheight+1 barheight] );
entries(ii).ProgressSize = [width-barheight barheight];
set( entries(ii).CancelButton, 'Visible', 'on', 'Position', [p(3)-border-barheight ypos-barheight barheight barheight] );
else
set( entries(ii).Progress, 'Position', [border ypos-barheight width+1 barheight] );
entries(ii).ProgressSize = [width barheight];
set( entries(ii).CancelButton, 'Visible', 'off' );
end
ypos = ypos - barheight;
set( entries(ii).Panel, 'Position', [-500 ypos-500-panelheight/2 p(3)+1000 500] );
ypos = ypos - panelheight;
entries(ii) = iUpdateEntry( entries(ii), true );
end
setappdata( fig, 'ProgressEntries', entries );
end % iRedraw
function cdata = iMakeCross( sz )
% Create a cross-shape image
cdata = nan( sz, sz );
for ii=1:sz
cdata(ii,ii) = 0;
cdata(sz-ii+1,ii) = 0;
end
for ii=2:sz
cdata(ii,ii-1) = 0;
cdata(ii-1,ii) = 0;
cdata(sz-ii+1,ii-1) = 0;
cdata(ii,sz-ii+2) = 0;
end
cdata = cat( 3, cdata, cdata, cdata );
end % iMakeCross
function iTimerFcn(fig)
% Timer callback for updating stuff every so often
entries = getappdata( fig, 'ProgressEntries' );
for ii=1:numel(entries)
if entries(ii).Busy
entries(ii) = iUpdateBusyEntry(entries(ii));
end
end
setappdata( fig, 'ProgressEntries', entries );
end % iTimerFcn
|
github | carlassmith/exampleGLRT-master | lapmember.m | .m | exampleGLRT-master/helperfunctions/trackHelpers/lapmember.m | 26,042 | utf_8 | 61ff74149cda5a1f98b332afcb7c34a1 | function varargout = lapmember(A,B,flag1,flag2)
%ISMEMBER True for set member.
% LIA = ISMEMBER(A,B) for arrays A and B returns an array of the same
% size as A containing true where the elements of A are in B and false
% otherwise.
%
% LIA = ISMEMBER(A,B,'rows') for matrices A and B with the same number
% of columns, returns a vector containing true where the rows of A are
% also rows of B and false otherwise.
%
% [LIA,LOCB] = ISMEMBER(A,B) also returns an array LOCB containing the
% lowest absolute index in B for each element in A which is a member of
% B and 0 if there is no such index.
%
% [LIA,LOCB] = ISMEMBER(A,B,'rows') also returns a vector LOCB containing
% the lowest absolute index in B for each row in A which is a member
% of B and 0 if there is no such index.
%
% The behavior of ISMEMBER has changed. This includes:
% - occurrence of indices in LOCB switched from highest to lowest
% - tighter restrictions on combinations of classes
%
% If this change in behavior has adversely affected your code, you may
% preserve the previous behavior with:
%
% [LIA,LOCB] = ISMEMBER(A,B,'legacy')
% [LIA,LOCB] = ISMEMBER(A,B,'rows','legacy')
%
% Examples:
%
% a = [9 9 8 8 7 7 7 6 6 6 5 5 4 4 2 1 1 1]
% b = [1 1 1 3 3 3 3 3 4 4 4 4 4 9 9 9]
%
% [lia1,locb1] = ismember(a,b)
% % returns
% lia1 = [1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1]
% locb1 = [14 14 0 0 0 0 0 0 0 0 0 0 9 9 0 1 1 1]
%
% [lia,locb] = ismember([1 NaN 2 3],[3 4 NaN 1])
% % NaNs compare as not equal, so this returns
% lia = [1 0 0 1], locb = [4 0 0 1]
%
% Class support for inputs A and B, where A and B must be of the same
% class unless stated otherwise:
% - logical, char, all numeric classes (may combine with double arrays)
% - cell arrays of strings (may combine with char arrays)
% -- 'rows' option is not supported for cell arrays
% - objects with methods SORT (SORTROWS for the 'rows' option), EQ and NE
% -- including heterogeneous arrays derived from the same root class
%
% See also UNIQUE, UNION, INTERSECT, SETDIFF, SETXOR, SORT, SORTROWS.
% Copyright 1984-2013 The MathWorks, Inc.
if nargin == 2
[varargout{1:max(1,nargout)}] = ismemberR2012a(A,B);
else
% acceptable combinations, with optional inputs denoted in []
% ismember(A,B, ['rows'], ['legacy'/'R2012a'])
nflagvals = 3;
flagvals = {'rows' 'legacy' 'R2012a'};
% When a flag is found, note the index into varargin where it was found
flaginds = zeros(1,nflagvals);
for i = 3:nargin
if i == 3
flag = flag1;
else
flag = flag2;
end
foundflag = strcmpi(flag,flagvals);
if ~any(foundflag)
if ischar(flag)
error(message('MATLAB:ISMEMBER:UnknownFlag',flag));
else
error(message('MATLAB:ISMEMBER:UnknownInput'));
end
end
% Only 1 occurrence of each allowed flag value
if flaginds(foundflag)
error(message('MATLAB:ISMEMBER:RepeatedFlag',flag));
end
flaginds(foundflag) = i;
end
% Only 1 of each of the paired flags
if flaginds(2) && flaginds(3)
error(message('MATLAB:ISMEMBER:BehaviorConflict'))
end
% 'legacy' and 'R2012a' flags must be trailing
if flaginds(2) && flaginds(2)~=nargin
error(message('MATLAB:ISMEMBER:LegacyTrailing'))
end
if flaginds(3) && flaginds(3)~=nargin
error(message('MATLAB:ISMEMBER:R2012aTrailing'))
end
if flaginds(3) % trailing 'R2012a' specified
[varargout{1:max(1,nargout)}] = ismemberR2012a(A,B,logical(flaginds(1)));
elseif flaginds(2) % trailing 'legacy' specified
[varargout{1:max(1,nargout)}] = ismemberlegacy(A,B,logical(flaginds(1)));
else % 'R2012a' (default behavior)
[varargout{1:max(1,nargout)}] = ismemberR2012a(A,B,logical(flaginds(1)));
end
end
end
function [tf,loc] = ismemberlegacy(a,s,isrows)
% 'legacy' flag implementation
if nargin == 3 && isrows
flag = 'rows';
else
flag = [];
end
numelA = numel(a);
numelS = numel(s);
nOut = nargout;
if ~(isa(a,'opaque') || isa(s,'opaque'))
if isempty(flag)
% Initialize types and sizes.
tf = false(size(a));
if nOut > 1
loc = zeros(size(a));
end
% Handle empty arrays and scalars.
if numelA == 0 || numelS <= 1
if (numelA == 0 || numelS == 0)
return
% Scalar A handled below.
% Scalar S: find which elements of A are equal to S.
elseif numelS == 1
tf = (a == s);
if nOut > 1
% Use DOUBLE to convert logical "1" index to double "1" index.
loc = double(tf);
end
return
end
else
% General handling.
% Use FIND method for very small sizes of the input vector to avoid SORT.
scalarcut = 5;
if numelA <= scalarcut
if nOut <= 1
for i=1:numelA
tf(i) = any(a(i)==s(:)); % ANY returns logical.
end
else
for i=1:numelA
found = find(a(i)==s(:)); % FIND returns indices for LOC.
if ~isempty(found)
tf(i) = 1;
loc(i) = found(end);
end
end
end
else
% Use method which sorts list, then performs binary search.
% Convert to double for quicker sorting, to full to work in C helper.
a = double(a);
if issparse(a)
a = full(a);
end
s = double(s);
if issparse(s)
s = full(s);
end
if (isreal(s))
% Find out whether list is presorted before sort
% If the list is short enough, SORT will be faster than ISSORTED
% If the list is longer, ISSORTED can potentially save time
checksortcut = 1000;
if numelS > checksortcut
sortedlist = issorted(s(:));
else
sortedlist = 0;
end
if nOut > 1
if ~sortedlist
[s,idx] = sort(s(:));
end
elseif ~sortedlist
s = sort(s(:));
end
else
sortedlist = 0;
[~,idx] = sort(real(s(:)));
s = s(idx);
end
% Two C-Helper Functions are used in the code below:
% ISMEMBC - S must be sorted - Returns logical vector indicating which
% elements of A occur in S
% ISMEMBC2 - S must be sorted - Returns a vector of the locations of
% the elements of A occurring in S. If multiple instances occur,
% the last occurrence is returned
% Check for NaN values - NaN values will be at the end of S,
% but may be anywhere in A.
nana = isnan(a(:));
if (any(nana) || isnan(s(numelS)))
% If NaNs detected, remove NaNs from the data before calling ISMEMBC.
ida = (nana == 0);
ids = (isnan(s(:)) == 0);
if nOut <= 1
ainfn = ismembc(a(ida),s(ids));
tf(ida) = ainfn;
else
loc1 = ismembc2(a(ida),s(ids));
tf(ida) = (loc1 > 0);
loc(ida) = loc1;
loc(~ida) = 0;
end
else
% No NaN values, call ISMEMBC directly.
if nOut <= 1
tf = ismembc(a,s);
else
loc = ismembc2(a,s);
tf = (loc > 0);
end
end
if nOut > 1 && ~sortedlist
% Re-reference loc to original list if it was unsorted
loc(tf) = idx(loc(tf));
end
end
end
else % 'rows' case
rowsA = size(a,1);
colsA = size(a,2);
rowsS = size(s,1);
colsS = size(s,2);
% Automatically pad strings with spaces
if ischar(a) && ischar(s),
if colsA > colsS
s = [s repmat(' ',rowsS,colsA-colsS)];
elseif colsA < colsS
a = [a repmat(' ',rowsA,colsS-colsA)];
end
elseif colsA ~= colsS && ~isempty(a) && ~isempty(s)
error(message('MATLAB:ISMEMBER:AandBColnumAgree'));
end
% Empty check for 'rows'.
if rowsA == 0 || rowsS == 0
if (isempty(a) || isempty(s))
tf = false(rowsA,1);
loc = zeros(rowsA,1);
return
end
end
% General handling for 'rows'.
% Duplicates within the sets are eliminated
if (rowsA == 1)
au = repmat(a,rowsS,1);
d = au(1:end,:)==s(1:end,:);
d = all(d,2);
tf = any(d);
if nOut > 1
if tf
loc = find(d, 1, 'last');
else
loc = 0;
end
end
return;
else
[au,~,an] = unique(a,'rows','legacy');
end
if nOut <= 1
su = unique(s,'rows','legacy');
else
[su,sm] = unique(s,'rows','legacy');
end
% Sort the unique elements of A and S, duplicate entries are adjacent
[c,ndx] = sortrows([au;su]);
% Find matching entries
d = c(1:end-1,:)==c(2:end,:); % d indicates matching entries in 2-D
d = find(all(d,2)); % Finds the index of matching entries
ndx1 = ndx(d); % NDX1 are locations of repeats in C
if nOut <= 1
tf = ismember(an,ndx1,'legacy'); % Find repeats among original list
else
szau = size(au,1);
[tf,loc] = ismember(an,ndx1,'legacy'); % Find loc by using given indices
newd = d(loc(tf)); % NEWD is D for non-unique A
where = sm(ndx(newd+1)-szau); % Index values of SU through UNIQUE
loc(tf) = where; % Return last occurrence of A within S
end
end
else
% Handle objects that cannot be converted to doubles
if isempty(flag)
% Handle empty arrays and scalars.
if numelA == 0 || numelS <= 1
if (numelA == 0 || numelS == 0)
tf = false(size(a));
loc = zeros(size(a));
return
% Scalar A handled below.
% Scalar S: find which elements of A are equal to S.
elseif numelS == 1
tf = (a == s);
if nOut > 1
% Use DOUBLE to convert logical "1" index to double "1" index.
loc = double(tf);
end
return
end
else
% General handling.
% Use FIND method for very small sizes of the input vector to avoid SORT.
scalarcut = 5;
if numelA <= scalarcut
tf = false(size(a));
loc = zeros(size(a));
if nOut <= 1
for i=1:numelA
tf(i) = any(a(i)==s); % ANY returns logical.
end
else
for i=1:numelA
found = find(a(i)==s); % FIND returns indices for LOC.
if ~isempty(found)
tf(i) = 1;
loc(i) = found(end);
end
end
end
else
% Duplicates within the sets are eliminated
[au,~,an] = unique(a(:),'legacy');
if nOut <= 1
su = unique(s(:),'legacy');
else
[su,sm] = unique(s(:),'legacy');
end
% Sort the unique elements of A and S, duplicate entries are adjacent
[c,ndx] = sort([au;su]);
% Find matching entries
d = c(1:end-1)==c(2:end); % d indicates matching entries in 2-D
d = find(d); % Finds the index of matching entries
ndx1 = ndx(d); % NDX1 are locations of repeats in C
if nOut <= 1
tf = ismember(an,ndx1,'legacy'); % Find repeats among original list
else
szau = size(au,1);
[tf,loc] = ismember(an,ndx1,'legacy'); % Find loc by using given indices
newd = d(loc(tf)); % NEWD is D for non-unique A
where = sm(ndx(newd+1)-szau); % Index values of SU through UNIQUE
loc(tf) = where; % Return last occurrence of A within S
end
end
tf = reshape(tf,size(a));
if nOut > 1
loc = reshape(loc,size(a));
end
end
else % 'rows' case
rowsA = size(a,1);
colsA = size(a,2);
rowsS = size(s,1);
colsS = size(s,2);
% Automatically pad strings with spaces
if ischar(a) && ischar(s),
if colsA > colsS
s = [s repmat(' ',rowsS,colsA-colsS)];
elseif colsA < colsS
a = [a repmat(' ',rowsA,colsS-colsA)];
end
elseif size(a,2)~=size(s,2) && ~isempty(a) && ~isempty(s)
error(message('MATLAB:ISMEMBER:AandBColnumAgree'));
end
% Empty check for 'rows'.
if rowsA == 0 || rowsS == 0
if (isempty(a) || isempty(s))
tf = false(rowsA,1);
loc = zeros(rowsA,1);
return
end
end
% Duplicates within the sets are eliminated
[au,~,an] = unique(a,'rows','legacy');
if nOut <= 1
su = unique(s,'rows','legacy');
else
[su,sm] = unique(s,'rows','legacy');
end
% Sort the unique elements of A and S, duplicate entries are adjacent
[c,ndx] = sortrows([au;su]);
% Find matching entries
d = c(1:end-1,:)==c(2:end,:); % d indicates matching entries in 2-D
d = find(all(d,2)); % Finds the index of matching entries
ndx1 = ndx(d); % NDX1 are locations of repeats in C
if nOut <= 1
tf = ismember(an,ndx1,'legacy'); % Find repeats among original list
else
szau = size(au,1);
[tf,loc] = ismember(an,ndx1,'legacy'); % Find loc by using given indices
newd = d(loc(tf)); % NEWD is D for non-unique A
where = sm(ndx(newd+1)-szau); % Index values of SU through UNIQUE
loc(tf) = where; % Return last occurrence of A within S
end
end
end
end
function [lia,locb] = ismemberR2012a(a,b,options)
% 'R2012a' flag implementation
% Error check flag
if nargin == 2
byrow = false;
else
byrow = options > 0;
end
classFlag = true;
% Check that one of A and B is double if A and B are non-homogeneous. Do a
% separate check if A is a heterogeneous object and only allow a B
% that is of the same root class.
if ~(isa(a,'handle.handle') || isa(b,'handle.handle'))
if ~strcmpi(class(a),class(b))
if isa(a,'matlab.mixin.Heterogeneous') && isa(b,'matlab.mixin.Heterogeneous')
rootClassA = meta.internal.findHeterogeneousRootClass(a);
if isempty(rootClassA) || ~isa(b,rootClassA.Name)
error(message('MATLAB:ISMEMBER:InvalidInputsDataType',class(a),class(b)));
end
elseif ~(strcmpi(class(a),'double') || strcmpi(class(b),'double'))
error(message('MATLAB:ISMEMBER:InvalidInputsDataType',class(a),class(b)));
end
classFlag = false;
end
end
numelA = numel(a);
if ~byrow
if ~(isa(a,'opaque') || isa(b,'opaque')) && (classFlag || numelA <= 5)
% Initialize types and sizes.
if nargout > 1
[lia,locb] = ismemberBuiltinTypes(a,b);
else
lia = ismemberBuiltinTypes(a,b);
end
else %Handle objects and allowed mixed data types
if nargout > 1
[lia,locb] = ismemberClassTypes(a,b);
else
lia = ismemberClassTypes(a,b);
end
end
else % 'rows' case
if ~(ismatrix(a) && ismatrix(b))
error(message('MATLAB:ISMEMBER:NotAMatrix'));
end
[rowsA,colsA] = size(a);
[rowsB,colsB] = size(b);
% Automatically pad strings with spaces
if ischar(a) && ischar(b),
b = [b repmat(' ',rowsB,colsA-colsB)];
a = [a repmat(' ',rowsA,colsB-colsA)];
elseif colsA ~= colsB
error(message('MATLAB:ISMEMBER:AandBColnumAgree'));
end
% Empty check for 'rows'.
if rowsA == 0 || rowsB == 0
lia = false(rowsA,1);
locb = zeros(rowsA,1);
return
end
% General handling for 'rows'.
% overhead removed by PKR, data is already sorted, yeah!
% % Duplicates within the sets are eliminated
% if (rowsA == 1)
% uA = repmat(a,rowsB,1);
% d = uA(1:end,:)==b(1:end,:);
% d = all(d,2);
% lia = any(d);
% if nargout > 1
% if lia
% locb = find(d, 1, 'first');
% else
% locb = 0;
% end
% end
% return;
% else
% [uA,~,icA] = unique(a,'rows','sorted');
% end
% if nargout <= 1
% uB = unique(b,'rows','sorted');
% else
% [uB,ib] = unique(b,'rows','sorted');
% end
% Sort the unique elements of A and B, duplicate entries are adjacent
%[sortuAuB,IndSortuAuB] = sortrows([uA;uB]);
% modified by PKR, don't need to carry over dummy variables, no changes
% here.
[sortuAuB,IndSortuAuB] = sortrows([a;b]);
icA = (1:size(a,1))';
% Find matching entries
d = sortuAuB(1:end-1,:)==sortuAuB(2:end,:); % d indicates matching entries
d = all(d,2); % Finds the index of matching entries
ndx1 = IndSortuAuB(d); % NDX1 are locations of repeats in C
if nargout <= 1
lia = ismemberBuiltinTypes(icA,ndx1); % Find repeats among original list
else
szuA = size(uA,1);
[lia,locb] = ismemberBuiltinTypes(icA,ndx1); % Find locb by using given indices
d = find(d);
newd = d(locb(lia)); % NEWD is D for non-unique A
where = ib(IndSortuAuB(newd+1)-szuA); % Index values of uB through UNIQUE
locb(lia) = where; % Return first or last occurrence of A within B
end
end
end
function [lia,locb] = ismemberBuiltinTypes(a,b)
% General handling.
% Use FIND method for very small sizes of the input vector to avoid SORT.
lia = false(size(a));
if nargout > 1
locb = zeros(size(a));
end
% Handle empty arrays and scalars.
numelA = numel(a);
numelB = numel(b);
if numelA == 0 || numelB <= 1
if (numelA == 0 || numelB == 0)
return
% Scalar A handled below.
% Scalar B: find which elements of A are equal to B.
elseif numelB == 1
lia = (a == b);
if nargout > 1
% Use DOUBLE to convert logical "1" index to double "1" index.
locb = double(lia);
end
return
end
end
lia = false(size(a));
if nargout > 1
locb = zeros(size(a));
end
scalarcut = 5;
numelA = numel(a);
numelB = numel(b);
if numelA <= scalarcut
if nargout <= 1
for i=1:numelA
lia(i) = any(a(i)==b(:)); % ANY returns logical.
end
else
for i=1:numelA
found = a(i)==b(:); % FIND returns indices for LOCB.
if any(found)
lia(i) = true;
found = find(found);
locb(i) = found(1);
end
end
end
else
% Use method which sorts list, then performs binary search.
% Convert to full to work in C helper.
if issparse(a)
a = full(a);
end
if issparse(b)
b = full(b);
end
if (isreal(b))
% Find out whether list is presorted before sort
% If the list is short enough, SORT will be faster than ISSORTED
% If the list is longer, ISSORTED can potentially save time
checksortcut = 1000;
if numelB > checksortcut
sortedlist = issorted(b(:));
else
sortedlist = 0;
end
if nargout > 1
if ~sortedlist
[b,idx] = sort(b(:));
end
elseif ~sortedlist
b = sort(b(:));
end
else
sortedlist = 0;
[~,idx] = sort(real(b(:)));
b = b(idx);
end
% C++ - Helper Function are used in the code below:
% ISMEMBERONEOUTPUT(A,B) - B must be sorted - Returns logical vector indicating which
% elements of A occur in B
% ISMEMBERLAST(A,B) - B must be sorted - Returns a vector of the locations of
% the elements of A occurring in B. If multiple instances occur,
% the last occurrence is returned (Not currently being used)
% ISMEMBERFIRST(A,B) - B must be sorted - Returns a vector of the
% locations of the elements of A occurring in B. If multiple
% instances occur, the first occurence is returned.
% Check for NaN values - NaN values will be at the end of B,
% but may be anywhere in A.
nana = isnan(a(:));
if builtin('isnumeric',a) && builtin('isnumeric',b) && strcmp(class(a),class(b))
if (any(nana) || isnan(b(numelB)))
% If NaNs detected, remove NaNs from the data
ida = ~nana;
idb = ~isnan(b(:));
if nargout <= 1
ainfn = builtin('_ismemberoneoutput',a(ida),b(idb));
lia(ida) = ainfn;
else
loc1 = builtin('_ismemberfirst',a(ida),b(idb));
lia(ida) = (loc1 > 0);
locb(ida) = loc1;
locb(~ida) = 0;
end
else
if nargout <= 1
lia = builtin('_ismemberoneoutput',a,b);
else
locb = builtin('_ismemberfirst',a,b);
lia = (locb > 0);
end
end
else %(a,b, are some other class like gpuArray, syb object)
if nargout <= 1
for i=1:numelA
lia(i) = any(a(i)==b(:)); % ANY returns logical.
end
else
for i=1:numelA
found = a(i)==b(:); % FIND returns indices for LOCB.
if any(found)
lia(i) = true;
found = find(found);
locb(i) = found(1);
end
end
end
end
if nargout > 1 && ~sortedlist
% Re-reference locb to original list if it was unsorted
locb(lia) = idx(locb(lia));
end
end
end
function [lia,locb] = ismemberClassTypes(a,b)
if issparse(a)
a = full(a);
end
if issparse(b)
b = full(b);
end
% Duplicates within the sets are eliminated
if isscalar(a) || isscalar(b)
ab = [a(:);b(:)];
sort(ab(1));
numa = numel(a);
lia = ab(1:numa)==ab(1+numa:end);
if ~any(lia)
lia = false(size(a));
locb = zeros(size(a));
return
end
if ~isscalar(b)
locb = find(lia);
locb = locb(1);
lia = any(lia);
else
locb = double(lia);
end
else
% Duplicates within the sets are eliminated
[uA,~,icA] = unique(a(:),'sorted');
if nargout <= 1
uB = unique(b(:),'sorted');
else
[uB,ib] = unique(b(:),'sorted');
end
% Sort the unique elements of A and B, duplicate entries are adjacent
[sortuAuB,IndSortuAuB] = sort([uA;uB]);
% Find matching entries
d = sortuAuB(1:end-1)==sortuAuB(2:end); % d indicates the indices matching entries
ndx1 = IndSortuAuB(d); % NDX1 are locations of repeats in C
if nargout <= 1
lia = ismemberBuiltinTypes(icA,ndx1); % Find repeats among original list
else
szuA = size(uA,1);
d = find(d);
[lia,locb] = ismemberBuiltinTypes(icA,ndx1);% Find locb by using given indices
newd = d(locb(lia)); % NEWD is D for non-unique A
where = ib(IndSortuAuB(newd+1)-szuA); % Index values of uB through UNIQUE
locb(lia) = where; % Return first or last occurrence of A within B
end
end
lia = reshape(lia,size(a));
if nargout > 1
locb = reshape(locb,size(a));
end
end |
github | carlassmith/exampleGLRT-master | transP.m | .m | exampleGLRT-master/helperfunctions/trackHelpers/transP.m | 7,905 | utf_8 | 3b8e285958fff26a629f85eef911fb28 |
function [ pTrans ] = transP(row,col,kon,koff,D,time,density,dist,probDim,LA1,LA2,rr,cc)
% function P supplies the transition probabilities as:
% P(1,1) s_{k-1}=0 s_k=0
% P(1,2) s_{k-1}=0 s_k=x_{k}
% P(2,1) s_{k-1}=x_{k-1} s_k=0
% P(2,2) s_{k-1}=x_{k-1} s_k=x_{k}
% Created by Carlas Smith June 2014 (UMASS/TU-DELFT)
% TODO: add two sided boudndary crossing probaility for out of focus probability!!
% Karlin, S. and Taylor H. M. (1975). A First Course in Stochastic Processes, 2nd ed., Academic
% Press.
% Jacod, J. and Protter P. (2004). Probability Essentials. 2nd edition. Springer. ISBN 3-540-
% 43871-8.
% P(|W_t| > b) = 4 \infsum_k (-1)^{k} phi((2k-1)b/sqrt(t)) assuming we at
% zero.
% function p = pwt(b,t)
% phi=@(x).5.*(1 + erf(x./sqrt(2)));
% k = 1:100*2*D*t;
% p = 4.*sum((-1).^(k).*phi((2.*k-1).*b./sqrt(2*D*t)));
% end
if nargin < 8
dist = 1;
end
if nargin < 9
probDim = 2;
end
if nargin < 7 || nargin < 7
LA1 = 0; LA2 = 0;
end
if nargin < 12 || isempty(rr) || isempty(cc)
cc = 1; rr = 1;
end
% true = transition probabilities calculated by Pat Cutler.
classic = false;
if row == 1 & col == 1
if nargin < 4 || isempty(time)
time = ones(size(LA2,1),1);
end
% s_{k-1}=0 s_k=0
% lr = sum(dist,2);
Drep = repmat(permute(D,[1 2]),[size(LA1,1) 1]);
timeRep = repmat(time,[1 probDim]);
lr = sum(dist./(2.*(2.*Drep.*timeRep+1.*(LA1.^2+LA2.^2))+eps)+0.5.*log(2.*pi.*(2.*Drep.*timeRep+1.*(LA1.^2+LA2.^2))+eps),2);
lr = (-log(1-density.*exp(-1.*(time).*koff).*koff)).*(lr>0); % minimize costs of lr matrix
% .*kon*exp(kon)
pTrans = lr;
if isscalar(cc)
pTrans = reshape(pTrans,[rr,cc])';
else
pTrans = sparse(rr,cc,pTrans)';
end
elseif row == 1 & col == 2
% s_{k-1}=0 s_k=x_k
if nargin < 4 || isempty(time)
time = ones(size(LA2,1),1);
end
if ~classic
Pb = ((time).*kon-log(kon));
% +(time).*koff-log(koff)-log(density)+
else
Pb = (-log(density)-log(kon)-(time).*log(1-kon));
end
birthCost = Pb;
birthBlock = birthCost; %lower left
birthBlock(birthBlock==0) = NaN;
pTrans = birthBlock;
pTrans = diag(pTrans);
if ~isscalar(cc)
pTrans = sparse(pTrans);
end
elseif row == 2 & col == 1
% s_{k-1}=x_{k-1} s_k=0
if nargin < 4 || isempty(time)
time = ones(size(LA1,1),1);
end
%P(T<=delta t) = 1- exp(-koff deltat)
if ~classic
Pd = (eps-real(-1.*(time).*koff+log(koff)));
% log(density)++(time).*kon-log(kon)
else
Pd = eps-(time).*log(1-kon);
end
deathCost = Pd ;
%generate upper right and lower left block
deathBlock = deathCost; %upper right
deathBlock(deathBlock==0) = NaN;
pTrans = deathBlock;
pTrans = diag(pTrans);
if ~isscalar(cc)
pTrans = sparse(pTrans);
end
elseif row == 2 & col == 2
% s_{k-1}=x_{k-1} s_k=x_{k}
% p(x_{k}-Ax_{k-1})=exp(-.5(x_{k}-Ax_{k-1})^2./(Ddeltat+crlbest^2))
% pxx = 1-Pd; % also multiply with gaussian (p(x_{k}-Ax_{k-1})) but we implement that as a convolution.
%P(T<=delta t) = 1- exp(-koff deltat)
if nargin < 4 || isempty(time)
time = ones(size(LA1,1),1);
end
Drep = repmat(permute(D,[1 2]),[size(LA1,1) 1]);
timeRep = repmat(time,[1 probDim]);
pv = sum(dist./(2.*(2.*Drep.*timeRep+1.*(LA1.^2+LA2.^2))+eps)+0.5.*log(2.*pi.*(2.*Drep.*timeRep+1.*(LA1.^2+LA2.^2))+eps),2);
if ~classic
PdPv = pv-log(1-exp(-1.*kon).*kon);
else
PdPv = pv-log(1-koff);
end
PdPv(PdPv == 0) = 1e-10;
PdPv(sqrt(sum(dist,2)) >3 | time > 3) = 1e6;
%%
PdPv(isinf(PdPv)) = 0;
if isscalar(cc)
pTrans = reshape(PdPv,[rr,cc]);
else
pTrans = sparse(rr,cc,PdPv);
end
end
% function [ pTrans ] = transP(row,col,kon,koff,D,time,density,dist,probDim,LA1,LA2,rr,cc)
%
% % function P supplies the transition probabilities as:
% % P(1,1) s_{k-1}=0 s_k=0
% % P(1,2) s_{k-1}=0 s_k=x_{k}
% % P(2,1) s_{k-1}=x_{k-1} s_k=0
% % P(2,2) s_{k-1}=x_{k-1} s_k=x_{k}
% % Created by Carlas Smith June 2014 (UMASS/TU-DELFT)
%
% % TODO: add two sided boudndary crossing probaility for out of focus probability!!
% % Karlin, S. and Taylor H. M. (1975). A First Course in Stochastic Processes, 2nd ed., Academic
% % Press.
% % Jacod, J. and Protter P. (2004). Probability Essentials. 2nd edition. Springer. ISBN 3-540-
% % 43871-8.
% % P(|W_t| > b) = 4 \infsum_k (-1)^{k} phi((2k-1)b/sqrt(t)) assuming we at
% % zero.
% % function p = pwt(b,t)
% % phi=@(x).5.*(1 + erf(x./sqrt(2)));
% % k = 1:100*2*D*t;
% % p = 4.*sum((-1).^(k).*phi((2.*k-1).*b./sqrt(2*D*t)));
% % end
%
% if nargin < 8
% dist = 1;
% end
% if nargin < 9
% probDim = 2;
% end
% if nargin < 7 || nargin < 7
% LA1 = 0; LA2 = 0;
% end
%
% if nargin < 12 || isempty(rr) || isempty(cc)
% cc = 1; rr = 1;
% end
% % true = transition probabilities calculated by Pat Cutler.
% classic = false;
%
% if row == 1 & col == 1
% if nargin < 4 || isempty(time)
% time = ones(size(LA2,1),1);
% end
% % s_{k-1}=0 s_k=0
% lr = sum(dist,2);
% lr = (-log(1-density.*exp((time).*koff).*koff.*kon*exp(kon))).*(lr>0); % minimize costs of lr matrix
% pTrans = lr;
% if isscalar(cc)
% pTrans = reshape(pTrans,[rr,cc])';
% else
% pTrans = sparse(rr,cc,pTrans)';
% end
% elseif row == 1 & col == 2
% % s_{k-1}=0 s_k=x_k
% if nargin < 4 || isempty(time)
% time = ones(size(LA2,1),1);
% end
% if ~classic
% Pb = (-log(density)+(time).*koff-log(koff)+kon-log(kon));
% else
% Pb = (-log(density)-log(kon)-(time).*log(1-kon));
% end
% birthCost = Pb;
% birthBlock = birthCost; %lower left
% birthBlock(birthBlock==0) = NaN;
% pTrans = birthBlock;
% pTrans = diag(pTrans);
% if ~isscalar(cc)
% pTrans = sparse(pTrans);
% end
% elseif row == 2 & col == 1
% % s_{k-1}=x_{k-1} s_k=0
% if nargin < 4 || isempty(time)
% time = ones(size(LA1,1),1);
% end
%
% %P(T<=delta t) = 1- exp(-koff deltat)
% if ~classic
% Pd = eps-real(log(density)+(time).*kon-log(kon)+koff-log(koff));
% else
% Pd = eps-(time).*log(1-kon);
% end
% deathCost = Pd ;
% %generate upper right and lower left block
% deathBlock = deathCost; %upper right
% deathBlock(deathBlock==0) = NaN;
% pTrans = deathBlock;
% pTrans = diag(pTrans);
% if ~isscalar(cc)
% pTrans = sparse(pTrans);
% end
% elseif row == 2 & col == 2
% % s_{k-1}=x_{k-1} s_k=x_{k}
% % p(x_{k}-Ax_{k-1})=exp(-.5(x_{k}-Ax_{k-1})^2./(Ddeltat+crlbest^2))
% % pxx = 1-Pd; % also multiply with gaussian (p(x_{k}-Ax_{k-1})) but we implement that as a convolution.
% %P(T<=delta t) = 1- exp(-koff deltat)
% if nargin < 4 || isempty(time)
% time = ones(size(LA1,1),1);
% end
%
% Drep = repmat(permute(D,[1 2]),[size(LA1,1) 1]);
% timeRep = repmat(time,[1 probDim]);
%
%
% pv = sum(dist./(2.*(2.*Drep.*timeRep+(LA1.^2+LA2.^2))+eps)+0.5.*log(2.*pi.*(2.*Drep.*timeRep+(LA1.^2+LA2.^2))+eps),2);
% if ~classic
% PdPv = pv -real(log(1-(eps-real(log(density)+(time).*kon-log(kon)+koff-log(koff)))));
% else
% PdPv = pv-log(1-koff);
% end
% PdPv(PdPv == 0) = 1e-10;
%
% PdPv(sum(dist,2) > 8) = 1e6;
% %%
% PdPv(isinf(PdPv)) = 0;
% if isscalar(cc)
% pTrans = reshape(PdPv,[rr,cc]);
% else
% pTrans = sparse(rr,cc,PdPv);
% end
% end
%
% end |
github | carlassmith/exampleGLRT-master | dipTrack.m | .m | exampleGLRT-master/helperfunctions/trackHelpers/HIVHelperfunctions/dipTrack.m | 20,864 | utf_8 | 6894bccb2ecddd85e657332e686dbde0 | function varargout = dipTrack(varargin)
% dipTrack dipimage tracking figure
%
% USAGE:
% h = dipTrack(options); %setup dipTrack figure
% h = dipTrack(fh); %setup listener for dipTrack figure
%
% INPUTS
% options: options structure. Use dipTrackSetOptions to set options.
% im - image (required)
% plotTracksOptions - inputs for plotTracksV1. Default plotTracksV1SetOptions
% HeadMarkersize - 1 by 2 vector indicating the marker size for track
% head. Default [5 3]
% headMarker - single character or vector of characters specifying
% the shape of the head marker. If single character then
% a single head marker shape is used. If vector of
% characters is the same length as the number of tracks
% specified in plotTracksOptions then each track is
% represented with a different character. Default 'o'
% npoints - number of tail points. Default 10.
% h - figure handle
% fh: figure handle for figure created using dipTrack
% OUTPUTS
% h: figure handle
%
% for track testing
% datacursormode toggle
%
% <a href="matlab:edit('dipTrackExample');">dipTrackExample</a>
%
% See also dipTrackSetOptions, dipTrackObj, plotTracksV1, plotTracksV1SetOptions
%
% Created by Pat Cutler January 2012 (UNM)
%PJC 6-18-12 added dipTrackTable
%PJC 7-11-12 updated to use plotTracksV1
%PJC 11-10-12 fixed bug for not using colorByValue option in plotTracks
%also added ability to change headMarker for all tracks
if nargin > 2
error('dipTrack:ToManyInputs','dipTrack: 0 to 2 inputs required');
end
switch nargin
case 0
options = dipTrackSetOptions;
case 1
if ishandle(varargin{1})
h = varargin{1};
udata = get(h,'userdata');
if isfield(udata,'dipTrackData')
%add back compatibility for dipTrack figures made with plotTracks
if ~isfield(udata.dipTrackData,'plotTracksOptions')
udata.dipTrackData.plotTracksOptions = plotTracksV1SetOptions;
udata.dipTrackData.plotTracksOptions.marker = '.';
udata.dipTrackData.plotTracksOptions.tracks = udata.dipTrackData.tracks;
if size(udata.dipTrackData.c,1) == size(udata.dipTrackData.plotTracksOptions.tracks,1)
udata.dipTrackData.plotTracksOptions.tracksVal = repmat((1:size(udata.dipTrackData.c,1))',[1 size(udata.dipTrackData.plotTracksOptions.tracks,2)]);
udata.dipTrackData.plotTracksOptions.minMaxVal = [min(udata.dipTrackData.plotTracksOptions.tracksVal(:)) max(udata.dipTrackData.plotTracksOptions.tracksVal(:))];
udata.dipTrackData.plotTracksOptions.cmap = udata.dipTrackData.c;
end
if iscell(udata.dipTrackData.trackNum)
trackNum = cell2mat(udata.dipTrackData.trackNum);
else
trackNum = udata.dipTrackData.trackNum;
end
udata.dipTrackData.plotTracksOptions.colorbar = 0;
udata.dipTrackData.plotTracksOptions.WindowKeyPressFcn = 0;
udata.dipTrackData.plotTracksOptions.view = [];
% udata.dipTrackData.plotTracksOptions.addShadow = 0;
udata.dipTrackData.plotTracksOptions.trackNum = trackNum;
udata.dipTrackData.plotTracksOptions.linewidth = udata.dipTrackData.linewidth(2);
udata.dipTrackData.plotTracksOptions.h = h;
udata.dipTrackData.plotTracksOptions.ha = findall(h,'type','axes');
udata.dipTrackData.headMarkersize = udata.dipTrackData.markersize;
udata.dipTrackData.trackToggle = 1;
%delete all prior tracks and localization markers
delete(findall(udata.dipTrackData.plotTracksOptions.ha,'tag','trackLine'));
delete(findall(udata.dipTrackData.plotTracksOptions.ha,'tag','dipTrackLocMarker'));
end
udata.dipTrackData.h = h;
addlistener(udata.dipTrackData.h,'UserData','PostSet',@curslice);
set(h,'userdata',udata);
set(h,'KeyPressFcn',@dipTrack);
return;
else
error('dipTrack:InputMustBeDipTrack','dipTrack: input figure must be initialized using dipTrack')
end
end
options = varargin{1};
case 2
%dipimage keypress call back
dipshow('DIP_callback','KeyPressFcn')
h = varargin{1};
udata = get(h,'UserData');
switch varargin{2}.Key
case {'t','T'} % initialize trackTable
% update_trackTable(h,udata);
case {'r','R'} % toggle track plotting
udata.dipTrackData.trackToggle = ~udata.dipTrackData.trackToggle;
update_tracks(udata);
set(h,'userdata',udata);
case {'d','D'}
plotTracksV1('initDataTip(gcf)');
end
return
end
%initialize dipData
dipTrackData.headMarkersize = options.headMarkersize;
dipTrackData.dipTrackObj = dipTrackObj(0);
dipTrackData.trackTableToggle = 0;
dipTrackData.trackToggle = 1;
dipTrackData.npoints = options.npoints;
%initilize figure
if isempty(options.h)
h = figure;
else
h = options.h;
end
dipTrackData.h = h;
%show image
if options.updateImage
if isempty(options.im)
warning('dipTrack:NoIm','dipTrack: options.im is empty initializing with newim(256,256,10)')
if ~isempty(options.plotTracksOptions.tracks)
sz=round(max(dip_image(options.plotTracksOptions.tracks)));
dipshow(h,newim([sz,sz,size(options.plotTracksOptions.tracks,2)]));
else
dipshow(h,newim([256,256,10]));
end
else
dipshow(h,options.im);
end
end
%set values specific to plotTracksOptions
for ii = 1:length(options.plotTracksOptions)
dipTrackData.plotTracksOptions(ii) = options.plotTracksOptions(ii);
dipTrackData.plotTracksOptions(ii).h = h;
dipTrackData.plotTracksOptions(ii).ha = findall(h,'type','axes');
dipTrackData.plotTracksOptions(ii).colorbar = 0;
% dipTrackData.plotTracksOptions(ii).WindowKeyPressFcn = 0;
dipTrackData.plotTracksOptions(ii).view = [];
% dipTrackData.plotTracksOptions(ii).addShadow = 0;
if strcmp(dipTrackData.plotTracksOptions(ii).marker,'none')
dipTrackData.plotTracksOptions(ii).marker = '.';
end
end
%add listener
dipTrackData.lh = addlistener(h,'UserData','PostSet',@curslice);
%add dipTrackData to userdata
udata = get(h,'userdata');
udata.dipTrackData = dipTrackData;
set(h,'userdata',udata);
%change KeyPressFcn
set(h,'KeyPressFcn',@dipTrack,'busyaction','cancel','interruptible','off');
%add listener
% addlistener(udata.dipTrackData.h,'UserData','PostSet',@curslice);
%initialize tracks
try
dipmapping(h,'slice',1);
dipmapping(h,'slice',0);
catch
error('Tracks are too coarse!')
end
% %add initialization menu
% if isempty(findall(h,'Tag','initializeMenu'))
% hm = findall(h,'Label','plotTracks','Tag','plotTracksMenu');
% uimenu(hm,'Label','initialize dipTrack','Tag','initializeMenu',...
% 'Callback',@dipTrackInitialize);
% end
% ht = findall(h,'type','uitoolbar');
% tags = get(get(ht,'children'),'tag');
% if ~any(strcmp('initDipTrackPushTool',tags))
% load(fullfile(matlabroot,'/toolbox/matlab/icons/','arrow.mat'),'arrowCData');
% hpt = uipushtool(ht,'cdata',arrowCData,'TooltipString','initialize dipTrack',...
% 'clickedcallback',@KeyPress,'userdata','d','tag','initDipTrackPushTool');
% end
%output figure handle
if nargout == 1
varargout{1} = h;
end
function dipTrackInitialize(h,~)
%initialize dipTrack
hf = get(get(h,'parent'),'parent');
dipTrack(hf);
function update_tracks(udata)
%update trajectories in dipTrack figure
if isempty(udata.slicing)
return;
end
% plotTracksOptions = udata.dipTrackData.plotTracksOptions;
hp = findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatch');
if isempty(hp)
plotTracksOptions = udata.dipTrackData.plotTracksOptions;
else
for ii = 1:length(hp)
plotTracksOptions(ii) = get(hp(ii),'userdata');
end
end
%delete all prior tracks and localization markers
delete(findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatch'));
delete(findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatchShadow'));
delete(findall(plotTracksOptions(1).ha,'tag','plotTrackPatchHighlight'));
delete(findall(plotTracksOptions(1).ha,'tag','dipTrackLocMarker'));
if udata.dipTrackData.trackToggle
if udata.dipTrackData.npoints > udata.maxslice+1
npoints = udata.maxslice+1;
else
npoints = udata.dipTrackData.npoints;
end
trange = udata.curslice+(1:-1:-npoints);
trange(trange<0) = [];
for ii = 1:length(plotTracksOptions)
plotTracksOptions(ii).trange = trange;
[h ha hp] = plotTracksV1(plotTracksOptions(ii));
if ~isempty(hp)
plotTracksOptions1 = get(hp,'userdata');
plotLocMarker(udata,plotTracksOptions1);
end
end
end
function plotLocMarker(udata,options)
%plot localization marker
tag = 'dipTrackLocMarker';
if isfield(udata.dipTrackData,'headMarker') && length(udata.dipTrackData.headMarker) == length(options.trackNum)
for ii = 1:length(options.trackNum)
if options.tracks(options.trackNum(ii),udata.curslice+1,1)
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(1),...
'markerfacecolor',[1 1 1],...
'markeredgecolor',[0 0 0])
if isfield(udata.dipTrackData,'headColor')
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(2),...
'markerfacecolor',udata.dipTrackData.headColor(ii,:),...
'markeredgecolor',[1 1 1])
else
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(2),...
'markerfacecolor',colorstretch(options.tracksVal(options.trackNum(ii),udata.curslice+1,1),options.minMaxVal,options.cmap),...
'markeredgecolor',[1 1 1])
end
end
end
else
if isfield(udata.dipTrackData,'headMarker') && ~isempty(udata.dipTrackData.headMarker)
options.marker = udata.dipTrackData.headMarker(1);
else
options.marker = 'o';
end
facevertexcdata = options.facevertexcdata;
% options.marker = 'o';
options.markersize = udata.dipTrackData.headMarkersize(1);
options.facevertexcdata = facevertexcdata*0.5;
options.markeredgecolor = [1 1 1];
options.trange = udata.curslice+1;
vert = options.vert(:,[1 2 end-1]);
face = options.face(:,[1 2]);
vertIdx = ismember(options.vert(:,end),options.trackNum) & ismember(options.vert(:,end-1),options.trange);
vert(~vertIdx,:) = NaN;
face(all(~ismember(face(:,1:2),find(vertIdx)),2),:) = NaN;
% face(~ismember(face(:,2),find(vertIdx)),:) = NaN;
if options.trange-1 == udata.maxslice
face = face(:,[2 2]);
else
face = face(:,[1 1]);
end
% if options.trange == 1
% face = face(:,[1 1]);
% else
% face = face(:,[2 2]);
% end
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
options.markersize = udata.dipTrackData.headMarkersize(2);
options.facevertexcdata = facevertexcdata;
if size(facevertexcdata,1) == 1
options.markeredgecolor = facevertexcdata;
else
options.markeredgecolor = 'flat';
end
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
end
function curslice(h,evnt)
%check updating of curslice field in userdata
%get userdata
if isobject(evnt)
udata = get(evnt.AffectedObject,'UserData');
else
udata = get(evnt,'NewValue');
end
% udata = get(evnt,'NewValue');
%get current slice
if isfield(udata,'curslice') && isfield(udata,'dipTrackData') &&...
udata.dipTrackData.dipTrackObj.slice ~= udata.curslice
udata.dipTrackData.dipTrackObj.slice = udata.curslice; %update slice property
update_tracks(udata); %update figure
% set(udata.dipTrackData.h,'userdata',udata)
end
function initDataTip(h)
% initialize specialized data tip
%
% h - figure handle
dcm_obj = datacursormode(h);
if isempty(get(dcm_obj,'updatefcn'))
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
disp('plotTracks: specialized data tip initialized')
end
function update_trackTable(h,udata)
%update trackTable
%populate fields for backcompatibility
if ~isfield(udata.dipTrackData,'ntrackTable')
udata.dipTrackData.ntrackTable = 5;
end
if ~isfield(udata.dipTrackData,'trackTableDeleteLast')
udata.dipTrackData.trackTableDeleteLast = 1;
end
if ~isfield(udata.dipTrackData,'trackTableShowSummary')
udata.dipTrackData.trackTableShowSummary = 1;
end
locs=dipgetcoords(h,1);
if udata.dipTrackData.trackTableDeleteLast
curFigs = get(findall(0,'tag','dipTrackTable'),'parent');
if iscell(curFigs)
curFigs = cell2mat(curFigs);
end
delete(curFigs)
end
%get track numbers
if iscell(udata.dipTrackData.trackNum)
trackNum = [];
for ii = 1:numel(udata.dipTrackData.trackNum)
trackNum = [trackNum;udata.dipTrackData.trackNum{ii}(:)];
end
else
if isempty(udata.dipTrackData.trackNum)
trackNum = 1:size(udata.dipTrackData.tracks,1);
end
end
%get tracks observed in the current frame
trackNum = trackNum(logical(udata.dipTrackData.tracks(trackNum,locs(3)+1,1)));
%sort tracks by distance from locs
dist = sum((repmat(reshape(locs(1:2),[1 1 2]),[length(trackNum) 1 1])-udata.dipTrackData.tracks(trackNum,locs(3)+1,:)).^2,3);
[val idx] = sort(dist);
trackNum = trackNum(idx);
%get track information
trackNum = trackNum(1:min(udata.dipTrackData.ntrackTable,length(trackNum)));
x = udata.dipTrackData.tracks(trackNum,locs(3)+1,1);
y = udata.dipTrackData.tracks(trackNum,locs(3)+1,2);
c = round(udata.dipTrackData.c(trackNum,:)*255);
% c = zeros(length(trackNum),3);
% obs = zeros(length(trackNum),3); %first observations,last observation, number of total observations
data = cell(length(trackNum),10);
for ii = 1:length(trackNum)
obsfirst = find(udata.dipTrackData.tracks(trackNum(ii),:,1),1,'first');
obslast = find(udata.dipTrackData.tracks(trackNum(ii),:,1),1,'last');
obsall = sum(logical(udata.dipTrackData.tracks(trackNum(ii),:,1)));
% data(ii,:) = {trackNum(ii) x(ii) y(ii) obsfirst obslast obsall false sprintf('%0.1g ',c(ii,:)) '' ''};
cii = sprintf('%s%i%s%i%s%i%s%i%s%i%s%i%s','<html><span style="background-color: rgb(',...
c(ii,1),',',c(ii,2),',',c(ii,3),');">(',...
c(ii,1),',',c(ii,2),',',c(ii,3),')</span></html>');
data(ii,:) = {trackNum(ii) x(ii) y(ii) obsfirst obslast obsall false cii '' ''};
end
cnames = {'track#' 'x' 'y' 'First obs' 'Last obs' '# obs','append' 'color' 'identifier' 'comments'};
cformat= {'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'logical' 'char' 'char' 'char'};
ceditable = logical([0 0 0 0 0 0 1 0 1 1]);
th = figure;
namestr = sprintf('%s%i%s%i%s%i','dipTrackTable(x-',locs(1),',y-',locs(2),',t-',locs(3),')');
t=uitable(th,'ColumnName', cnames,'ColumnFormat', cformat, 'Data', data,...
'columneditable', ceditable,'tag','dipTrackTable');
%update table
pos=get(t,'extent');
set(t, 'Position', pos );
udata1.dipTrackData.trackTableShowSummary = udata.dipTrackData.trackTableShowSummary;
set(th,'Position',pos+[10 75 0 0],'name',namestr,...
'DeleteFcn',@deleteTrackTable,'userdata',udata1);
set(h,'userdata',udata)
figure(h);
%insert code for closing fcn
%add export fcn. export trackTable to workspace and append
function deleteTrackTable(fh,evnt)
% deleteTrackTable delete track table and update trackTableSummary
%
% INPUTS
% fh: figure handle for trackTable
%
% Created by Pat Cutler June 2012 (UNM)
%get table data
dipTrackTableData = get(findall(fh,'tag','dipTrackTable'),'data');
%find data to append
if ~isempty(dipTrackTableData)
appendIdx = cell2mat(dipTrackTableData(:,7));
dipTrackTableData = dipTrackTableData(appendIdx,:);
%eliminate append column
dipTrackTableData(:,7) = [];
end
%update summary table
update_trackTableSummary(fh,dipTrackTableData)
function update_trackTableSummary(fh,dipTrackTableData)
% update_trackTableSummary update summary table
%
% INPUTS
% fh: figure handle for trackTable
% dipTrackTableData: table to append to summary table
%
% Created by Pat Cutler June 2012 (UNM)
%get current figure handle
curSummaryTable = findall(0,'tag','diptracktablesummary');
if ~isempty(curSummaryTable)
dipTrackTableData = [get(curSummaryTable,'data');dipTrackTableData];
else if evalin('base','exist(''dipTrackTableData'',''var'')')
dipTrackTableData = [evalin('base','dipTrackTableData');dipTrackTableData];
end
end
udata = get(fh,'userdata');
%make summary table
curfigs = get(curSummaryTable,'parent');
if iscell(curfigs)
curfigs = cell2mat(curfigs);
end
delete(curfigs)
if ~isempty(dipTrackTableData)
if udata.dipTrackData.trackTableShowSummary
cnames = {'track#' 'x' 'y' 'first obs' 'last obs' '# obs' 'color' 'identifier' 'comments' 'delete'};
cformat= {'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'char' 'char' 'char' 'logical'};
ceditable = logical([0 0 0 0 0 0 0 1 1 1]);
th = figure;
namestr = sprintf('%s%i%s%i%s%i','dipTrackTable(summary)');
t=uitable(th,'columnname', cnames,'columnformat', cformat, 'data', dipTrackTableData,...
'columneditable', ceditable,'tag','diptracktablesummary',...
'celleditcallback',@update_dipTrackTableSummary);
monpos = get(0,'monitorposition');
[val idx] = min(sum(monpos(:,1:2),2)); %find lower left monitor
pos=get(t,'extent');
if pos(4) > monpos(idx,4)-100
pos(4) = monpos(idx,4)-150;
end
if pos(3) > monpos(idx,3)-100
pos(3) = monpos(idx,3)-150;
end
pos1 = [monpos(idx,[3 4]) 0 0]+[-pos([3 4])-75 pos([3 4])];
set(t, 'position', pos );
set(th,'position',pos1,'userdata',udata,'name',namestr);
end
end
assignin('base','dipTrackTableData',dipTrackTableData)
function update_dipTrackTableSummary(t,evnt)
if evnt.Indices(2) == 10
button = questdlg(sprintf('%s%i%s','Do you want to delete row',evnt.Indices(1),'?'),...
'dipTrackTable(summary)','YES','NO','YES');
switch button
case 'YES'
th = get(t,'parent');
% dipTrackTableData = evalin('base','dipTrackTableData');
curSummaryTable = findall(0,'tag','diptracktablesummary');
dipTrackTableData = get(curSummaryTable,'data');
dipTrackTableData(evnt.Indices(1),:) = [];
assignin('base','dipTrackTableData',dipTrackTableData);
set(curSummaryTable,'data',dipTrackTableData);
% update_trackTableSummary(th,[]);
return
case 'NO'
return
end
end
|
github | carlassmith/exampleGLRT-master | plotTracksV1.m | .m | exampleGLRT-master/helperfunctions/trackHelpers/HIVHelperfunctions/plotTracksV1.m | 32,380 | utf_8 | cf792a04c86a270fc04dc42f71113870 | function [h ha hp] = plotTracksV1(options)
% PLOTTRACKSV1 plot tracks using specified options
%
% h = plotTracksV1(options)
%
% INPUTS
% options - options structure with input options. See
% plotTracksSetOptions for more details.
% OUTPUTS
% h - figure handle
% ha - axes handle
% hp - patch handle
%
% Note:
% - hotkeys
% <r> reset figure
% <h> toggle syncHsiLocalizeQDFigBrowse
% - to highlight specific tracks without data tip use the following
% call: plotTracks('highlightTrack(gcf,[29 58;2 2],[],''o'',''none'',0,[],0)')
% INPUTS: for subfunction highlightTrackLines
% plotTracks subfunction for highlighting indicated track lines
% highlightTrackLines(h,trackNum,linewidth,marker,scatterMarker,...
% makeOthersTransparent,linecolor,markeredgecolorgray)
% h - figure handle
% trackNum - 2 by N array with line numbers to highlight in the first row
% and plotInstance in the secong row. If only 1 by N then
% plotInstance 1 is assumed
% linewidth - linewidth for highlighted track. Default 4
% marker - marker style for highlighted track. Default 'o'
% scatterMarker - marker scatter plot.
% makeOthersTransparent - binary for graying out other trajectories. Default 1
% markeredgecolorgray - binary for making line marker edge color gray(1) or same color as
% track(0). Default 1
%
% See also plotTracksV1SetOptions, SPT.plotTracks
%
% Created by Pat Cutler July 2012 (UNM)
%%
% options = plotTracksSetOptions;
% options.tracks = tracks;
% options.tracksVal = tracksWv;
% options.t = 1;
%%
% highlight tracks if input is str
if ischar(options)
try
eval(options);
return
catch err
getReport(err)
error('plotTracks:ImproperInput','plotTracks: character input is not correct')
end
% if strfind(options,'highlightTracks')
% h = eval(options);
% return;
% else if strfind(options,'initDataTip')
% eval(options);
% return;
% else if strfind(options,'initDataTip')
% eval(options,'resetTracks')
% else
% error('plotTracks:ImproperInput','plotTracks: character input is not correct')
% end
% end
% end
end
%check inputs
if isempty(options.tracks)
error('plotTracks:EmptyTracks','plotTracks: tracks field of options cannot not be empty')
end
% make figure if not indicated in input options
if isempty(options.h) && isempty(options.ha)
h = figure; %make figure
else
if ~isempty(options.ha)
h = get(options.ha,'parent');
else
h = options.h; %get figure handle
end
end
%set key press function
% if options.WindowKeyPressFcn
% set(h,'WindowKeyPressFcn',@KeyPress);
% end
%setup axes
if isempty(options.ha)
ha = findall(allchild(h),'type','axes'); %get axis handle
if ~isempty(findall(ha,'tag','Colorbar'))
ha = ha(ha ~= findall(ha,'tag','Colorbar'));
end
if isempty(ha)
ha = axes('parent',h);
end
ha = ha(1);
else
ha = options.ha;
end
options.ha = ha;
options.h = h;
if ~isempty(options.xlim) && ~isempty(options.ylim)
set(ha,'plotboxaspectratio',[diff([options.xlim;options.ylim]')+1 max(diff([options.xlim;options.ylim]')+1)]) %set plotting aspect ratio
end
options = updateOptions(options);
[vert face] = setVertFace(options);
%make patch object
hp = makePatch(face,vert,'plotTrackPatch',options);
% create colorbar
if options.colorbar && ~isempty(options.minMaxVal) && options.minMaxVal(1)~=options.minMaxVal(2)
colormap(options.h,options.cmap) %define colormap
hcb = colorbar('peer',ha); %make colorbar
set(get(hcb,'title'),'string',options.valueName) %set colorbar title
set(findall(hcb,'tag','TMW_COLORBAR'),'ydata',options.minMaxVal) %set range for colorbar values
set(hcb,'ylim',options.minMaxVal) %set range for colorbar figure
end
if ~isempty(options.view)
view(options.ha,options.view)
end
resetAxes(options);
%setup data tip
dcm_obj = datacursormode(h);
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
%add toolbar
% if options.WindowKeyPressFcn && isempty(findall(h,'userdata','plotTracksToolbar'))
% addToolBar(h)
% end
% addToolBar(h)
% if isempty(findall(h,'tag','plotTracksMenu'))
% addMenu(h)
% end
%add shadow on xy plane
hp = makeShadow(hp,options);
function resetAxes(options)
%reset data axes
%only change renderer and axis if not dipimage figure
drawnow
udataFig = get(options.h,'userdata');
if ~isfield(udataFig,'state')
set(options.h,'renderer','zbuffer')
axis(options.ha,'ij')
end
% if ~isempty(options.view)
% view(options.ha,options.view)
% end
tightcheck = 0;
if ~isempty(options.xlim)
xlim(options.ha,options.xlim);
tightcheck = tightcheck+1;
end
if ~isempty(options.ylim)
ylim(options.ha,options.ylim);
tightcheck = tightcheck+1;
end
if isfield(options,'zlim') && ~isempty(options.zlim)
zlim(options.ha,options.zlim);
tightcheck = tightcheck+1;
end
if tightcheck ~= 3 && ~isfield(udataFig,'state')
axis(options.ha,'tight')
end
xdiff = diff(get(options.ha,'xlim'));
ydiff = diff(get(options.ha,'ylim'));
zdiff = diff(get(options.ha,'zlim'));
if isfield(options,'DataAspectRatio')
set(options.ha,'DataAspectRatio',options.DataAspectRatio)
else
set(options.ha,'DataAspectRatio',[1 1 zdiff/max([xdiff ydiff])])
end
% drawnow
function [vert face] = setVertFace(options)
% find vertices with specified trackNum and in specified trange
if isfield(options,'zPlotFlag') && options.zPlotFlag
vert = options.vert(:,[1 2 3]);
else
vert = options.vert(:,[1 2 end-1]);
vert(:,3) = (vert(:,3)-1)*options.t;
end
face = options.face(:,1:2);
vertIdx = ismember(options.vert(:,end),options.trackNum) & ismember(options.vert(:,end-1),options.trange);
% vert(:,3) = (vert(:,3)-1)*options.t;
vert(~vertIdx,:) = NaN;
face(any(~ismember(options.face(:,1:2),find(vertIdx)),2),:) = NaN;
function hp = makeShadow(hp,options)
%add shadow on xy plane
if nargin == 1
options = get(hp,'userdata');
end
if options.addShadow && ~isempty(hp)
shadOptions = options;
[vert face] = setVertFace(shadOptions);
shadOptions.addShadow = 0;
% shadOptions.tagAppendix = 'Shadow';
shadOptions.shadowParent = hp;
% if ~isempty(options.trange)
% shadOptions.trange = min(options.trange);
% else
% shadOptions.trange = 0;
% end
shadOptions.colorByValue = 0;
shadOptions.color = [.75 .75 .75];
% shadOptions.face = options.face;
shadOptions.markersize = options.markersize*options.addShadow;
shadOptions.linewidth = options.linewidth*options.addShadow;
% shadOptions.vert(:,shadOptions.ndims+1) = shadOptions.trange;
shadOptions = updateOptions(shadOptions);
% vert(:,end) = shadOptions.trange;
% vert(:,end) = min(get(shadOptions.ha,'zlim'))-0.5;
zdata = get(findall(shadOptions.h,'tag','plotTrackPatch'),'zdata');
if iscell(zdata)
zdata = cell2mat(zdata');
end
vert(:,end) = min(min(zdata))-shadOptions.t*0.5;
%make patch object
makePatch(face,vert,'plotTrackPatchShadow',shadOptions);
% hp(2) = plotTracksV1(shadOptions);
%repostion shadows z position
allShadows = findall(shadOptions.h,'tag','plotTrackPatchShadow');
faces = get(findall(shadOptions.h,'tag','plotTrackPatch'),'faces');
zdata = get(findall(shadOptions.h,'tag','plotTrackPatch'),'zdata');
if iscell(zdata)
zdata = cell2mat(zdata')';
faces = cell2mat(faces);
else
zdata = zdata';
end
for ii = 1:length(allShadows)
udata = get(allShadows(ii),'userdata');
[vert face] = setVertFace(udata);
if any(any(~isnan(faces)))
vert(:,end) = min(zdata(~isnan(faces)))-udata.t*1.5;
makePatch(face,vert,'plotTrackPatchShadow',udata,allShadows(ii));
end
end
end
function options = updateOptions(options)
%update options for vertices, faces etc.
%get track numbers if not specified
if isempty(options.trackNum)
options.trackNum = 1:size(options.tracks,1);
end
options.trackNum = options.trackNum(:)';
%get time range if not specified
if isempty(options.trange)
options.trange = 1:size(options.tracks,2);
end
options.trange = options.trange(:)';
%compile vertices and faces for all tracks
if ~isfield(options,'updateOptions') || options.updateOptions
options.ndims = size(options.tracks,3);
%vertices for patch [positions t trackIdx]
options.vert = zeros(sum(sum(logical(options.tracks(:,:,1)))),options.ndims+2);
%faces for patch [vert1 vert2 trackIdx]
options.face = zeros(size(options.vert,1)-size(options.tracks,1),3);
% %index for track that vertex belongs to
% options.vertTrackIdx = zeros(size(options.vert,1),1);
% %index for track that vertex belongs to
% options.vertFaceIdx = zeros(size(options.face,1),1);
if ~isempty(options.tracksVal)
options.val = zeros(size(options.vert,1),1);
else
options.val = [];
end
count = 1;
count1 = 0;
for ii = 1:size(options.tracks,1)
nObsTrack = sum(logical(options.tracks(ii,:,1)));
vertIdx = count+(0:nObsTrack-1);
if nObsTrack
if nObsTrack > 1
options.vert(count+(0:nObsTrack-1),:) = [squeeze(options.tracks(ii,logical(options.tracks(ii,:,1)),:)) find(logical(options.tracks(ii,:,1)))' repmat(ii,[nObsTrack 1])];
else
options.vert(count+(0:nObsTrack-1),:) = [reshape(options.tracks(ii,logical(options.tracks(ii,:,1)),:),[1 options.ndims]) find(logical(options.tracks(ii,:,1)))' repmat(ii,[nObsTrack 1])];
% options.vert(count+(0:nObsTrack-1),end) = repmat(ii,[nObsTrack 1]);
end
options.face((count1+(1:nObsTrack-1)),:) = [vertIdx(1:end-1)' vertIdx(2:end)' repmat(ii,[nObsTrack-1 1])];
% options.vertFaceIdx(count+(1:nObsTrack-1)) = repmat(ii,[nObsTrack-1 1]);
if ~isempty(options.tracksVal)
options.val(count+(0:nObsTrack-1)) = squeeze(options.tracksVal(ii,logical(options.tracks(ii,:,1)))) ;
end
count = count+nObsTrack;
count1 = count1+nObsTrack-1;
end
end
end
%get track coloration
if options.colorByValue
if ~isfield(options,'updateOptions') || options.updateOptions
if ~isempty(options.val) && any(options.val ~= 1)
% get color information for plotting
if isempty(options.minMaxVal)
options.minMaxVal = [min(options.val) max(options.val)];
end
options.facevertexcdata = colorstretch(options.val,options.minMaxVal,options.cmap);
if strcmp(options.linestyle,'-')
options.edgecolor = 'interp';
else
options.edgecolor = 'flat';
end
options.markerfacecolor = 'flat';
options.markeredgecolor = 'flat';
else
options.facevertexcdata = options.color;
options.edgecolor = options.color;
options.markerfacecolor = options.color;
options.markeredgecolor = options.color;
end
end
else
options.facevertexcdata = options.color;
options.edgecolor = options.color;
options.markerfacecolor = options.color;
options.markeredgecolor = options.color;
end
options.updateOptions = 0;
function KeyPress(h,evnt)
% scroll feature
%variable inputs
if isempty(evnt)
key = get(h,'userdata');
else
key = evnt.Key;
end
% if strcmp(get(get(h,'parent'),'userdata'),'plotTracksToolbar') || strcmp(get(get(h,'parent'),'tag'),'plotTracksMenu')
% hf = get(get(h,'parent'),'parent');
% else
% hf = h;
% end
hf = ancestor(h,'figure');
% get userdata
switch key
case 'r'
resetTracks(hf);
case 'h'
syncSPTHSIplotFitResultsBrowser(hf);
case 'd'
initDataTip(hf);
case 's'
updatePlotTrackOptions(hf);
case 'e'
updateDipTrackOptions(hf);
end
function addMenu(h)
%add plotTrack menu to figure
hm = uimenu(h,'Label','plotTracks','Tag','plotTracksMenu');
uimenu(hm,'Label','reset tracks','Tag','resetMenu',...
'Callback',@KeyPress,'userdata','r');
uimenu(hm,'Label','toggle datacursormode','Tag','dataTipMenu',...
'Callback',@KeyPress,'userdata','d');
uimenu(hm,'Label','BrowseFitResults','Tag','SPTHSIplotFitResultsBrowserToggleMenu',...
'Callback',@KeyPress,'userdata','h');
uimenu(hm,'Label','set plotTrackOptions','Tag','plotTracksOptionsMenu',...
'Callback',@KeyPress,'userdata','s');
uimenu(hm,'Label','set dipTrackOptions','Tag','plotTracksOptionsMenu',...
'Callback',@KeyPress,'userdata','e');
function addToolBar(h)
% add plotTracks toolbar to figure
% ht = uitoolbar(h);
set(h,'toolbar','figure')
ht = findall(h,'type','uitoolbar');
tags = get(get(ht,'children'),'tag');
% set(ht,'userdata','plotTracksToolbar')
if ~any(strcmp('SPTHSI:FitResultsBrowser',tags))
load('cubeIcon','cdata');
htt = uitoggletool(ht,'separator','on','cdata',cdata,'TooltipString','view box fitting in SPTHSI:FitResultsBrowser',...
'clickedcallback',@KeyPress,'userdata','h','tag','SPTHSI:FitResultsBrowser');
end
if ~any(strcmp('resetPushTool',tags))
load('colorlinesIcon','cdata');
hpt = uipushtool(ht,'cdata',cdata,'TooltipString','reset tracks to original state',...
'clickedcallback',@KeyPress,'userdata','r','tag','resetPushTool');
end
if ~any(strcmp('initDataTipPushTool',tags))
load('colorlinesboxIcon','cdata');
hpt = uipushtool(ht,'cdata',cdata,'TooltipString','initialize specialized data tip',...
'clickedcallback',@KeyPress,'userdata','d','tag','initDataTipPushTool');
end
function hp = makePatch(face,vert,tag,options,hp)
%make Patch object using options
% if all(isnan(vert))
% hp = [];
% return;
% end
if isfield(options,'tagAppendix')
tag = [tag options.tagAppendix];
end
if nargin == 5
options = get(hp,'userdata');
highlightTracksOriginal = options.highlightTracks;
options.highlightTracks = 0;
set(hp,'userdata',options);
% set(hp,'facevertexcdata', options.facevertexcdata, ...
% 'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
% 'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
% 'linewidth',options.linewidth,'linestyle',options.linestyle,...
% 'markeredgecolor',options.markeredgecolor);
set(hp,'faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor);
options.highlightTracks = highlightTracksOriginal;
set(hp,'userdata',options);
else
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
end
if isfield(options,'displayName')
set(hp,'displayname',options.displayName)
end
function hpNew = highlightTracks(hp,trackNum,linewidth,markersize,makeOthersTransparent,...
linecolor,markeredgecolorgray,marker)
% highlight indicated track lines
%
% INPUTS
% hp - patch handle
% trackNum - vector with length N containing track numbers to highlight.
% linewidth - linewidth for highlighted track. Default 4
% markersize - marker size for highlighted track.
% makeOthersTransparent - binary for graying out other trajectories. Default 1
% linecolor - color for highligthed tracsk 1 by 3 vector for rgb
% markeredgecolorgray - binary for making line marker edge color gray(1) or same color as
% track(0). Default 1
%check inputs
if ~exist('hp','var') || isempty(hp)
return;
end
if ~exist('trackNum','var') ||isempty(trackNum)
return;
end
if ~exist('linewidth','var') ||isempty(linewidth)
linewidth = 4;
end
if ~exist('markersize','var') ||isempty(markersize)
markersize = 6;
end
if ~exist('makeOthersTransparent','var') ||isempty(makeOthersTransparent)
makeOthersTransparent = 1;
end
if ~exist('linecolor','var') ||isempty(linecolor)
linecolor = [];
end
if ~exist('markeredgecolorgray','var') ||isempty(markeredgecolorgray)
markeredgecolorgray = 1;
end
if ~exist('marker','var') ||isempty(marker)
marker = 'o';
end
%find patch handle
if ~ishandle(hp)
hptmp = findall(0,'tag','plotTrackPatch');
hpIdx = round(hptmp - double(hp)) == 0;
hp = hptmp(hpIdx);
end
if isempty(hp)
return;
end
%find all existing highlighted tracks
hpHighlightOld = findall(get(hp,'parent'),'tag','plotTrackPatchHighlight');
trackNumOld = [];
if ~isempty(hpHighlightOld)
for ii = 1:length(hpHighlightOld)
udataOld = get(hpHighlightOld(ii),'userdata');
if isfield(udataOld,'trackii')
trackNumOld = [trackNumOld; udataOld.trackii];
end
end
end
delete(hpHighlightOld)
%get color information from figure
udata = get(hp,'userdata');
%find vertices for specifie
trackNum = unique([trackNumOld trackNum(:)']);
if makeOthersTransparent
%change transparency of patch
set(hp,'facevertexcdata', udata.facevertexcdata*.3+.7,...
'linewidth',udata.linewidth*.75,'markersize',udata.markersize*.75);
end
%get marker edge color
if markeredgecolorgray
if length(trackNum) > 1
markeredgeC = repmat((.4:.4/(length(trackNum)-1):.8)',[1 3]);
else
markeredgeC = [.4 .4 .4];
end
else if ~isempty(linecolor)
markeredgeC = linecolor;
else
markeredgeC = [];
end
end
%loop through tracks
if ~isempty(linecolor)
udata.facevertexcdata = linecolor;
udata.edgecolor = linecolor;
end
udata.markersize = markersize;
udata.linewidth = linewidth;
udata.marker = marker;
if size(markeredgeC,1) == length(trackNum)
for ii = 1:length(trackNum)
udata.trackii = trackNum(ii);
% find vertices with specified trackNum and in specified trange
% vert = udata.vert(:,[1 2 end-1]);
% face = udata.face(:,1:2);
% vertIdx = udata.vert(:,end) == udata.trackii & ismember(udata.vert(:,end-1),udata.trange);
% face(any(~ismember(udata.face(:,1:2),find(vertIdx)),2),:) = [];
[vert face] = setVertFace(udata);
vertIdx = udata.vert(:,end) == udata.trackii & ismember(udata.vert(:,end-1),udata.trange);
face(any(~ismember(udata.face(:,1:2),find(vertIdx)),2),:) = [];
%set marker edge color for track ii
udata.markeredgecolor = markeredgeC(ii,:);
%make patch
hpNew = makePatch(face,vert,'plotTrackPatchHighlight',udata);
end
else
udata.trackNum = trackNum;
[vert face] = setVertFace(udata);
hpNew = makePatch(face,vert,'plotTrackPatchHighlight',udata);
end
function initDataTip(h)
% initialize specialized data tip
%
% h - figure handle
dcm_obj = datacursormode(h);
if isempty(get(dcm_obj,'updatefcn'))
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
disp('plotTracks: specialized data tip initialized')
end
if strcmp(dcm_obj.Enable,'on')
datacursormode off
disp('plotTracks: datacursormode toggled off')
else
datacursormode on
disp('plotTracks: datacursormode toggled on')
end
function hp = resetTracks(h)
% reset patch
%
% INPUT
% h - figure handle
% OUTPUT
% hp - updated patch handles
%delete all plotTrackPatchHighlight
hpH = findall(h,'type','patch','tag','plotTrackPatchHighlight');
delete(hpH)
%find all plotTrackPatchShadow
hpS = findall(h,'type','patch','tag','plotTrackPatchShadow');
shadowParent = [];
for ii = 1:length(hpS)
udataShadow = get(hpS(ii),'userdata');
shadowParent(ii) = udataShadow.shadowParent;
end
%find all plotTrackPatch
hp = findall(h,'type','patch','tag','plotTrackPatch');
% if length(hp)>1
% idx = find(~cellfun('isempty',strfind(get(hp,'tag'),'plotTrackPatch')))';
% else
% idx = ~isempty(strfind(get(hp,'tag'),'plotTrackPatch'));
% end
for ii = 1:length(hp)
udata = get(hp(ii),'userdata');
delete(hp(ii))
udata.updateOptions = 1;
udata = updateOptions(udata);
[vert face] = setVertFace(udata);
shadowIdx = hp(ii) == shadowParent;
hp(ii) = makePatch(face,vert,'plotTrackPatch',udata);
%make new shadow
if any(shadowIdx)
delete(hpS(shadowIdx))
resetAxes(udata);
end
makeShadow(hp(ii));
end
%update dipTrack
udata = get(h,'userdata');
if ~isempty(udata) && isfield(udata,'curslice')
if udata.curslice == udata.maxslice
dipmapping(h,'slice',udata.curslice+-1);
else
dipmapping(h,'slice',udata.curslice+1);
end
dipmapping(h,'slice',udata.curslice);
end
hp = findall(h,'type','patch','tag','plotTrackPatch');
function updatePlotTrackOptions(h)
%update plotTracks options
hp = findall(h,'tag','plotTrackPatch');
updateFields = {'colorByValue' 'linewidth' 'linestyle' 'valueName'...
'trackNum' 'view' 'color' 'minMaxVal' 'markersize'...
'marker' 'trange' 'addShadow' 'highlightTracks' 'displayName' 'cmap'};
%reset
% resetTracks(h);
for ii = 1:length(hp)
udata(ii) = get(hp(ii),'userdata');
end
for ii = 1:length(hp)
% udata = get(hp(ii),'userdata');
%highlight patch
highlightTracks(hp(ii),1:size(udata(ii).tracks,1),[],[],[],[],0);
%Set fields with gui
for jj = 1:length(updateFields)
udataTmp.(updateFields{jj}) = udata(ii).(updateFields{jj});
end
udataTmp = StructDlg(udataTmp,sprintf('Set plotTrackOptions for group %i of %i',ii, length(hp)));
if ~isempty(udataTmp)
for jj = 1:length(updateFields)
udata(ii).(updateFields{jj}) = udataTmp.(updateFields{jj});
end
end
udata(ii) = updateOptions(udata(ii));
set(hp(ii),'userdata',udata(ii))
%reset
hp = resetTracks(h);
% hp = findall(h,'tag','plotTrackPatch');
end
function updateDipTrackOptions(h)
%update plotTracks options
udata = get(h,'userdata');
if ~isempty(udata)
updateFields = {'headMarker' 'headMarkersize' 'npoints'};
%set headMarker field if not defined (back compatibility)
if ~isfield(udata.dipTrackData,'headMarker') || isempty(udata.dipTrackData.headMarker)
udata.dipTrackData.headMarker = 'o';
end
%Set fields with gui
for jj = 1:length(updateFields)
dipTrackDataTmp.(updateFields{jj}) = udata.dipTrackData.(updateFields{jj});
end
dipTrackDataTmp = StructDlg(dipTrackDataTmp,'Set dipTrackOptions');
if ~isempty(dipTrackDataTmp)
for jj = 1:length(updateFields)
udata.dipTrackData.(updateFields{jj}) = dipTrackDataTmp.(updateFields{jj});
end
end
set(h,'userdata',udata);
resetTracks(h);
% if udata.curslice == udata.maxslice
% dipmapping(h,'slice',udata.curslice+-1);
% else
% dipmapping(h,'slice',udata.curslice+1);
% end
% dipmapping(h,'slice',udata.curslice);
end
function syncSPTHSIplotFitResultsBrowser(h)
% toggle syncing SPTHSIplotFitResultsBrowser with data tip
%
% h - figure handle
%get toggle tool handle
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for SPTHSI_FitResultsBrowser and data linkage
if isempty(htt)
addToolBar(h)
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for SPTHSI_FitResultsBrowser and data linkage
end
set(h,'Interruptible','off','BusyAction','cancel')
hp = findall(h,'tag','plotTrackPatch');
for ii = 1:length(hp)
if get(htt,'state') %get toggle tool state
udata = get(hp(ii),'userdata');
try
% if ~isfield(udata,'sptBrowserObj')
% disp('plotTrack: loading SPT object..');
% tic
% sptBrowserObj = SPTHSI_FitResultsBrowser(SPTHSI.loadFile);
% if ii > 1
% assignin('base',sprintf('sptBrowserObj%i',ii),sptBrowserObj);
% fprintf('sptBrowserObj%i variable created in workspace\n',ii)
% else
% assignin('base','sptBrowserObj',sptBrowserObj);
% fprintf('sptBrowserObj variable created in workspace')
% end
% udata.sptBrowserObj = sptBrowserObj;
% % udata.sptBrowserObj = SPTHSI_FitResultsBrowser(sptBrowserObj);
% toc
% end
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
try
%look for spt file 2 folders up
[pathName, baseFigName] = fileparts(get(h,'FileName'));
tmpIdx = strfind(baseFigName,'-');
baseName = baseFigName(1:tmpIdx(end)-1);
sptFile = fullfile(fileparts(fileparts(pathName)),[baseName '.spt']);
udata.sptBrowserObj.SptObj = SPT.loadFile(sptFile);
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
try
%look for spt file 3 folders up
sptFile = fullfile(fileparts(fileparts(fileparts(pathName))),[baseName '.spt']);
udata.sptBrowserObj.SptObj = SPT.loadFile(sptFile);
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
if isfield(udata,'sptBrowserObj')
udata = rmfield(udata,'sptBrowserObj');
set(hp(ii),'userdata',udata);
end
set(htt,'state','off') %set toggle tool state
warning('plotTrack:NoSptPlotObj','plotTrack: synchronization with sptPlot.FitResultsBrowser not available for current plot');
end
end
end
else
if isfield(udata,'sptBrowserObj')
udata.sptBrowserObj.BrowseFlag = 1;
end
end
end
function output_txt = plotTracksDataCursor(obj,event_obj)
% Display the position of the data cursor
% obj Currently not used (empty)
% event_obj Handle to event object
% output_txt Data cursor text string (string or cell array of strings).
pos = get(event_obj,'Position');
output_txt = {['X: ',num2str(pos(1),4)],...
['Y: ',num2str(pos(2),4)]};
try
% If there is a Z-coordinate in the position, display it as well
if length(pos) > 2
output_txt{end+1} = ['Z: ',num2str(pos(3),4)];
end
%get patch handle
hp = get(event_obj,'target');
if ~strcmp(get(hp,'type'),'patch') || (isempty(strfind(get(hp,'tag'),'plotTrackPatch'))...
&& isempty(strfind(get(hp,'tag'),'dipTrackLocMarker')))
output_txt = [];
return;
end
displayName = get(hp,'displayname');
if ~isempty(displayName)
output_txt{end+1} = sprintf('%s', displayName);
end
udata = get(hp,'userdata');
% find vertex index for current point
idx = get(event_obj,'dataindex');
% display trackNum
trackNum = udata.vert(idx,end);
output_txt{end+1} = sprintf('trackNum: %i', trackNum);
% If there is a Val field in userdata, display it as well
if isfield(udata,'val') && ~isempty(udata.val)
output_txt{end+1} = sprintf('Val: %.3g', udata.val(idx));
output_txt{end+1} = sprintf('meanVal: %.3g', mean(udata.val(udata.vert(:,end) == udata.vert(idx,end))));
end
% If there is a Val field in userdata, display it as well
zIdx = udata.vert(idx,end-1)/udata.t;
if isfield(udata,'subRegionModel') && ~isempty(udata.subRegionModel)
output_txt{end+1} = sprintf('boxIdxA: %i', udata.subRegionModel(trackNum,zIdx,1));
output_txt{end+1} = sprintf('boxIdxF: %i', udata.subRegionModel(trackNum,zIdx,2));
output_txt{end+1} = sprintf('model: %i', udata.subRegionModel(trackNum,zIdx,3));
output_txt{end+1} = sprintf('idx: %i', udata.subRegionModel(trackNum,zIdx,4));
end
% If there is a ID field in userdata, display it
if isfield(udata,'ID') && ~isempty(udata.ID)
if ischar(udata.ID)
output_txt{end+1} = sprintf('ID: %s', udata.ID);
else if isnumerical(udata.ID)
output_txt{end+1} = sprintf('ID: %g', udata.ID);
end
end
end
%highlight trackLines
% highlightTracks(get(event_obj,'target'),udata.vert(idx,end))
%highlight track
h = get(get(get(event_obj,'target'),'parent'),'parent');
dcm_obj = datacursormode(h);
info_cell = squeeze(struct2cell(getCursorInfo(dcm_obj)));
hLines = findall(cell2mat(info_cell(1,:)),'tag','plotTrackPatchHighlight');
if isempty(dcm_obj)
resetTracks(h);
else
if udata.highlightTracks
hpHighlight = findall(hp,'tag','plotTrackPatchHighlight');
trackNum = udata.vert(idx,end);
for ii = 1:length(hpHighlight)
udataHighlight = get(hpHighlight(ii),'userdata');
trackNum = [trackNum;udataHighlight.trackii];
end
try
highlightTracks(hp,trackNum);
catch me
output_txt{end+1} = sprintf('highlightTracks error\nmessage:%s\n',...
me.stack(end).file,me.stack(end).name,me.stack(end).line,me.message);
end
end
end
if isfield(udata,'sptBrowserObj') && isfield(udata,'subRegionModel')
%get toggle tool handle
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for sptBrowserObj and data linkage
if isa(udata.sptBrowserObj,'SPTHSI_FitResultsBrowser') ...
&& udata.sptBrowserObj.BrowseFlag
% && strcmp(get(htt,'state'),'on') ...
% && strcmp(get(dcm_obj,'Enable'),'on')
if zIdx ~= udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) == udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.FrameIdx = zIdx;
else if zIdx == udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) ~= udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.BoxIdx = udata.subRegionModel(trackNum,zIdx,2);
else if zIdx ~= udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) ~= udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.BrowseFlag = 0;
udata.sptBrowserObj.FrameIdx = zIdx;
udata.sptBrowserObj.BrowseFlag = 1;
udata.sptBrowserObj.BoxIdx = udata.subRegionModel(trackNum,zIdx,2);
% % disp(['plotTracks: updating frame ' num2str(zIdx) ' box ' num2str(udata.subRegionModel(trackNum,zIdx,2)) ' for SPTHSIplotFitResultsBrowser...'])
% % tic
% udata.sptBrowserObj.SptObj.plotFitResultsBrowser(zIdx,udata.subRegionModel(trackNum,zIdx,2));
% % toc
end
end
end
end
end
catch me
output_txt{end+1} = sprintf('plotTracksDataCursor error\nmessage:%s',...
me.stack(end).file,me.stack(end).name,me.stack(end).line,me.message);
end
|
github | carlassmith/exampleGLRT-master | pdftops.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/pdftops.m | 3,077 | utf_8 | 8dff856e4b450072050d8aa571d1a08e | function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
% under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
path_ = 'C:\Program Files\xpdf\pdftops.exe';
else
path_ = '/usr/local/bin/pdftops';
end
if check_store_xpdf_path(path_)
return
end
% Ask the user to enter the path
while 1
if strncmp(computer,'MAC',3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.'))
end
base = uigetdir('/', 'Pdftops not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep];
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break;
end
end
if check_store_xpdf_path(path_)
return
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system(sprintf('"%s" -h', path_));
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
end
|
github | carlassmith/exampleGLRT-master | crop_borders.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/crop_borders.m | 1,669 | utf_8 | 725f526e7270a9b417300035d8748a9c | %CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, v] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how many pixels padding to have. Default: 0.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% v - 1x4 vector of start and end indices for first two dimensions, s.t.
% B = A(v(1):v(2),v(3):v(4),:,:).
function [A, v] = crop_borders(A, bcol, padding)
if nargin < 3
padding = 0;
end
[h, w, c, n] = size(A);
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(h,ceil(end/2),:,1);
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop the background, leaving one boundary pixel to avoid bleeding on resize
v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];
A = A(v(1):v(2),v(3):v(4),:,:);
end
function A = col(A)
A = A(:);
end
|
github | carlassmith/exampleGLRT-master | dipTrack.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/dipTrack.m | 18,958 | utf_8 | c7d59b2c657c8bfc11b3b6bccfb4fdbb | function varargout = dipTrack(varargin)
% dipTrack dipimage tracking figure
%
% USAGE:
% h = dipTrack(options); %setup dipTrack figure
% h = dipTrack(fh); %setup listener for dipTrack figure
%
if nargin > 2
error('dipTrack:ToManyInputs','dipTrack: 0 to 2 inputs required');
end
switch nargin
case 0
options = dipTrackSetOptions;
case 1
if ishandle(varargin{1})
h = varargin{1};
udata = get(h,'userdata');
if isfield(udata,'dipTrackData')
%add back compatibility for dipTrack figures made with plotTracks
if ~isfield(udata.dipTrackData,'plotTracksOptions')
udata.dipTrackData.plotTracksOptions = plotTracksV1SetOptions;
udata.dipTrackData.plotTracksOptions.marker = '.';
udata.dipTrackData.plotTracksOptions.tracks = udata.dipTrackData.tracks;
if size(udata.dipTrackData.c,1) == size(udata.dipTrackData.plotTracksOptions.tracks,1)
udata.dipTrackData.plotTracksOptions.tracksVal = repmat((1:size(udata.dipTrackData.c,1))',[1 size(udata.dipTrackData.plotTracksOptions.tracks,2)]);
udata.dipTrackData.plotTracksOptions.minMaxVal = [min(udata.dipTrackData.plotTracksOptions.tracksVal(:)) max(udata.dipTrackData.plotTracksOptions.tracksVal(:))];
udata.dipTrackData.plotTracksOptions.cmap = udata.dipTrackData.c;
end
if iscell(udata.dipTrackData.trackNum)
trackNum = cell2mat(udata.dipTrackData.trackNum);
else
trackNum = udata.dipTrackData.trackNum;
end
udata.dipTrackData.plotTracksOptions.colorbar = 0;
udata.dipTrackData.plotTracksOptions.WindowKeyPressFcn = 0;
udata.dipTrackData.plotTracksOptions.view = [];
% udata.dipTrackData.plotTracksOptions.addShadow = 0;
udata.dipTrackData.plotTracksOptions.trackNum = trackNum;
udata.dipTrackData.plotTracksOptions.linewidth = udata.dipTrackData.linewidth(2);
udata.dipTrackData.plotTracksOptions.h = h;
udata.dipTrackData.plotTracksOptions.ha = findall(h,'type','axes');
udata.dipTrackData.headMarkersize = udata.dipTrackData.markersize;
udata.dipTrackData.trackToggle = 1;
%delete all prior tracks and localization markers
delete(findall(udata.dipTrackData.plotTracksOptions.ha,'tag','trackLine'));
delete(findall(udata.dipTrackData.plotTracksOptions.ha,'tag','dipTrackLocMarker'));
end
udata.dipTrackData.h = h;
addlistener(udata.dipTrackData.h,'UserData','PostSet',@curslice);
set(h,'userdata',udata);
set(h,'KeyPressFcn',@dipTrack);
return;
else
error('dipTrack:InputMustBeDipTrack','dipTrack: input figure must be initialized using dipTrack')
end
end
options = varargin{1};
case 2
%dipimage keypress call back
dipshow('DIP_callback','KeyPressFcn')
h = varargin{1};
udata = get(h,'UserData');
switch varargin{2}.Key
case {'t','T'} % initialize trackTable
% update_trackTable(h,udata);
case {'r','R'} % toggle track plotting
udata.dipTrackData.trackToggle = ~udata.dipTrackData.trackToggle;
update_tracks(udata);
set(h,'userdata',udata);
case {'d','D'}
plotTracksV1('initDataTip(gcf)');
end
return
end
%initialize dipData
dipTrackData.headMarkersize = options.headMarkersize;
dipTrackData.dipTrackObj = dipTrackObj(0);
dipTrackData.trackTableToggle = 0;
dipTrackData.trackToggle = 1;
dipTrackData.npoints = options.npoints;
%initilize figure
if isempty(options.h)
h = figure;
else
h = options.h;
end
dipTrackData.h = h;
%show image
if options.updateImage
if isempty(options.im)
warning('dipTrack:NoIm','dipTrack: options.im is empty initializing with newim(256,256,10)')
if ~isempty(options.plotTracksOptions.tracks)
sz=round(max(dip_image(options.plotTracksOptions.tracks)));
dipshow(h,newim([sz,sz,size(options.plotTracksOptions.tracks,2)]));
else
dipshow(h,newim([256,256,10]));
end
else
dipshow(h,options.im);
end
end
%set values specific to plotTracksOptions
for ii = 1:length(options.plotTracksOptions)
dipTrackData.plotTracksOptions(ii) = options.plotTracksOptions(ii);
dipTrackData.plotTracksOptions(ii).h = h;
dipTrackData.plotTracksOptions(ii).ha = findall(h,'type','axes');
dipTrackData.plotTracksOptions(ii).colorbar = 0;
% dipTrackData.plotTracksOptions(ii).WindowKeyPressFcn = 0;
dipTrackData.plotTracksOptions(ii).view = [];
% dipTrackData.plotTracksOptions(ii).addShadow = 0;
if strcmp(dipTrackData.plotTracksOptions(ii).marker,'none')
dipTrackData.plotTracksOptions(ii).marker = '.';
end
end
%add listener
dipTrackData.lh = addlistener(h,'UserData','PostSet',@curslice);
%add dipTrackData to userdata
udata = get(h,'userdata');
udata.dipTrackData = dipTrackData;
set(h,'userdata',udata);
%change KeyPressFcn
set(h,'KeyPressFcn',@dipTrack,'busyaction','cancel','interruptible','off');
%add listener
% addlistener(udata.dipTrackData.h,'UserData','PostSet',@curslice);
%initialize tracks
dipmapping(h,'slice',1);
dipmapping(h,'slice',0);
% %add initialization menu
% if isempty(findall(h,'Tag','initializeMenu'))
% hm = findall(h,'Label','plotTracks','Tag','plotTracksMenu');
% uimenu(hm,'Label','initialize dipTrack','Tag','initializeMenu',...
% 'Callback',@dipTrackInitialize);
% end
% ht = findall(h,'type','uitoolbar');
% tags = get(get(ht,'children'),'tag');
% if ~any(strcmp('initDipTrackPushTool',tags))
% load(fullfile(matlabroot,'/toolbox/matlab/icons/','arrow.mat'),'arrowCData');
% hpt = uipushtool(ht,'cdata',arrowCData,'TooltipString','initialize dipTrack',...
% 'clickedcallback',@KeyPress,'userdata','d','tag','initDipTrackPushTool');
% end
%output figure handle
if nargout == 1
varargout{1} = h;
end
function dipTrackInitialize(h,~)
%initialize dipTrack
hf = get(get(h,'parent'),'parent');
dipTrack(hf);
function update_tracks(udata)
%update trajectories in dipTrack figure
if isempty(udata.slicing)
return;
end
% plotTracksOptions = udata.dipTrackData.plotTracksOptions;
hp = findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatch');
if isempty(hp)
plotTracksOptions = udata.dipTrackData.plotTracksOptions;
else
for ii = 1:length(hp)
plotTracksOptions(ii) = get(hp(ii),'userdata');
end
end
%delete all prior tracks and localization markers
delete(findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatch'));
delete(findall(udata.dipTrackData(1).plotTracksOptions(1).ha,'tag','plotTrackPatchShadow'));
delete(findall(plotTracksOptions(1).ha,'tag','plotTrackPatchHighlight'));
delete(findall(plotTracksOptions(1).ha,'tag','dipTrackLocMarker'));
if udata.dipTrackData.trackToggle
if udata.dipTrackData.npoints > udata.maxslice+1
npoints = udata.maxslice+1;
else
npoints = udata.dipTrackData.npoints;
end
trange = udata.curslice+(1:-1:-npoints);
trange(trange<0) = [];
for ii = 1:length(plotTracksOptions)
plotTracksOptions(ii).trange = trange;
[h ha hp] = plotTracksV1(plotTracksOptions(ii));
if ~isempty(hp)
plotTracksOptions1 = get(hp,'userdata');
plotLocMarker(udata,plotTracksOptions1);
end
end
end
function plotLocMarker(udata,options)
%plot localization marker
tag = 'dipTrackLocMarker';
if isfield(udata.dipTrackData,'headMarker') && length(udata.dipTrackData.headMarker) == length(options.trackNum)
for ii = 1:length(options.trackNum)
if options.tracks(options.trackNum(ii),udata.curslice+1,1)
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(1),...
'markerfacecolor',[1 1 1],...
'markeredgecolor',[0 0 0])
if isfield(udata.dipTrackData,'headColor')
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(2),...
'markerfacecolor',udata.dipTrackData.headColor(ii,:),...
'markeredgecolor',[1 1 1])
else
line(options.tracks(options.trackNum(ii),udata.curslice+1,1),...
options.tracks(options.trackNum(ii),udata.curslice+1,2),...
udata.curslice,'tag',tag,'marker',udata.dipTrackData.headMarker(ii),...
'markersize',udata.dipTrackData.headMarkersize(2),...
'markerfacecolor',colorstretch(options.tracksVal(options.trackNum(ii),udata.curslice+1,1),options.minMaxVal,options.cmap),...
'markeredgecolor',[1 1 1])
end
end
end
else
if isfield(udata.dipTrackData,'headMarker') && ~isempty(udata.dipTrackData.headMarker)
options.marker = udata.dipTrackData.headMarker(1);
else
options.marker = 'o';
end
facevertexcdata = options.facevertexcdata;
% options.marker = 'o';
options.markersize = udata.dipTrackData.headMarkersize(1);
options.facevertexcdata = facevertexcdata*0.5;
options.markeredgecolor = [1 1 1];
options.trange = udata.curslice+1;
vert = options.vert(:,[1 2 end-1]);
face = options.face(:,[1 2]);
vertIdx = ismember(options.vert(:,end),options.trackNum) & ismember(options.vert(:,end-1),options.trange);
vert(~vertIdx,:) = NaN;
face(all(~ismember(face(:,1:2),find(vertIdx)),2),:) = NaN;
% face(~ismember(face(:,2),find(vertIdx)),:) = NaN;
if options.trange-1 == udata.maxslice
face = face(:,[2 2]);
else
face = face(:,[1 1]);
end
% if options.trange == 1
% face = face(:,[1 1]);
% else
% face = face(:,[2 2]);
% end
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
options.markersize = udata.dipTrackData.headMarkersize(2);
options.facevertexcdata = facevertexcdata;
if size(facevertexcdata,1) == 1
options.markeredgecolor = facevertexcdata;
else
options.markeredgecolor = 'flat';
end
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
end
function curslice(h,evnt)
%check updating of curslice field in userdata
%get userdata
udata = get(evnt,'NewValue');
%get current slice
if isfield(udata,'curslice') && isfield(udata,'dipTrackData') &&...
udata.dipTrackData.dipTrackObj.slice ~= udata.curslice
udata.dipTrackData.dipTrackObj.slice = udata.curslice; %update slice property
update_tracks(udata); %update figure
% set(udata.dipTrackData.h,'userdata',udata)
end
function initDataTip(h)
% initialize specialized data tip
%
% h - figure handle
dcm_obj = datacursormode(h);
if isempty(get(dcm_obj,'updatefcn'))
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
disp('plotTracks: specialized data tip initialized')
end
function update_trackTable(h,udata)
%update trackTable
%populate fields for backcompatibility
if ~isfield(udata.dipTrackData,'ntrackTable')
udata.dipTrackData.ntrackTable = 5;
end
if ~isfield(udata.dipTrackData,'trackTableDeleteLast')
udata.dipTrackData.trackTableDeleteLast = 1;
end
if ~isfield(udata.dipTrackData,'trackTableShowSummary')
udata.dipTrackData.trackTableShowSummary = 1;
end
locs=dipgetcoords(h,1);
if udata.dipTrackData.trackTableDeleteLast
curFigs = get(findall(0,'tag','dipTrackTable'),'parent');
if iscell(curFigs)
curFigs = cell2mat(curFigs);
end
delete(curFigs)
end
%get track numbers
if iscell(udata.dipTrackData.trackNum)
trackNum = [];
for ii = 1:numel(udata.dipTrackData.trackNum)
trackNum = [trackNum;udata.dipTrackData.trackNum{ii}(:)];
end
else
if isempty(udata.dipTrackData.trackNum)
trackNum = 1:size(udata.dipTrackData.tracks,1);
end
end
%get tracks observed in the current frame
trackNum = trackNum(logical(udata.dipTrackData.tracks(trackNum,locs(3)+1,1)));
%sort tracks by distance from locs
dist = sum((repmat(reshape(locs(1:2),[1 1 2]),[length(trackNum) 1 1])-udata.dipTrackData.tracks(trackNum,locs(3)+1,:)).^2,3);
[val idx] = sort(dist);
trackNum = trackNum(idx);
%get track information
trackNum = trackNum(1:min(udata.dipTrackData.ntrackTable,length(trackNum)));
x = udata.dipTrackData.tracks(trackNum,locs(3)+1,1);
y = udata.dipTrackData.tracks(trackNum,locs(3)+1,2);
c = round(udata.dipTrackData.c(trackNum,:)*255);
% c = zeros(length(trackNum),3);
% obs = zeros(length(trackNum),3); %first observations,last observation, number of total observations
data = cell(length(trackNum),10);
for ii = 1:length(trackNum)
obsfirst = find(udata.dipTrackData.tracks(trackNum(ii),:,1),1,'first');
obslast = find(udata.dipTrackData.tracks(trackNum(ii),:,1),1,'last');
obsall = sum(logical(udata.dipTrackData.tracks(trackNum(ii),:,1)));
% data(ii,:) = {trackNum(ii) x(ii) y(ii) obsfirst obslast obsall false sprintf('%0.1g ',c(ii,:)) '' ''};
cii = sprintf('%s%i%s%i%s%i%s%i%s%i%s%i%s','<html><span style="background-color: rgb(',...
c(ii,1),',',c(ii,2),',',c(ii,3),');">(',...
c(ii,1),',',c(ii,2),',',c(ii,3),')</span></html>');
data(ii,:) = {trackNum(ii) x(ii) y(ii) obsfirst obslast obsall false cii '' ''};
end
cnames = {'track#' 'x' 'y' 'First obs' 'Last obs' '# obs','append' 'color' 'identifier' 'comments'};
cformat= {'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'logical' 'char' 'char' 'char'};
ceditable = logical([0 0 0 0 0 0 1 0 1 1]);
th = figure;
namestr = sprintf('%s%i%s%i%s%i','dipTrackTable(x-',locs(1),',y-',locs(2),',t-',locs(3),')');
t=uitable(th,'ColumnName', cnames,'ColumnFormat', cformat, 'Data', data,...
'columneditable', ceditable,'tag','dipTrackTable');
%update table
pos=get(t,'extent');
set(t, 'Position', pos );
udata1.dipTrackData.trackTableShowSummary = udata.dipTrackData.trackTableShowSummary;
set(th,'Position',pos+[10 75 0 0],'name',namestr,...
'DeleteFcn',@deleteTrackTable,'userdata',udata1);
set(h,'userdata',udata)
figure(h);
%insert code for closing fcn
%add export fcn. export trackTable to workspace and append
function deleteTrackTable(fh,evnt)
%get table data
dipTrackTableData = get(findall(fh,'tag','dipTrackTable'),'data');
%find data to append
if ~isempty(dipTrackTableData)
appendIdx = cell2mat(dipTrackTableData(:,7));
dipTrackTableData = dipTrackTableData(appendIdx,:);
%eliminate append column
dipTrackTableData(:,7) = [];
end
%update summary table
update_trackTableSummary(fh,dipTrackTableData)
function update_trackTableSummary(fh,dipTrackTableData)
%get current figure handle
curSummaryTable = findall(0,'tag','diptracktablesummary');
if ~isempty(curSummaryTable)
dipTrackTableData = [get(curSummaryTable,'data');dipTrackTableData];
else if evalin('base','exist(''dipTrackTableData'',''var'')')
dipTrackTableData = [evalin('base','dipTrackTableData');dipTrackTableData];
end
end
udata = get(fh,'userdata');
%make summary table
curfigs = get(curSummaryTable,'parent');
if iscell(curfigs)
curfigs = cell2mat(curfigs);
end
delete(curfigs)
if ~isempty(dipTrackTableData)
if udata.dipTrackData.trackTableShowSummary
cnames = {'track#' 'x' 'y' 'first obs' 'last obs' '# obs' 'color' 'identifier' 'comments' 'delete'};
cformat= {'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric' 'char' 'char' 'char' 'logical'};
ceditable = logical([0 0 0 0 0 0 0 1 1 1]);
th = figure;
namestr = sprintf('%s%i%s%i%s%i','dipTrackTable(summary)');
t=uitable(th,'columnname', cnames,'columnformat', cformat, 'data', dipTrackTableData,...
'columneditable', ceditable,'tag','diptracktablesummary',...
'celleditcallback',@update_dipTrackTableSummary);
monpos = get(0,'monitorposition');
[val idx] = min(sum(monpos(:,1:2),2)); %find lower left monitor
pos=get(t,'extent');
if pos(4) > monpos(idx,4)-100
pos(4) = monpos(idx,4)-150;
end
if pos(3) > monpos(idx,3)-100
pos(3) = monpos(idx,3)-150;
end
pos1 = [monpos(idx,[3 4]) 0 0]+[-pos([3 4])-75 pos([3 4])];
set(t, 'position', pos );
set(th,'position',pos1,'userdata',udata,'name',namestr);
end
end
assignin('base','dipTrackTableData',dipTrackTableData)
function update_dipTrackTableSummary(t,evnt)
if evnt.Indices(2) == 10
button = questdlg(sprintf('%s%i%s','Do you want to delete row',evnt.Indices(1),'?'),...
'dipTrackTable(summary)','YES','NO','YES');
switch button
case 'YES'
th = get(t,'parent');
% dipTrackTableData = evalin('base','dipTrackTableData');
curSummaryTable = findall(0,'tag','diptracktablesummary');
dipTrackTableData = get(curSummaryTable,'data');
dipTrackTableData(evnt.Indices(1),:) = [];
assignin('base','dipTrackTableData',dipTrackTableData);
set(curSummaryTable,'data',dipTrackTableData);
% update_trackTableSummary(th,[]);
return
case 'NO'
return
end
end
|
github | carlassmith/exampleGLRT-master | plotTracksV1.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/plotTracksV1.m | 31,113 | utf_8 | 7a5e09d1acadaeab6f261a406503f75f | function [h ha hp] = plotTracksV1(options)
% PLOTTRACKSV1 plot tracks using specified options
%
% h = plotTracksV1(options)
%
% INPUTS
% options - options structure with input options. See
% plotTracksSetOptions for more details.
% OUTPUTS
% h - figure handle
% ha - axes handle
% hp - patch handle
%
%%
% options = plotTracksSetOptions;
% options.tracks = tracks;
% options.tracksVal = tracksWv;
% options.t = 1;
%%
% highlight tracks if input is str
if ischar(options)
try
eval(options);
return
catch err
getReport(err)
error('plotTracks:ImproperInput','plotTracks: character input is not correct')
end
% if strfind(options,'highlightTracks')
% h = eval(options);
% return;
% else if strfind(options,'initDataTip')
% eval(options);
% return;
% else if strfind(options,'initDataTip')
% eval(options,'resetTracks')
% else
% error('plotTracks:ImproperInput','plotTracks: character input is not correct')
% end
% end
% end
end
%check inputs
if isempty(options.tracks)
error('plotTracks:EmptyTracks','plotTracks: tracks field of options cannot not be empty')
end
% make figure if not indicated in input options
if isempty(options.h) && isempty(options.ha)
h = figure; %make figure
else
if ~isempty(options.ha)
h = get(options.ha,'parent');
else
h = options.h; %get figure handle
end
end
%set key press function
% if options.WindowKeyPressFcn
% set(h,'WindowKeyPressFcn',@KeyPress);
% end
%setup axes
if isempty(options.ha)
ha = findall(allchild(h),'type','axes'); %get axis handle
if ~isempty(findall(ha,'tag','Colorbar'))
ha = ha(ha ~= findall(ha,'tag','Colorbar'));
end
if isempty(ha)
ha = axes('parent',h);
end
ha = ha(1);
else
ha = options.ha;
end
options.ha = ha;
options.h = h;
if ~isempty(options.xlim) && ~isempty(options.ylim)
set(ha,'plotboxaspectratio',[diff([options.xlim;options.ylim]')+1 max(diff([options.xlim;options.ylim]')+1)]) %set plotting aspect ratio
end
options = updateOptions(options);
[vert face] = setVertFace(options);
%make patch object
hp = makePatch(face,vert,'plotTrackPatch',options);
% create colorbar
if options.colorbar && ~isempty(options.minMaxVal) && options.minMaxVal(1)~=options.minMaxVal(2)
colormap(options.h,options.cmap) %define colormap
hcb = colorbar('peer',ha); %make colorbar
set(get(hcb,'title'),'string',options.valueName) %set colorbar title
set(findall(hcb,'tag','TMW_COLORBAR'),'ydata',options.minMaxVal) %set range for colorbar values
set(hcb,'ylim',options.minMaxVal) %set range for colorbar figure
end
if ~isempty(options.view)
view(options.ha,options.view)
end
resetAxes(options);
%setup data tip
dcm_obj = datacursormode(h);
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
%add toolbar
% if options.WindowKeyPressFcn && isempty(findall(h,'userdata','plotTracksToolbar'))
% addToolBar(h)
% end
% addToolBar(h)
% if isempty(findall(h,'tag','plotTracksMenu'))
% addMenu(h)
% end
%add shadow on xy plane
hp = makeShadow(hp,options);
function resetAxes(options)
%reset data axes
%only change renderer and axis if not dipimage figure
drawnow
udataFig = get(options.h,'userdata');
if ~isfield(udataFig,'state')
set(options.h,'renderer','zbuffer')
axis(options.ha,'ij')
end
% if ~isempty(options.view)
% view(options.ha,options.view)
% end
tightcheck = 0;
if ~isempty(options.xlim)
xlim(options.ha,options.xlim);
tightcheck = tightcheck+1;
end
if ~isempty(options.ylim)
ylim(options.ha,options.ylim);
tightcheck = tightcheck+1;
end
if isfield(options,'zlim') && ~isempty(options.zlim)
zlim(options.ha,options.zlim);
tightcheck = tightcheck+1;
end
if tightcheck ~= 3 && ~isfield(udataFig,'state')
axis(options.ha,'tight')
end
xdiff = diff(get(options.ha,'xlim'));
ydiff = diff(get(options.ha,'ylim'));
zdiff = diff(get(options.ha,'zlim'));
if isfield(options,'DataAspectRatio')
set(options.ha,'DataAspectRatio',options.DataAspectRatio)
else
set(options.ha,'DataAspectRatio',[1 1 zdiff/max([xdiff ydiff])])
end
% drawnow
function [vert face] = setVertFace(options)
% find vertices with specified trackNum and in specified trange
if isfield(options,'zPlotFlag') && options.zPlotFlag
vert = options.vert(:,[1 2 3]);
else
vert = options.vert(:,[1 2 end-1]);
vert(:,3) = (vert(:,3)-1)*options.t;
end
face = options.face(:,1:2);
vertIdx = ismember(options.vert(:,end),options.trackNum) & ismember(options.vert(:,end-1),options.trange);
% vert(:,3) = (vert(:,3)-1)*options.t;
vert(~vertIdx,:) = NaN;
face(any(~ismember(options.face(:,1:2),find(vertIdx)),2),:) = NaN;
function hp = makeShadow(hp,options)
%add shadow on xy plane
if nargin == 1
options = get(hp,'userdata');
end
if options.addShadow && ~isempty(hp)
shadOptions = options;
[vert face] = setVertFace(shadOptions);
shadOptions.addShadow = 0;
% shadOptions.tagAppendix = 'Shadow';
shadOptions.shadowParent = hp;
% if ~isempty(options.trange)
% shadOptions.trange = min(options.trange);
% else
% shadOptions.trange = 0;
% end
shadOptions.colorByValue = 0;
shadOptions.color = [.75 .75 .75];
% shadOptions.face = options.face;
shadOptions.markersize = options.markersize*options.addShadow;
shadOptions.linewidth = options.linewidth*options.addShadow;
% shadOptions.vert(:,shadOptions.ndims+1) = shadOptions.trange;
shadOptions = updateOptions(shadOptions);
% vert(:,end) = shadOptions.trange;
% vert(:,end) = min(get(shadOptions.ha,'zlim'))-0.5;
zdata = get(findall(shadOptions.h,'tag','plotTrackPatch'),'zdata');
if iscell(zdata)
zdata = cell2mat(zdata');
end
vert(:,end) = min(min(zdata))-shadOptions.t*0.5;
%make patch object
makePatch(face,vert,'plotTrackPatchShadow',shadOptions);
% hp(2) = plotTracksV1(shadOptions);
%repostion shadows z position
allShadows = findall(shadOptions.h,'tag','plotTrackPatchShadow');
faces = get(findall(shadOptions.h,'tag','plotTrackPatch'),'faces');
zdata = get(findall(shadOptions.h,'tag','plotTrackPatch'),'zdata');
if iscell(zdata)
zdata = cell2mat(zdata')';
faces = cell2mat(faces);
else
zdata = zdata';
end
for ii = 1:length(allShadows)
udata = get(allShadows(ii),'userdata');
[vert face] = setVertFace(udata);
if any(any(~isnan(faces)))
vert(:,end) = min(zdata(~isnan(faces)))-udata.t*1.5;
makePatch(face,vert,'plotTrackPatchShadow',udata,allShadows(ii));
end
end
end
function options = updateOptions(options)
%update options for vertices, faces etc.
%get track numbers if not specified
if isempty(options.trackNum)
options.trackNum = 1:size(options.tracks,1);
end
options.trackNum = options.trackNum(:)';
%get time range if not specified
if isempty(options.trange)
options.trange = 1:size(options.tracks,2);
end
options.trange = options.trange(:)';
%compile vertices and faces for all tracks
if ~isfield(options,'updateOptions') || options.updateOptions
options.ndims = size(options.tracks,3);
%vertices for patch [positions t trackIdx]
options.vert = zeros(sum(sum(logical(options.tracks(:,:,1)))),options.ndims+2);
%faces for patch [vert1 vert2 trackIdx]
options.face = zeros(size(options.vert,1)-size(options.tracks,1),3);
% %index for track that vertex belongs to
% options.vertTrackIdx = zeros(size(options.vert,1),1);
% %index for track that vertex belongs to
% options.vertFaceIdx = zeros(size(options.face,1),1);
if ~isempty(options.tracksVal)
options.val = zeros(size(options.vert,1),1);
else
options.val = [];
end
count = 1;
count1 = 0;
for ii = 1:size(options.tracks,1)
nObsTrack = sum(logical(options.tracks(ii,:,1)));
vertIdx = count+(0:nObsTrack-1);
if nObsTrack
if nObsTrack > 1
options.vert(count+(0:nObsTrack-1),:) = [squeeze(options.tracks(ii,logical(options.tracks(ii,:,1)),:)) find(logical(options.tracks(ii,:,1)))' repmat(ii,[nObsTrack 1])];
else
options.vert(count+(0:nObsTrack-1),:) = [reshape(options.tracks(ii,logical(options.tracks(ii,:,1)),:),[1 options.ndims]) find(logical(options.tracks(ii,:,1)))' repmat(ii,[nObsTrack 1])];
% options.vert(count+(0:nObsTrack-1),end) = repmat(ii,[nObsTrack 1]);
end
options.face((count1+(1:nObsTrack-1)),:) = [vertIdx(1:end-1)' vertIdx(2:end)' repmat(ii,[nObsTrack-1 1])];
% options.vertFaceIdx(count+(1:nObsTrack-1)) = repmat(ii,[nObsTrack-1 1]);
if ~isempty(options.tracksVal)
options.val(count+(0:nObsTrack-1)) = squeeze(options.tracksVal(ii,logical(options.tracks(ii,:,1)))) ;
end
count = count+nObsTrack;
count1 = count1+nObsTrack-1;
end
end
end
%get track coloration
if options.colorByValue
if ~isfield(options,'updateOptions') || options.updateOptions
if ~isempty(options.val) && any(options.val ~= 1)
% get color information for plotting
if isempty(options.minMaxVal)
options.minMaxVal = [min(options.val) max(options.val)];
end
options.facevertexcdata = colorstretch(options.val,options.minMaxVal,options.cmap);
if strcmp(options.linestyle,'-')
options.edgecolor = 'interp';
else
options.edgecolor = 'flat';
end
options.markerfacecolor = 'flat';
options.markeredgecolor = 'flat';
else
options.facevertexcdata = options.color;
options.edgecolor = options.color;
options.markerfacecolor = options.color;
options.markeredgecolor = options.color;
end
end
else
options.facevertexcdata = options.color;
options.edgecolor = options.color;
options.markerfacecolor = options.color;
options.markeredgecolor = options.color;
end
options.updateOptions = 0;
function KeyPress(h,evnt)
% scroll feature
%variable inputs
if isempty(evnt)
key = get(h,'userdata');
else
key = evnt.Key;
end
% if strcmp(get(get(h,'parent'),'userdata'),'plotTracksToolbar') || strcmp(get(get(h,'parent'),'tag'),'plotTracksMenu')
% hf = get(get(h,'parent'),'parent');
% else
% hf = h;
% end
hf = ancestor(h,'figure');
% get userdata
switch key
case 'r'
resetTracks(hf);
case 'h'
syncSPTHSIplotFitResultsBrowser(hf);
case 'd'
initDataTip(hf);
case 's'
updatePlotTrackOptions(hf);
case 'e'
updateDipTrackOptions(hf);
end
function addMenu(h)
%add plotTrack menu to figure
hm = uimenu(h,'Label','plotTracks','Tag','plotTracksMenu');
uimenu(hm,'Label','reset tracks','Tag','resetMenu',...
'Callback',@KeyPress,'userdata','r');
uimenu(hm,'Label','toggle datacursormode','Tag','dataTipMenu',...
'Callback',@KeyPress,'userdata','d');
uimenu(hm,'Label','BrowseFitResults','Tag','SPTHSIplotFitResultsBrowserToggleMenu',...
'Callback',@KeyPress,'userdata','h');
uimenu(hm,'Label','set plotTrackOptions','Tag','plotTracksOptionsMenu',...
'Callback',@KeyPress,'userdata','s');
uimenu(hm,'Label','set dipTrackOptions','Tag','plotTracksOptionsMenu',...
'Callback',@KeyPress,'userdata','e');
function addToolBar(h)
% add plotTracks toolbar to figure
% ht = uitoolbar(h);
set(h,'toolbar','figure')
ht = findall(h,'type','uitoolbar');
tags = get(get(ht,'children'),'tag');
% set(ht,'userdata','plotTracksToolbar')
if ~any(strcmp('SPTHSI:FitResultsBrowser',tags))
load('cubeIcon','cdata');
htt = uitoggletool(ht,'separator','on','cdata',cdata,'TooltipString','view box fitting in SPTHSI:FitResultsBrowser',...
'clickedcallback',@KeyPress,'userdata','h','tag','SPTHSI:FitResultsBrowser');
end
if ~any(strcmp('resetPushTool',tags))
load('colorlinesIcon','cdata');
hpt = uipushtool(ht,'cdata',cdata,'TooltipString','reset tracks to original state',...
'clickedcallback',@KeyPress,'userdata','r','tag','resetPushTool');
end
if ~any(strcmp('initDataTipPushTool',tags))
load('colorlinesboxIcon','cdata');
hpt = uipushtool(ht,'cdata',cdata,'TooltipString','initialize specialized data tip',...
'clickedcallback',@KeyPress,'userdata','d','tag','initDataTipPushTool');
end
function hp = makePatch(face,vert,tag,options,hp)
%make Patch object using options
% if all(isnan(vert))
% hp = [];
% return;
% end
if isfield(options,'tagAppendix')
tag = [tag options.tagAppendix];
end
if nargin == 5
options = get(hp,'userdata');
highlightTracksOriginal = options.highlightTracks;
options.highlightTracks = 0;
set(hp,'userdata',options);
% set(hp,'facevertexcdata', options.facevertexcdata, ...
% 'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
% 'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
% 'linewidth',options.linewidth,'linestyle',options.linestyle,...
% 'markeredgecolor',options.markeredgecolor);
set(hp,'faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor);
options.highlightTracks = highlightTracksOriginal;
set(hp,'userdata',options);
else
hp = patch('faces', face, 'vertices', vert, 'facevertexcdata', options.facevertexcdata, ...
'edgecolor', options.edgecolor, 'facecolor', 'none','markersize',options.markersize,...
'marker',options.marker,'markerfacecolor', options.markerfacecolor,...
'linewidth',options.linewidth,'linestyle',options.linestyle,...
'markeredgecolor',options.markeredgecolor,...
'parent',options.ha,'tag',tag,'userdata',options);
end
if isfield(options,'displayName')
set(hp,'displayname',options.displayName)
end
function hpNew = highlightTracks(hp,trackNum,linewidth,markersize,makeOthersTransparent,...
linecolor,markeredgecolorgray,marker)
% highlight indicated track lines
%
% INPUTS
% hp - patch handle
% trackNum - vector with length N containing track numbers to highlight.
% linewidth - linewidth for highlighted track. Default 4
% markersize - marker size for highlighted track.
% makeOthersTransparent - binary for graying out other trajectories. Default 1
% linecolor - color for highligthed tracsk 1 by 3 vector for rgb
% markeredgecolorgray - binary for making line marker edge color gray(1) or same color as
% track(0). Default 1
%check inputs
if ~exist('hp','var') || isempty(hp)
return;
end
if ~exist('trackNum','var') ||isempty(trackNum)
return;
end
if ~exist('linewidth','var') ||isempty(linewidth)
linewidth = 4;
end
if ~exist('markersize','var') ||isempty(markersize)
markersize = 6;
end
if ~exist('makeOthersTransparent','var') ||isempty(makeOthersTransparent)
makeOthersTransparent = 1;
end
if ~exist('linecolor','var') ||isempty(linecolor)
linecolor = [];
end
if ~exist('markeredgecolorgray','var') ||isempty(markeredgecolorgray)
markeredgecolorgray = 1;
end
if ~exist('marker','var') ||isempty(marker)
marker = 'o';
end
%find patch handle
if ~ishandle(hp)
hptmp = findall(0,'tag','plotTrackPatch');
hpIdx = round(hptmp - double(hp)) == 0;
hp = hptmp(hpIdx);
end
if isempty(hp)
return;
end
%find all existing highlighted tracks
hpHighlightOld = findall(get(hp,'parent'),'tag','plotTrackPatchHighlight');
trackNumOld = [];
if ~isempty(hpHighlightOld)
for ii = 1:length(hpHighlightOld)
udataOld = get(hpHighlightOld(ii),'userdata');
if isfield(udataOld,'trackii')
trackNumOld = [trackNumOld; udataOld.trackii];
end
end
end
delete(hpHighlightOld)
%get color information from figure
udata = get(hp,'userdata');
%find vertices for specifie
trackNum = unique([trackNumOld trackNum(:)']);
if makeOthersTransparent
%change transparency of patch
set(hp,'facevertexcdata', udata.facevertexcdata*.3+.7,...
'linewidth',udata.linewidth*.75,'markersize',udata.markersize*.75);
end
%get marker edge color
if markeredgecolorgray
if length(trackNum) > 1
markeredgeC = repmat((.4:.4/(length(trackNum)-1):.8)',[1 3]);
else
markeredgeC = [.4 .4 .4];
end
else if ~isempty(linecolor)
markeredgeC = linecolor;
else
markeredgeC = [];
end
end
%loop through tracks
if ~isempty(linecolor)
udata.facevertexcdata = linecolor;
udata.edgecolor = linecolor;
end
udata.markersize = markersize;
udata.linewidth = linewidth;
udata.marker = marker;
if size(markeredgeC,1) == length(trackNum)
for ii = 1:length(trackNum)
udata.trackii = trackNum(ii);
% find vertices with specified trackNum and in specified trange
% vert = udata.vert(:,[1 2 end-1]);
% face = udata.face(:,1:2);
% vertIdx = udata.vert(:,end) == udata.trackii & ismember(udata.vert(:,end-1),udata.trange);
% face(any(~ismember(udata.face(:,1:2),find(vertIdx)),2),:) = [];
[vert face] = setVertFace(udata);
vertIdx = udata.vert(:,end) == udata.trackii & ismember(udata.vert(:,end-1),udata.trange);
face(any(~ismember(udata.face(:,1:2),find(vertIdx)),2),:) = [];
%set marker edge color for track ii
udata.markeredgecolor = markeredgeC(ii,:);
%make patch
hpNew = makePatch(face,vert,'plotTrackPatchHighlight',udata);
end
else
udata.trackNum = trackNum;
[vert face] = setVertFace(udata);
hpNew = makePatch(face,vert,'plotTrackPatchHighlight',udata);
end
function initDataTip(h)
% initialize specialized data tip
%
% h - figure handle
dcm_obj = datacursormode(h);
if isempty(get(dcm_obj,'updatefcn'))
set(dcm_obj,'updatefcn',@plotTracksDataCursor);
disp('plotTracks: specialized data tip initialized')
end
if strcmp(dcm_obj.Enable,'on')
datacursormode off
disp('plotTracks: datacursormode toggled off')
else
datacursormode on
disp('plotTracks: datacursormode toggled on')
end
function hp = resetTracks(h)
% reset patch
%
% INPUT
% h - figure handle
% OUTPUT
% hp - updated patch handles
%delete all plotTrackPatchHighlight
hpH = findall(h,'type','patch','tag','plotTrackPatchHighlight');
delete(hpH)
%find all plotTrackPatchShadow
hpS = findall(h,'type','patch','tag','plotTrackPatchShadow');
shadowParent = [];
for ii = 1:length(hpS)
udataShadow = get(hpS(ii),'userdata');
shadowParent(ii) = udataShadow.shadowParent;
end
%find all plotTrackPatch
hp = findall(h,'type','patch','tag','plotTrackPatch');
% if length(hp)>1
% idx = find(~cellfun('isempty',strfind(get(hp,'tag'),'plotTrackPatch')))';
% else
% idx = ~isempty(strfind(get(hp,'tag'),'plotTrackPatch'));
% end
for ii = 1:length(hp)
udata = get(hp(ii),'userdata');
delete(hp(ii))
udata.updateOptions = 1;
udata = updateOptions(udata);
[vert face] = setVertFace(udata);
shadowIdx = hp(ii) == shadowParent;
hp(ii) = makePatch(face,vert,'plotTrackPatch',udata);
%make new shadow
if any(shadowIdx)
delete(hpS(shadowIdx))
resetAxes(udata);
end
makeShadow(hp(ii));
end
%update dipTrack
udata = get(h,'userdata');
if ~isempty(udata) && isfield(udata,'curslice')
if udata.curslice == udata.maxslice
dipmapping(h,'slice',udata.curslice+-1);
else
dipmapping(h,'slice',udata.curslice+1);
end
dipmapping(h,'slice',udata.curslice);
end
hp = findall(h,'type','patch','tag','plotTrackPatch');
function updatePlotTrackOptions(h)
%update plotTracks options
hp = findall(h,'tag','plotTrackPatch');
updateFields = {'colorByValue' 'linewidth' 'linestyle' 'valueName'...
'trackNum' 'view' 'color' 'minMaxVal' 'markersize'...
'marker' 'trange' 'addShadow' 'highlightTracks' 'displayName' 'cmap'};
%reset
% resetTracks(h);
for ii = 1:length(hp)
udata(ii) = get(hp(ii),'userdata');
end
for ii = 1:length(hp)
% udata = get(hp(ii),'userdata');
%highlight patch
highlightTracks(hp(ii),1:size(udata(ii).tracks,1),[],[],[],[],0);
%Set fields with gui
for jj = 1:length(updateFields)
udataTmp.(updateFields{jj}) = udata(ii).(updateFields{jj});
end
udataTmp = StructDlg(udataTmp,sprintf('Set plotTrackOptions for group %i of %i',ii, length(hp)));
if ~isempty(udataTmp)
for jj = 1:length(updateFields)
udata(ii).(updateFields{jj}) = udataTmp.(updateFields{jj});
end
end
udata(ii) = updateOptions(udata(ii));
set(hp(ii),'userdata',udata(ii))
%reset
hp = resetTracks(h);
% hp = findall(h,'tag','plotTrackPatch');
end
function updateDipTrackOptions(h)
%update plotTracks options
udata = get(h,'userdata');
if ~isempty(udata)
updateFields = {'headMarker' 'headMarkersize' 'npoints'};
%set headMarker field if not defined (back compatibility)
if ~isfield(udata.dipTrackData,'headMarker') || isempty(udata.dipTrackData.headMarker)
udata.dipTrackData.headMarker = 'o';
end
%Set fields with gui
for jj = 1:length(updateFields)
dipTrackDataTmp.(updateFields{jj}) = udata.dipTrackData.(updateFields{jj});
end
dipTrackDataTmp = StructDlg(dipTrackDataTmp,'Set dipTrackOptions');
if ~isempty(dipTrackDataTmp)
for jj = 1:length(updateFields)
udata.dipTrackData.(updateFields{jj}) = dipTrackDataTmp.(updateFields{jj});
end
end
set(h,'userdata',udata);
resetTracks(h);
% if udata.curslice == udata.maxslice
% dipmapping(h,'slice',udata.curslice+-1);
% else
% dipmapping(h,'slice',udata.curslice+1);
% end
% dipmapping(h,'slice',udata.curslice);
end
function syncSPTHSIplotFitResultsBrowser(h)
% toggle syncing SPTHSIplotFitResultsBrowser with data tip
%
% h - figure handle
%get toggle tool handle
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for SPTHSI_FitResultsBrowser and data linkage
if isempty(htt)
addToolBar(h)
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for SPTHSI_FitResultsBrowser and data linkage
end
set(h,'Interruptible','off','BusyAction','cancel')
hp = findall(h,'tag','plotTrackPatch');
for ii = 1:length(hp)
if get(htt,'state') %get toggle tool state
udata = get(hp(ii),'userdata');
try
% if ~isfield(udata,'sptBrowserObj')
% disp('plotTrack: loading SPT object..');
% tic
% sptBrowserObj = SPTHSI_FitResultsBrowser(SPTHSI.loadFile);
% if ii > 1
% assignin('base',sprintf('sptBrowserObj%i',ii),sptBrowserObj);
% fprintf('sptBrowserObj%i variable created in workspace\n',ii)
% else
% assignin('base','sptBrowserObj',sptBrowserObj);
% fprintf('sptBrowserObj variable created in workspace')
% end
% udata.sptBrowserObj = sptBrowserObj;
% % udata.sptBrowserObj = SPTHSI_FitResultsBrowser(sptBrowserObj);
% toc
% end
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
try
%look for spt file 2 folders up
[pathName, baseFigName] = fileparts(get(h,'FileName'));
tmpIdx = strfind(baseFigName,'-');
baseName = baseFigName(1:tmpIdx(end)-1);
sptFile = fullfile(fileparts(fileparts(pathName)),[baseName '.spt']);
udata.sptBrowserObj.SptObj = SPT.loadFile(sptFile);
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
try
%look for spt file 3 folders up
sptFile = fullfile(fileparts(fileparts(fileparts(pathName))),[baseName '.spt']);
udata.sptBrowserObj.SptObj = SPT.loadFile(sptFile);
udata.sptBrowserObj.SptObj.checkDataLink;
udata.sptBrowserObj.BrowseFlag = 1;
set(hp(ii),'userdata',udata);
catch me
if isfield(udata,'sptBrowserObj')
udata = rmfield(udata,'sptBrowserObj');
set(hp(ii),'userdata',udata);
end
set(htt,'state','off') %set toggle tool state
warning('plotTrack:NoSptPlotObj','plotTrack: synchronization with sptPlot.FitResultsBrowser not available for current plot');
end
end
end
else
if isfield(udata,'sptBrowserObj')
udata.sptBrowserObj.BrowseFlag = 1;
end
end
end
function output_txt = plotTracksDataCursor(obj,event_obj)
% Display the position of the data cursor
% obj Currently not used (empty)
% event_obj Handle to event object
% output_txt Data cursor text string (string or cell array of strings).
pos = get(event_obj,'Position');
output_txt = {['X: ',num2str(pos(1),4)],...
['Y: ',num2str(pos(2),4)]};
try
% If there is a Z-coordinate in the position, display it as well
if length(pos) > 2
output_txt{end+1} = ['Z: ',num2str(pos(3),4)];
end
%get patch handle
hp = get(event_obj,'target');
if ~strcmp(get(hp,'type'),'patch') || (isempty(strfind(get(hp,'tag'),'plotTrackPatch'))...
&& isempty(strfind(get(hp,'tag'),'dipTrackLocMarker')))
output_txt = [];
return;
end
displayName = get(hp,'displayname');
if ~isempty(displayName)
output_txt{end+1} = sprintf('%s', displayName);
end
udata = get(hp,'userdata');
% find vertex index for current point
idx = get(event_obj,'dataindex');
% display trackNum
trackNum = udata.vert(idx,end);
output_txt{end+1} = sprintf('trackNum: %i', trackNum);
% If there is a Val field in userdata, display it as well
if isfield(udata,'val') && ~isempty(udata.val)
output_txt{end+1} = sprintf('Val: %.3g', udata.val(idx));
output_txt{end+1} = sprintf('meanVal: %.3g', mean(udata.val(udata.vert(:,end) == udata.vert(idx,end))));
end
% If there is a Val field in userdata, display it as well
zIdx = udata.vert(idx,end-1)/udata.t;
if isfield(udata,'subRegionModel') && ~isempty(udata.subRegionModel)
output_txt{end+1} = sprintf('boxIdxA: %i', udata.subRegionModel(trackNum,zIdx,1));
output_txt{end+1} = sprintf('boxIdxF: %i', udata.subRegionModel(trackNum,zIdx,2));
output_txt{end+1} = sprintf('model: %i', udata.subRegionModel(trackNum,zIdx,3));
output_txt{end+1} = sprintf('idx: %i', udata.subRegionModel(trackNum,zIdx,4));
end
% If there is a ID field in userdata, display it
if isfield(udata,'ID') && ~isempty(udata.ID)
if ischar(udata.ID)
output_txt{end+1} = sprintf('ID: %s', udata.ID);
else if isnumerical(udata.ID)
output_txt{end+1} = sprintf('ID: %g', udata.ID);
end
end
end
%highlight trackLines
% highlightTracks(get(event_obj,'target'),udata.vert(idx,end))
%highlight track
h = get(get(get(event_obj,'target'),'parent'),'parent');
dcm_obj = datacursormode(h);
info_cell = squeeze(struct2cell(getCursorInfo(dcm_obj)));
hLines = findall(cell2mat(info_cell(1,:)),'tag','plotTrackPatchHighlight');
if isempty(dcm_obj)
resetTracks(h);
else
if udata.highlightTracks
hpHighlight = findall(hp,'tag','plotTrackPatchHighlight');
trackNum = udata.vert(idx,end);
for ii = 1:length(hpHighlight)
udataHighlight = get(hpHighlight(ii),'userdata');
trackNum = [trackNum;udataHighlight.trackii];
end
try
highlightTracks(hp,trackNum);
catch me
output_txt{end+1} = sprintf('highlightTracks error\nmessage:%s\n',...
me.stack(end).file,me.stack(end).name,me.stack(end).line,me.message);
end
end
end
if isfield(udata,'sptBrowserObj') && isfield(udata,'subRegionModel')
%get toggle tool handle
htt = findall(h,'tag','SPTHSI:FitResultsBrowser');%check for sptBrowserObj and data linkage
if isa(udata.sptBrowserObj,'SPTHSI_FitResultsBrowser') ...
&& udata.sptBrowserObj.BrowseFlag
% && strcmp(get(htt,'state'),'on') ...
% && strcmp(get(dcm_obj,'Enable'),'on')
if zIdx ~= udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) == udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.FrameIdx = zIdx;
else if zIdx == udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) ~= udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.BoxIdx = udata.subRegionModel(trackNum,zIdx,2);
else if zIdx ~= udata.sptBrowserObj.FrameIdx ...
&& udata.subRegionModel(trackNum,zIdx,2) ~= udata.sptBrowserObj.BoxIdx
udata.sptBrowserObj.BrowseFlag = 0;
udata.sptBrowserObj.FrameIdx = zIdx;
udata.sptBrowserObj.BrowseFlag = 1;
udata.sptBrowserObj.BoxIdx = udata.subRegionModel(trackNum,zIdx,2);
% % disp(['plotTracks: updating frame ' num2str(zIdx) ' box ' num2str(udata.subRegionModel(trackNum,zIdx,2)) ' for SPTHSIplotFitResultsBrowser...'])
% % tic
% udata.sptBrowserObj.SptObj.plotFitResultsBrowser(zIdx,udata.subRegionModel(trackNum,zIdx,2));
% % toc
end
end
end
end
end
catch me
output_txt{end+1} = sprintf('plotTracksDataCursor error\nmessage:%s',...
me.stack(end).file,me.stack(end).name,me.stack(end).line,me.message);
end
|
github | carlassmith/exampleGLRT-master | isolate_axes.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/isolate_axes.m | 3,668 | utf_8 | e2dce471e433886fcb87f9dcb284a2cb | %ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m.
% 12/12/12 - Add support for isolating uipanels. Thanks to michael for
% suggesting it.
% 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!).
% 05/12/13 - Bug fix to axes having different units. Thanks to Remington
% Reid for reporting the issue.
function fh = isolate_axes(ah, vis)
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'});
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
ax_pos = get(ah, 'OuterPosition');
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
leg_pos = get(lh, 'OuterPosition');
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github | carlassmith/exampleGLRT-master | im2gif.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/im2gif.m | 6,048 | utf_8 | 5a7437140f8d013158a195de1e372737 | %IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github | carlassmith/exampleGLRT-master | pdf2eps.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/pdf2eps.m | 1,471 | utf_8 | a1f41f0c7713c73886a2323e53ed982b | %PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github | carlassmith/exampleGLRT-master | print2array.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/print2array.m | 6,270 | utf_8 | a174d717616819281a17f51e1f6584c8 | %PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2012
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the
% issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting
% the issue.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure
% size and erasemode settings. Makes it a bit slower, but more
% reliable. Thanks to Phil Trinh and Meelis Lootus for reporting
% the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting
% it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
function [A, bcol] = print2array(fig, res, renderer)
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
if nargin > 2 && strcmp(renderer, '-painters')
% Print to eps file
tmp_eps = [tempname '.eps'];
print2eps(tmp_eps, fig, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"'];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
err = false;
% Set paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
try
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
% Reset paper size
set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
% Throw any error that occurred
if err
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = [px([4 3])*res 3];
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | carlassmith/exampleGLRT-master | shadedPatchPlot.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/shadedPatchPlot.m | 2,226 | utf_8 | 545fe2fa24d52bd8308ec2d3eef5f7ec | function H=shadedPatchPlot(x,Q2,Q,lineProps,patchSaturation)
%shadedPatchPlot Creates DStorm Simlation
% SYNOPSIS:
% H=shadedPatchPlot(x,Q2,Q,lineProps,patchSaturation)
%
% PARAMETERS:
% x: x values
% Q2: main solid line (mean)
% Q: cell with patch values 2 vector with upper and lower value
% lineProps
% patchSaturation
%
% OUTPUTS:
% H Figure handle
% EXAMPLE
%
% h2 = shadedPatchPlot(t(1:end-1), Q2(2,:), ...
% {[Q1(2,:); Q3(2,:)],[NO1(2,:); NO2(2,:)]},{'r','Linewidth',2});
%
% SEE ALSO:
% plot
holdStatus = ishold;
Q2=Q2(:)';
if isempty(x)
x=1:length(Q2);
else
x=x(:)';
end
if length(x) ~= length(Q2)
error('inputs x and y are not of equal lengths')
end
defaultProps={'-k'};
if nargin<4 || isempty(lineProps)
lineProps=defaultProps;
end
if ~iscell(lineProps)
lineProps={lineProps};
end
% Main line
H.mainLine=plot(x,Q2,lineProps{:});
col=get(H.mainLine,'color');
%draw paches + edges
if nargin < 5
if length(Q) == 1
patchSaturation = 0.2;
elseif length(Q) == 2
patchSaturation = [0.2, 0.2*0.4];
else
patchSaturation= logspace(log10(0.2),log10(0.2^2),length(Q));
end
end
for ll=1:length(Q)
Q13=Q{ll};
if length(x) ~= length(Q13)
error('inputs x and y must have the same length as Q13')
end
[H.patch{ll}, uE, lE] = drawpatch(x,col,patchSaturation(ll),Q13);
edgeColor = col+(1-col)*0.25;
H.edge{ll} = drawEdge(x,lE,uE,edgeColor);
end
delete(H.mainLine);
H.mainLine=plot(x,Q2,lineProps{:});
if ~holdStatus, hold off, end
end
function edge = drawEdge(x,lE,uE,edgeColor)
edge(1)=plot(x,lE,'-','color',edgeColor);
edge(2)=plot(x,uE,'-','color',edgeColor);
end
function [Hpatch, upE, loE]= drawpatch(x,col,patchSaturation,twoVector)
faceAlpha=patchSaturation;
patchColor=col;
set(gcf,'renderer','openGL')
upE=twoVector(1,:);
loE=twoVector(2,:);
if ~ishold, hold on, end
yP=[loE,fliplr(upE)];
xP=[x,fliplr(x)];
%remove any nans otherwise patch won't work
xP(isnan(yP))=[];
yP(isnan(yP))=[];
Hpatch=patch(xP,yP,1,'facecolor',patchColor,...
'edgecolor','none',...
'facealpha',faceAlpha);
end
|
github | carlassmith/exampleGLRT-master | append_pdfs.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/append_pdfs.m | 2,010 | utf_8 | 1034abde9642693c404671ff1c693a22 | %APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
function append_pdfs(varargin)
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
if append
output = [tempname '.pdf'];
else
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
cmdfile = [tempname '.txt'];
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github | carlassmith/exampleGLRT-master | using_hg2.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/using_hg2.m | 365 | utf_8 | 6a7f56042fda1873d8225eb3ec1cc197 | %USING_HG2 Determine if the HG2 graphics pipeline is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics pipeline is being used
% (true) or not (false).
function tf = using_hg2(fig)
try
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = false;
end
end
|
github | carlassmith/exampleGLRT-master | eps2pdf.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/eps2pdf.m | 5,009 | utf_8 | 5658b3d96232e138be7fd49693d88453 | %EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
%IN:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed to
% already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale or
% not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% Copyright (C) Oliver Woodford 2009-2011
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
function eps2pdf(source, dest, crop, append, gray, quality)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
else
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github | carlassmith/exampleGLRT-master | copyfig.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/copyfig.m | 812 | utf_8 | b6b1fa9a9351df33ae0d42056c3df40a | %COPYFIG Create a copy of a figure, without changing the figure
%
% Examples:
% fh_new = copyfig(fh_old)
%
% This function will create a copy of a figure, but not change the figure,
% as copyobj sometimes does, e.g. by changing legends.
%
% IN:
% fh_old - The handle of the figure to be copied. Default: gcf.
%
% OUT:
% fh_new - The handle of the created figure.
% Copyright (C) Oliver Woodford 2012
function fh = copyfig(fh)
% Set the default
if nargin == 0
fh = gcf;
end
% Is there a legend?
if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
% Safe to copy using copyobj
fh = copyobj(fh, 0);
else
% copyobj will change the figure, so save and then load it instead
tmp_nam = [tempname '.fig'];
hgsave(fh, tmp_nam);
fh = hgload(tmp_nam);
delete(tmp_nam);
end
end
|
github | carlassmith/exampleGLRT-master | user_string.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/user_string.m | 2,460 | utf_8 | e8aa836a5140410546fceccb4cca47aa | %USER_STRING Get/set a user specific string
%
% Examples:
% string = user_string(string_name)
% saved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% IN:
% string_name - String containing the name of the string required. The
% string is extracted from a file called (string_name).txt,
% stored in the same directory as user_string.m.
% new_string - The new string to be saved under the name given by
% string_name.
%
% OUT:
% string - The currently saved string. Default: ''.
% saved - Boolean indicating whether the save was succesful
% Copyright (C) Oliver Woodford 2011-2013
% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.
% 10/01/2013 - Access files in text, not binary mode, as latter can cause
% errors. Thanks to Christian for pointing this out.
function string = user_string(string_name, string)
if ~ischar(string_name)
error('string_name must be a string.');
end
% Create the full filename
string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']);
if nargin > 1
% Set string
if ~ischar(string)
error('new_string must be a string.');
end
% Make sure the save directory exists
dname = fileparts(string_name);
if ~exist(dname, 'dir')
% Create the directory
try
if ~mkdir(dname)
string = false;
return
end
catch
string = false;
return
end
% Make it hidden
try
fileattrib(dname, '+h');
catch
end
end
% Write the file
fid = fopen(string_name, 'wt');
if fid == -1
string = false;
return
end
try
fprintf(fid, '%s', string);
catch
fclose(fid);
string = false;
return
end
fclose(fid);
string = true;
else
% Get string
fid = fopen(string_name, 'rt');
if fid == -1
string = '';
return
end
string = fgetl(fid);
fclose(fid);
end
end
|
github | carlassmith/exampleGLRT-master | export_fig.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/export_fig.m | 29,068 | utf_8 | 82ef7090addd483cfc1ce8daa936c776 | %EXPORT_FIG Exports figures suitable for publication
%
% Examples:
% im = export_fig
% [im alpha] = export_fig
% export_fig filename
% export_fig filename -format1 -format2
% export_fig ... -nocrop
% export_fig ... -transparent
% export_fig ... -native
% export_fig ... -m<val>
% export_fig ... -r<val>
% export_fig ... -a<val>
% export_fig ... -q<val>
% export_fig ... -<renderer>
% export_fig ... -<colorspace>
% export_fig ... -append
% export_fig ... -bookmark
% export_fig(..., handle)
%
% This function saves a figure or single axes to one or more vector and/or
% bitmap file formats, and/or outputs a rasterized version to the
% workspace, with the following properties:
% - Figure/axes reproduced as it appears on screen
% - Cropped borders (optional)
% - Embedded fonts (vector formats)
% - Improved line and grid line styles
% - Anti-aliased graphics (bitmap formats)
% - Render images at native resolution (optional for bitmap formats)
% - Transparent background supported (pdf, eps, png)
% - Semi-transparent patch objects supported (png only)
% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
% - Variable image compression, including lossless (pdf, eps, jpg)
% - Optionally append to file (pdf, tiff)
% - Vector formats: pdf, eps
% - Bitmap formats: png, tiff, jpg, bmp, export to workspace
%
% This function is especially suited to exporting figures for use in
% publications and presentations, because of the high quality and
% portability of media produced.
%
% Note that the background color and figure dimensions are reproduced
% (the latter approximately, and ignoring cropping & magnification) in the
% output file. For transparent background (and semi-transparent patch
% objects), use the -transparent option or set the figure 'Color' property
% to 'none'. To make axes transparent set the axes 'Color' property to
% 'none'. Pdf, eps and png are the only file formats to support a
% transparent background, whilst the png format alone supports transparency
% of patch objects.
%
% The choice of renderer (opengl, zbuffer or painters) has a large impact
% on the quality of output. Whilst the default value (opengl for bitmaps,
% painters for vector formats) generally gives good results, if you aren't
% satisfied then try another renderer. Notes: 1) For vector formats (eps,
% pdf), only painters generates vector graphics. 2) For bitmaps, only
% opengl can render transparent patch objects correctly. 3) For bitmaps,
% only painters will correctly scale line dash and dot lengths when
% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
% using painters.
%
% When exporting to vector format (pdf & eps) and bitmap format using the
% painters renderer, this function requires that ghostscript is installed
% on your system. You can download this from:
% http://www.ghostscript.com
% When exporting to eps it additionally requires pdftops, from the Xpdf
% suite of functions. You can download this from:
% http://www.foolabs.com/xpdf
%
%IN:
% filename - string containing the name (optionally including full or
% relative path) of the file the figure is to be saved as. If
% a path is not specified, the figure is saved in the current
% directory. If no name and no output arguments are specified,
% the default name, 'export_fig_out', is used. If neither a
% file extension nor a format are specified, a ".png" is added
% and the figure saved in that format.
% -format1, -format2, etc. - strings containing the extensions of the
% file formats the figure is to be saved as.
% Valid options are: '-pdf', '-eps', '-png',
% '-tif', '-jpg' and '-bmp'. All combinations
% of formats are valid.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -transparent - option indicating that the figure background is to be
% made transparent (png, pdf and eps output only).
% -m<val> - option where val indicates the factor to magnify the
% on-screen figure pixel dimensions by when generating bitmap
% outputs. Default: '-m1'.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap and vector outputs at, keeping the dimensions
% of the on-screen figure. Default: '-r864' (for vector output
% only). Note that the -m option overides the -r option for
% bitmap outputs only.
% -native - option indicating that the output resolution (when outputting
% a bitmap format) should be such that the vertical resolution
% of the first suitable image found in the figure is at the
% native resolution of that image. To specify a particular
% image to use, give it the tag 'export_fig_native'. Notes:
% This overrides any value set with the -m and -r options. It
% also assumes that the image is displayed front-to-parallel
% with the screen. The output resolution is approximate and
% should not be relied upon. Anti-aliasing can have adverse
% effects on image quality (disable with the -a1 option).
% -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
% use for bitmap outputs. '-a1' means no anti-
% aliasing; '-a4' is the maximum amount (default).
% -<renderer> - option to force a particular renderer (painters, opengl
% or zbuffer) to be used over the default: opengl for
% bitmaps; painters for vector formats.
% -<colorspace> - option indicating which colorspace color figures should
% be saved in: RGB (default), CMYK or gray. CMYK is only
% supported in pdf, eps and tiff output.
% -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
% files only). Larger val, in the range 0-100, gives higher
% quality/lower compression. val > 100 gives lossless
% compression. Default: '-q95' for jpg, ghostscript prepress
% default for pdf & eps. Note: lossless compression can
% sometimes give a smaller file size than the default lossy
% compression, depending on the type of images.
% -append - option indicating that if the file (pdfs only) already
% exists, the figure is to be appended as a new page, instead
% of being overwritten (default).
% -bookmark - option to indicate that a bookmark with the name of the
% figure is to be created in the output file (pdf only).
% handle - The handle of the figure, axes or uipanels (can be an array of
% handles, but the objects must be in the same figure) to be
% saved. Default: gcf.
%
%OUT:
% im - MxNxC uint8 image array of the figure.
% alpha - MxN single array of alphamatte values in range [0,1], for the
% case when the background is transparent.
%
% Some helpful examples and tips can be found at:
% https://github.com/ojwoodford/export_fig
%
% See also PRINT, SAVEAS.
% Copyright (C) Oliver Woodford 2008-2014
% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928).
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
% 20979).
% The idea of appending figures in pdfs came from Matt C in comments on the
% FEX (id: 23629)
% Thanks to Roland Martin for pointing out the colour MATLAB
% bug/feature with colorbar axes and transparent backgrounds.
% Thanks also to Andrew Matthews for describing a bug to do with the figure
% size changing in -nodisplay mode. I couldn't reproduce it, but included a
% fix anyway.
% Thanks to Tammy Threadgill for reporting a bug where an axes is not
% isolated from gui objects.
% 23/02/12: Ensure that axes limits don't change during printing
% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
% reporting it).
% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
% bookmarking of figures in pdf files.
% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
% tick marks fixed.
% 12/12/12: Add support for isolating uipanels. Thanks to michael for
% suggesting it.
% 25/09/13: Add support for changing resolution in vector formats. Thanks
% to Jan Jaap Meijer for suggesting it.
% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
% for suggesting it.
function [im, alpha] = export_fig(varargin)
% Make sure the figure is rendered correctly _now_ so that properties like
% axes limits are up-to-date.
drawnow;
% Parse the input arguments
[fig, options] = parse_args(nargout, varargin{:});
% Isolate the subplot, if it is one
cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
if cls
% Given handles of one or more axes, so isolate them from the rest
fig = isolate_axes(fig);
else
% Check we have a figure
if ~isequal(get(fig, 'Type'), 'figure');
error('Handle must be that of a figure, axes or uipanel');
end
% Get the old InvertHardcopy mode
old_mode = get(fig, 'InvertHardcopy');
end
% Hack the font units where necessary (due to a font rendering bug in
% print?). This may not work perfectly in all cases. Also it can change the
% figure layout if reverted, so use a copy.
magnify = options.magnify * options.aa_factor;
if isbitmap(options) && magnify ~= 1
fontu = findobj(fig, 'FontUnits', 'normalized');
if ~isempty(fontu)
% Some normalized font units found
if ~cls
fig = copyfig(fig);
set(fig, 'Visible', 'off');
fontu = findobj(fig, 'FontUnits', 'normalized');
cls = true;
end
set(fontu, 'FontUnits', 'points');
end
end
% MATLAB "feature": axes limits and tick marks can change when printing
Hlims = findall(fig, 'Type', 'axes');
if ~cls
% Record the old axes limit and tick modes
Xlims = make_cell(get(Hlims, 'XLimMode'));
Ylims = make_cell(get(Hlims, 'YLimMode'));
Zlims = make_cell(get(Hlims, 'ZLimMode'));
Xtick = make_cell(get(Hlims, 'XTickMode'));
Ytick = make_cell(get(Hlims, 'YTickMode'));
Ztick = make_cell(get(Hlims, 'ZTickMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
% Set to print exactly what is there
set(fig, 'InvertHardcopy', 'off');
% Set the renderer
switch options.renderer
case 1
renderer = '-opengl';
case 2
renderer = '-zbuffer';
case 3
renderer = '-painters';
otherwise
renderer = '-opengl'; % Default for bitmaps
end
% Do the bitmap formats first
if isbitmap(options)
% Get the background colour
if options.transparent && (options.png || options.alpha)
% Get out an alpha channel
% MATLAB "feature": black colorbar axes can change to white and vice versa!
hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar');
if isempty(hCB)
yCol = [];
xCol = [];
else
yCol = get(hCB, 'YColor');
xCol = get(hCB, 'XColor');
if iscell(yCol)
yCol = cell2mat(yCol);
xCol = cell2mat(xCol);
end
yCol = sum(yCol, 2);
xCol = sum(xCol, 2);
end
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
% Set the background colour to black, and set size in case it was
% changed internally
tcol = get(fig, 'Color');
set(fig, 'Color', 'k', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==0), 'YColor', [0 0 0]);
set(hCB(xCol==0), 'XColor', [0 0 0]);
% Print large version to array
B = print2array(fig, magnify, renderer);
% Downscale the image
B = downsize(single(B), options.aa_factor);
% Set background to white (and set size)
set(fig, 'Color', 'w', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==3), 'YColor', [1 1 1]);
set(hCB(xCol==3), 'XColor', [1 1 1]);
% Print large version to array
A = print2array(fig, magnify, renderer);
% Downscale the image
A = downsize(single(A), options.aa_factor);
% Set the background colour (and size) back to normal
set(fig, 'Color', tcol, 'Position', pos);
% Compute the alpha map
alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
A = alpha;
A(A==0) = 1;
A = B ./ A(:,:,[1 1 1]);
clear B
% Convert to greyscale
if options.colourspace == 2
A = rgb2grey(A);
end
A = uint8(A);
% Crop the background
if options.crop
[alpha, v] = crop_borders(alpha, 0, 1);
A = A(v(1):v(2),v(3):v(4),:);
end
if options.png
% Compute the resolution
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
% Save the png
imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
% Clear the png bit
options.png = false;
end
% Return only one channel for greyscale
if isbitmap(options)
A = check_greyscale(A);
end
if options.alpha
% Store the image
im = A;
% Clear the alpha bit
options.alpha = false;
end
% Get the non-alpha image
if isbitmap(options)
alph = alpha(:,:,ones(1, size(A, 3)));
A = uint8(single(A) .* alph + 255 * (1 - alph));
clear alph
end
if options.im
% Store the new image
im = A;
end
else
% Print large version to array
if options.transparent
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
tcol = get(fig, 'Color');
set(fig, 'Color', 'w', 'Position', pos);
A = print2array(fig, magnify, renderer);
set(fig, 'Color', tcol, 'Position', pos);
tcol = 255;
else
[A, tcol] = print2array(fig, magnify, renderer);
end
% Crop the background
if options.crop
A = crop_borders(A, tcol, 1);
end
% Downscale the image
A = downsize(A, options.aa_factor);
if options.colourspace == 2
% Convert to greyscale
A = rgb2grey(A);
else
% Return only one channel for greyscale
A = check_greyscale(A);
end
% Outputs
if options.im
im = A;
end
if options.alpha
im = A;
alpha = zeros(size(A, 1), size(A, 2), 'single');
end
end
% Save the images
if options.png
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
end
if options.bmp
imwrite(A, [options.name '.bmp']);
end
% Save jpeg with given quality
if options.jpg
quality = options.quality;
if isempty(quality)
quality = 95;
end
if quality > 100
imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
else
imwrite(A, [options.name '.jpg'], 'Quality', quality);
end
end
% Save tif images in cmyk if wanted (and possible)
if options.tif
if options.colourspace == 1 && size(A, 3) == 3
A = double(255 - A);
K = min(A, [], 3);
K_ = 255 ./ max(255 - K, 1);
C = (A(:,:,1) - K) .* K_;
M = (A(:,:,2) - K) .* K_;
Y = (A(:,:,3) - K) .* K_;
A = uint8(cat(3, C, M, Y, K));
clear C M Y K K_
end
append_mode = {'overwrite', 'append'};
imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
end
end
% Now do the vector formats
if isvector(options)
% Set the default renderer to painters
if ~options.renderer
renderer = '-painters';
end
% Generate some filenames
tmp_nam = [tempname '.eps'];
if options.pdf
pdf_nam = [options.name '.pdf'];
else
pdf_nam = [tempname '.pdf'];
end
% Generate the options for print
p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
if options.colourspace == 1
p2eArgs = [p2eArgs {'-cmyk'}];
end
if ~options.crop
p2eArgs = [p2eArgs {'-loose'}];
end
try
% Generate an eps
print2eps(tmp_nam, fig, p2eArgs{:});
% Remove the background, if desired
if options.transparent && ~isequal(get(fig, 'Color'), 'none')
eps_remove_background(tmp_nam, 1 + using_hg2(fig));
end
% Add a bookmark to the PDF if desired
if options.bookmark
fig_nam = get(fig, 'Name');
if isempty(fig_nam)
warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
end
add_bookmark(tmp_nam, fig_nam);
end
% Generate a pdf
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
catch ex
% Delete the eps
delete(tmp_nam);
rethrow(ex);
end
% Delete the eps
delete(tmp_nam);
if options.eps
try
% Generate an eps from the pdf
pdf2eps(pdf_nam, [options.name '.eps']);
catch ex
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
rethrow(ex);
end
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
end
end
if cls
% Close the created figure
close(fig);
else
% Reset the hardcopy mode
set(fig, 'InvertHardcopy', old_mode);
% Reset the axes limit and tick modes
for a = 1:numel(Hlims)
set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
end
end
end
function [fig, options] = parse_args(nout, varargin)
% Parse the input arguments
% Set the defaults
fig = get(0, 'CurrentFigure');
options = struct('name', 'export_fig_out', ...
'crop', true, ...
'transparent', false, ...
'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
'pdf', false, ...
'eps', false, ...
'png', false, ...
'tif', false, ...
'jpg', false, ...
'bmp', false, ...
'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
'append', false, ...
'im', nout == 1, ...
'alpha', nout == 2, ...
'aa_factor', 0, ...
'magnify', [], ...
'resolution', [], ...
'bookmark', false, ...
'quality', []);
native = false; % Set resolution to native of an image
% Go through the other arguments
for a = 1:nargin-1
if all(ishandle(varargin{a}))
fig = varargin{a};
elseif ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
switch lower(varargin{a}(2:end))
case 'nocrop'
options.crop = false;
case {'trans', 'transparent'}
options.transparent = true;
case 'opengl'
options.renderer = 1;
case 'zbuffer'
options.renderer = 2;
case 'painters'
options.renderer = 3;
case 'pdf'
options.pdf = true;
case 'eps'
options.eps = true;
case 'png'
options.png = true;
case {'tif', 'tiff'}
options.tif = true;
case {'jpg', 'jpeg'}
options.jpg = true;
case 'bmp'
options.bmp = true;
case 'rgb'
options.colourspace = 0;
case 'cmyk'
options.colourspace = 1;
case {'gray', 'grey'}
options.colourspace = 2;
case {'a1', 'a2', 'a3', 'a4'}
options.aa_factor = str2double(varargin{a}(3));
case 'append'
options.append = true;
case 'bookmark'
options.bookmark = true;
case 'native'
native = true;
otherwise
val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
if ~isscalar(val)
error('option %s not recognised', varargin{a});
end
switch lower(varargin{a}(2))
case 'm'
options.magnify = val;
case 'r'
options.resolution = val;
case 'q'
options.quality = max(val, 0);
end
end
else
[p, options.name, ext] = fileparts(varargin{a});
if ~isempty(p)
options.name = [p filesep options.name];
end
switch lower(ext)
case {'.tif', '.tiff'}
options.tif = true;
case {'.jpg', '.jpeg'}
options.jpg = true;
case '.png'
options.png = true;
case '.bmp'
options.bmp = true;
case '.eps'
options.eps = true;
case '.pdf'
options.pdf = true;
otherwise
options.name = varargin{a};
end
end
end
end
% Set default anti-aliasing now we know the renderer
if options.aa_factor == 0
options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(fig, 'GraphicsSmoothing'), 'on')) | (options.renderer == 3));
end
% Convert user dir '~' to full path
if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
end
% Compute the magnification and resolution
if isempty(options.magnify)
if isempty(options.resolution)
options.magnify = 1;
options.resolution = 864;
else
options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
end
elseif isempty(options.resolution)
options.resolution = 864;
end
% Check we have a figure handle
if isempty(fig)
error('No figure found');
end
% Set the default format
if ~isvector(options) && ~isbitmap(options)
options.png = true;
end
% Check whether transparent background is wanted (old way)
if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
options.transparent = true;
end
% If requested, set the resolution to the native vertical resolution of the
% first suitable image found
if native && isbitmap(options)
% Find a suitable image
list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native');
if isempty(list)
list = findobj(fig, 'Type', 'image', 'Visible', 'on');
end
for hIm = list(:)'
% Check height is >= 2
height = size(get(hIm, 'CData'), 1);
if height < 2
continue
end
% Account for the image filling only part of the axes, or vice
% versa
yl = get(hIm, 'YData');
if isscalar(yl)
yl = [yl(1)-0.5 yl(1)+height+0.5];
else
if ~diff(yl)
continue
end
yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
end
hAx = get(hIm, 'Parent');
yl2 = get(hAx, 'YLim');
% Find the pixel height of the axes
oldUnits = get(hAx, 'Units');
set(hAx, 'Units', 'pixels');
pos = get(hAx, 'Position');
set(hAx, 'Units', oldUnits);
if ~pos(4)
continue
end
% Found a suitable image
% Account for stretch-to-fill being disabled
pbar = get(hAx, 'PlotBoxAspectRatio');
pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
% Set the magnification to give native resolution
options.magnify = (height * diff(yl2)) / (pos * diff(yl));
break
end
end
end
function A = downsize(A, factor)
% Downsample an image
if factor == 1
% Nothing to do
return
end
try
% Faster, but requires image processing toolbox
A = imresize(A, 1/factor, 'bilinear');
catch
% No image processing toolbox - resize manually
% Lowpass filter - use Gaussian as is separable, so faster
% Compute the 1d Gaussian filter
filt = (-factor-1:factor+1) / (factor * 0.6);
filt = exp(-filt .* filt);
% Normalize the filter
filt = single(filt / sum(filt));
% Filter the image
padding = floor(numel(filt) / 2);
for a = 1:size(A, 3)
A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
end
% Subsample
A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
end
end
function A = rgb2grey(A)
A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
end
function A = check_greyscale(A)
% Check if the image is greyscale
if size(A, 3) == 3 && ...
all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
all(reshape(A(:,:,2) == A(:,:,3), [], 1))
A = A(:,:,1); % Save only one channel for 8-bit output
end
end
function eps_remove_background(fname, count)
% Remove the background of an eps file
% Open the file
fh = fopen(fname, 'r+');
if fh == -1
error('Not able to open file %s.', fname);
end
% Read the file line by line
while count
% Get the next line
l = fgets(fh);
if isequal(l, -1)
break; % Quit, no rectangle found
end
% Check if the line contains the background rectangle
if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
% Set the line to whitespace and quit
l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
fseek(fh, -numel(l), 0);
fprintf(fh, l);
% Reduce the count
count = count - 1;
end
end
% Close the file
fclose(fh);
end
function b = isvector(options)
b = options.pdf || options.eps;
end
function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
end
% Helper function
function A = make_cell(A)
if ~iscell(A)
A = {A};
end
end
function add_bookmark(fname, bookmark_text)
% Adds a bookmark to the temporary EPS file after %%EndPageSetup
% Read in the file
fh = fopen(fname, 'r');
if fh == -1
error('File %s not found.', fname);
end
try
fstrm = fread(fh, '*char')';
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
% Include standard pdfmark prolog to maximize compatibility
fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
% Add page bookmark
fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
error('Unable to open %s for writing.', fname);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github | carlassmith/exampleGLRT-master | ghostscript.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/ghostscript.m | 5,009 | utf_8 | e93de4034ac6e4ac154729dc2c12f725 | %GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2013
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Nathan Childress for the fix to the default location on 64-bit
% Windows systems.
% 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 4/5/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
function varargout = ghostscript(cmd)
% Initialize any required system calls before calling ghostscript
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Call ghostscript
[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while 1
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep];
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'));
return
end
end
function good = check_gs_path(path_)
% Check the path is valid
shell_cmd = '';
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
good = good == 0;
end
|
github | carlassmith/exampleGLRT-master | dipSubLoc2D.m | .m | exampleGLRT-master/helperfunctions/plotHelpers/dipSubLoc2D.m | 6,485 | utf_8 | 51b0c2b3c02ec4b7b16d49c1ead9f4c7 | function varargout = dipSubLoc2D(varargin)
% dipSubLoc2D plot subregions and localizations
%
% USAGE:
% h = dipSubLoc2D(options); %setup dipSubLoc2D figure
% h = dipSubLoc2D(fh); %setup listener for dipSubLoc2D figure
%
% Peter UNM v1
% Carlas UMASSMED v2 (added matlab 2015 support)
if nargin > 2
error('dipSubLoc2D:ToManyInputs','dipSubLoc2D: 0 to 2 inputs required');
end
switch nargin
case 0
options = dipSubLoc2DSetOptions;
case 1
if ishandle(varargin{1})
h = varargin{1};
udata = get(h,'userdata');
if isfield(udata,'dipSubLoc2DData')
udata.dipSubLoc2DData.h = h;
addlistener(udata.dipSubLoc2DData.h,'UserData','PostSet',@curslice);
set(h,'userdata',udata);
return;
else
error('dipSubLoc2D:InputMustBeDipTrack','dipSubLoc2D: input figure must be initialized using dipSubLoc2D')
end
end
options = varargin{1};
end
%initilize figure
if isempty(options.h)
h = figure;
else
h = options.h;
end
%show image
if isempty(options.im)
warning('dipSubLoc2D:NoIm','dipSubLoc2D: options.im is empty initializing with newim(256,256,10)')
if ~isempty(options.BoxCenters)
dipshow(h,newim(256,256,max(options.BoxCenters(:,3))),'lin');
else
dipshow(h,newim(256,256,10),'lin');
end
else
dipshow(h,options.im,'lin');
end
%initialize dipData
dipSubLoc2DData.BoxCenters = options.BoxCenters;
dipSubLoc2DData.BoxSize = options.BoxSize;
dipSubLoc2DData.BoxColor = options.BoxColor;
dipSubLoc2DData.plotBoxes = options.plotBoxes;
dipSubLoc2DData.fitCoords = options.fitCoords;
dipSubLoc2DData.fitCoordsMarker = options.fitCoordsMarker;
dipSubLoc2DData.fitColor = options.fitColor;
dipSubLoc2DData.markersize = options.markersize;
dipSubLoc2DData.linewidth = options.linewidth;
dipSubLoc2DData.h = h;
dipSubLoc2DData.ha = findall(h,'type','axes');
dipSubLoc2DData.dipTrackObj = dipTrackObj(0);
%add dipSubLoc2DData to userdata
udata = get(h,'userdata');
udata.dipSubLoc2DData = dipSubLoc2DData;
set(h,'userdata',udata);
%add listener
addlistener(udata.dipSubLoc2DData.h,'UserData','PostSet',@curslice);
dipmapping(h,'slice',1);
dipmapping(h,'slice',0);
%output figure handle
if nargout == 1
varargout{1} = h;
end
function update_boxes(udata)
%update boxes for subregions in dipSubLoc2D figure
%don't update if slice is the same
if isempty(udata.slicing) || isempty(udata.dipSubLoc2DData.BoxCenters)
return;
end
%find boxes in current slice
boxIdx = find(udata.dipSubLoc2DData.BoxCenters(:,3) == udata.curslice);
%random color scheme
if isempty(udata.dipSubLoc2DData.BoxColor)
cTmp = jet(length(boxIdx));
[v idx] = sort(rand(size(boxIdx)));
c = cTmp(idx,:);
else if ~size(udata.dipSubLoc2DData.BoxColor,1)
c = repmat(udata.dipSubLoc2DData.BoxColor,[length(boxIdx) 1]);
else
c = udata.dipSubLoc2DData.BoxColor(boxIdx,:);
end
end
%delete all current boxes
delete(findall(udata.dipSubLoc2DData.ha,'tag','plotBox'));
delete(findall(udata.dipSubLoc2DData.ha,'tag','dipTrackLocMarker'));
if udata.dipSubLoc2DData.plotBoxes && ~isempty(udata.dipSubLoc2DData.BoxCenters)
%plot boxes
plotBox(udata.dipSubLoc2DData.BoxCenters(boxIdx,1),udata.dipSubLoc2DData.BoxCenters(boxIdx,2),...
c,udata.dipSubLoc2DData.BoxSize(1),udata.dipSubLoc2DData.BoxSize(2),udata.dipSubLoc2DData.linewidth,...
udata.dipSubLoc2DData.ha);
end
if udata.dipSubLoc2DData.fitCoordsMarker && ~isempty(udata.dipSubLoc2DData.fitCoords)
if isempty(udata.dipSubLoc2DData.fitColor)
for ii = 1:length(boxIdx)
fitIdx = find(udata.dipSubLoc2DData.fitCoords(:,3) == boxIdx(ii));
for jj = 1:length(fitIdx)
%plot fit coordinates
plotLocMarker(udata.dipSubLoc2DData.fitCoords(fitIdx(jj),1),udata.dipSubLoc2DData.fitCoords(fitIdx(jj),2),...
c(ii,:),udata.dipSubLoc2DData.markersize,udata.dipSubLoc2DData.ha)
end
end
else
for ii = 1:length(boxIdx)
fitIdx = find(udata.dipSubLoc2DData.fitCoords(:,3) == boxIdx(ii));
c = udata.dipSubLoc2DData.fitColor(fitIdx,:);
for jj = 1:length(fitIdx)
%plot fit coordinates
plotLocMarker(udata.dipSubLoc2DData.fitCoords(fitIdx(jj),1),udata.dipSubLoc2DData.fitCoords(fitIdx(jj),2),...
c(jj,:),udata.dipSubLoc2DData.markersize,udata.dipSubLoc2DData.ha)
end
end
end
end
function curslice(h,evnt)
%check updating of curslice field in userdata
%get userdata
if isobject(evnt)
udata = get(evnt.AffectedObject,'UserData');
else
udata = get(evnt,'NewValue');
end
%get current slice
if isfield(udata,'curslice') && udata.dipSubLoc2DData.dipTrackObj.slice ~= udata.curslice
udata.dipSubLoc2DData.dipTrackObj.slice = udata.curslice; %update slice property
update_boxes(udata); %update figure
% set(udata.dipTrackData.h,'userdata',udata)
end
function h = plotBox(x,y,c,w,h,lw,ha)
% PLOTBOX add box around a given coordinate
%
% h = plotBox(x,y,c,w,h,lw)
%
% INPUTS
% x - x coordinate(s)
% y - y coordinate(s)
% c - color of box
% w - width of box
% h - height of box
% lw - linewidth
% ha - axes handle
% OUTPUT
% h - handle for line object
%
% Created by Pat Cutler October 2009
if size(c == 1)
c = repmat(c,[size(x,1) 1]);
end
distx = w/2;
disty = h/2;
if size(x,1) == 1
x = shiftdim(x);
y = shiftdim(y);
end
xc = [x-distx x+distx x+distx x-distx x-distx];
yc = [y+disty y+disty y-disty y-disty y+disty];
% h = line(xc,yc,'color',c,'linewidth',lw,'parent',ha);
hold on
for ii = 1:length(x)
h(ii) = line(xc(ii,:),yc(ii,:),'color',c(ii,:),'linewidth',lw,'parent',ha,'tag','plotBox');
end
hold off
function plotLocMarker(x,y,c,markersize,ha)
%plot localization marker
line(x,y,...
'marker','o','color',c*0.8,'markersize',markersize(1),...
'tag','dipTrackLocMarker','parent',ha);
line(x,y,...
'marker','o','color',c*0.6,'markersize',markersize(2),...
'markerfacecolor',c*.3,'tag','dipTrackLocMarker','parent',ha);
% hold(ha,'on')
% scatter(ha,x,y,...
% markersize(1),c,'filled','marker','o',...
% 'markeredgecolor',[1 1 1],'tag','dipTrackLocMarker');
% scatter(ha,x,y,...
% markersize(2),c,'filled','marker','o',...
% 'markeredgecolor',[0 0 0],'tag','dipTrackLocMarker');
% hold(ha,'off') |
github | carlassmith/exampleGLRT-master | RWLSPoisson.m | .m | exampleGLRT-master/helperfunctions/pfo/RWLSPoisson.m | 1,477 | utf_8 | 72c16ac8a590ca49b790f80952f46bb2 | % [o,s]=RWLSPoisson(x,y,N) : Poisson Reweighted Least Square fit, linear regression with error according to the Poisson distribution. Fits a straight line with offset.
% x : vector of x-values, known postions at which was measured.
% y : vector y-values, measurements.
% N : optional number of measurements from which y was obtained by averaging
%
% This routine is based on the Wikipedia description at
% https://en.wikipedia.org/wiki/Linear_regression
% (Xt Omega-1 X)^-1 Xt Omega^-1 Y
%
% Example:
% [o,s]=RWLSPoisson([1 2 3 4],[7 8 9 11])
%
function [o,s,vv]=RWLSPoisson(x,y,N)
if nargin < 3
N=1;
end
myThresh=1.0; % roughly determined by a simulation
NumIter=5;
v=y; % variances of data is equal (or proportional) to the measured variances
for n=1:NumIter
vv = v.^2 ./ N; % Variance of the variance. The error of the variance is proportional to the square of the variance, see http://math.stackexchange.com/questions/1015215/standard-error-of-sample-variance
if any(v<myThresh)
vv(v<myThresh)=myThresh; % This is to protect agains ADU-caused bias, which is NOT reduced by averaging
%if (n==1)
% warning('The data has a variance below 2 ADUs at low signal level. This leads to unwanted biases. Increasing the variance estimation for the fit.\n');
%end
end
[o,s]=GLS(x,y,vv);
v=o+s*x; % predict variances from the fit for the next round
%fprintf('RWLSPoisson Iteration %d, o: %g, s: %g\n',n,o,s);
end
|
github | carlassmith/exampleGLRT-master | pcfo.m | .m | exampleGLRT-master/helperfunctions/pfo/pcfo.m | 4,565 | utf_8 | 32d4dd25edc6f2900744356aa2ff9e2b | % PCFO = Calculates the photon conversion factor as well as the ADU offset
% from one image only
%
% SYNOPSIS:
% [gain, offset] = pcfo(in, k_thres, RNStd, AvoidCross, doPlot, Tiles)
%
% k_thres: spatial frequencies k>k_thres are used for noise computation
% in the discrete Fourier domain.
% Possible values [0, sqrt(2)] as the 'corners' of a rectangular image have freq > 1
% k_thres is specified as a fraction of the maximal sampling frequency in the Fourier Domain.
% RNStd : camera readout noise std in ADUs. I.e. the StdDev of a dark image.
% AvoidCross: Binary flag stating whether the X- and Y-only frequencies should be avoided.
% doPlot: Plot the noise fit for offset determination
% Tiles: [nx ny] number of tiles to use in each direction
%
% DEFAULTS:
% k_thres = 0.9
% RNStd = 0;
% AvoidCross = 1
% doPlot = 0
% Tiles = [3 3]
%
% EXAMPLE:
% a = readim;
% psf = gaussf(deltaim,2);%not really a point spread function of a microscope
% ap = convolve(a,psf);
% apn = noise(ap,'poisson',1,0)*3.8 + 50;
% [g,o] = pcfo(apn)
%
% LITERATURE:
% R. Heintzmann, P. Relich, R. Nieuwenhuizen, K. Lidke, B. Rieger,
% Calibrating photon counts from a single image, submitted
%
% Requires matlab toolbox DIPimage to run (free academic download from www.diplib.org)
% (C) Copyright 2004-2016
% All rights reserved Faculty of Applied Sciences
% Delft University of Technology
% Delft, The Netherlands
% &
% Institute of Physical Chemistry,
% Friedrich Schiller University,
% Jena, Germany
% Bernd Rieger & Rainer Heintzmann
function [gain, offset] = pcfo(in, kthres, RNStd, AvoidCross, doPlot, Tiles)
if nargin <2; kthres = 0.9; end
if nargin <3; RNStd = 0;end
if nargin <4; AvoidCross = 1;end
if nargin <5; doPlot =0;end
if nargin <6; Tiles = 3;end
if numel(Tiles)==1;Tiles(2)=Tiles(1);end
TilesX = Tiles(1);
TilesY = Tiles(2);
% test if DIPimage is installed
o = which('readim');
if isempty(o)
error('DIPimage not installed or not on the path.');
end
if ~isa(in,'dip_image'); in=mat2im(in); end
if ndims(in)>2
in=squeeze(in);
end
%% this part computes the noise variance and sum intensites per tile
n = 1;
for ty=0:TilesY-1
for tx=0:TilesX-1
xStart = floor((tx*imsize(in,1))/TilesX);
xEnd = floor(((tx+1)*imsize(in,1))/TilesX)-1;
yStart = floor((ty*imsize(in,2))/TilesY);
yEnd = floor(((ty+1)*imsize(in,2))/TilesY)-1;
myTile = in(xStart:xEnd,yStart:yEnd);
if (prod(size(myTile)) > 0) %just in case, should not happen
NumPixelsInBin(n) = prod(size(myTile));
[TotalVar(n), TotalInt(n)] = noisevariance(myTile, kthres, AvoidCross); % this does not need any information on offset or readout noise
n=n+1;
end
end
end
%% linear regression on the mean-variance plot to find the variance offset
maxFitBin = n-1;%range for the linear regression
[Voffset, slope, vv] = RWLSPoisson(TotalInt(1:maxFitBin), TotalVar(1:maxFitBin), NumPixelsInBin(1:maxFitBin)); % iteratively updates the variance of the variance estimate
offset = -Voffset/slope; % Use result from the fit, mapped into the offset along x where variance is zero
%% compute the noise variance on the full image, correct for the variance offset to find the gain
[AllTotalVar, AllTotalInt] = noisevariance(in, kthres, AvoidCross);
gain = (AllTotalVar-Voffset)/AllTotalInt; % Estimate this again from the whole image to reduce the tile effect
offset = RNStd^2/gain + offset; % account for the readout noise effect
%%
if doPlot
offset2 = TotalInt(1) - TotalVar(1)/slope; % The point on the x-axis where the variance is zero
figure
plot(TotalInt,TotalVar,'b*');hold on;
myYFit=(TotalInt-offset)*slope;
plot(TotalInt,myYFit,'r')
plot(TotalInt,myYFit-sqrt(vv),'r:')
plot(TotalInt,myYFit+sqrt(vv),'r:')
g=gca;
set(g,'FontSize',12)
xlabel('Mean Intensity [ADU]');
ylabel('Noise Variance [ADU]');
title('Mean Variance Plot');
s=sprintf('offset: %0.4g ADU\nslope: %0.2g',offset2,slope);
ax = axis;
axis([0 ax(2) 0 ax(4)])
text(ax(2)/10,ax(4)*0.8,s,'FontSize',11)
hold off
drawnow;
fprintf('offset: %0.4g ADU, slope: %0.2g\n',offset2,slope); % show what the fit results into
end
return;
|
github | carlassmith/exampleGLRT-master | noisevariance.m | .m | exampleGLRT-master/helperfunctions/pfo/noisevariance.m | 2,707 | utf_8 | 726708f4372756e8ceeb5bab655c9042 | % NOISEVARIANEC = Calculates the noise variance and mean intensity for an image
%
% SYNOPSIS:
% [noisevariance, sumintensity] = noisevariance(in, kthres, AvoidCross)
%
% kthres: frequencies that should be cut away
% in the high pass filtering [0, sqrt(dimension of in)]
% the 'corners' of the rectangular image have freq > 1
%
% DEFAULTS:
% kthres = .9
% AvoidCross =1
%
% SEE ALSO
% pcfo
%
% LITERATURE:
% R. Heintzmann, P. Relich, R. Nieuwenhuizen, K. Lidke, B. Rieger,
% Calibrating photon counts from a single image, submitted
%
% Requires matlab toolbox DIPimage to run (free academic download from www.diplib.org)
% (C) Copyright 2004-2016
% All rights reserved Faculty of Applied Sciences
% Delft University of Technology
% Delft, The Netherlands
% &
% Institute of Physical Chemistry,
% Friedrich Schiller University,
% Jena, Germany
% Bernd Rieger & Rainer Heintzmann
function [TotalVar, ImgSum] = noisevariance(in, kthres, AvoidCross)
borderfraction=0.05; % real space fraction of pixels to be used. This can avoid some residual artefacts near the border.
CrossWidth=3; % Width of pixels +/- to avoid in the cross
if ~isa(in,'dip_image');
in = mat2im(in);
end
if ndims(in)>2
in = squeeze(in);
if ndims(in)>2; error('Input image must be 2D.');end
end
if nargin < 3
AvoidCross = 1;
end
if nargin <2
kthres =.9;
else
if kthres <0 | kthres >sqrt(ndims(in))
error('kcut in [0,sqrt(dimensions of in)]');
end
end
inOriginal = in;
in = symmetrize(in); %flip and mirror the input to avoid boundary effects in the DFT
f = ft(in);
m = rr(in)>(kthres*size(in,1)/2); % mask for high-frequency region
if (AvoidCross) % introduce the blocked regions anyway
m(abs(xx(m)) <=CrossWidth)=0;
m(abs(yy(m)) <=CrossWidth)=0;
end
% make the masks smooth to avoid too extensive spreading in real space. Seems to yield a small advantage for the mean value.
m=real(gaussf(m,[CrossWidth CrossWidth]/4));
fra = sum(m)/prod(size(m)); % fraction of all pixels in high-pass filter
nf = m.*f; % filtered result
nf=ift(nf); % Not needed any longer, as the power spectral energy can just as well be measured in Fourier space.
amask=newim(inOriginal);
myborder=round(borderfraction/2*size(amask));
amask(myborder(1):end-myborder(1),myborder(2):end-myborder(2))=1;
amaskBig=symmetrize(amask);
TotalVar = mean(abssqr(nf),amaskBig)/fra;
ImgSum = mean(inOriginal,amask);
return;
|
github | carlassmith/exampleGLRT-master | GLS.m | .m | exampleGLRT-master/helperfunctions/pfo/GLS.m | 942 | utf_8 | 3705a3279835f07e722ec49cd1fe6e9b | % [o,s]=GLS(x,y,v) : Generalized Least Square fit, linear regression with error. Fits a straight line with offset through data with known variances.
% x : vector of x-values, known postions at which was measured.
% y : vector y-values, measurements.
% v : vector of known errors. These can also be estimated, but if you have a model, use RWLS, the reweighted least squares regression.
% Specifically look at RWLSPoisson if this fitting is for Poisson statistics.
% o : offset = y-value at zero x-value
% s : slope
%
% This routine is based on the Wikipedia description at
% https://en.wikipedia.org/wiki/Linear_regression
% (Xt Omega-1 X)^-1 Xt Omega^-1 Y
%
% Example:
% [o,s]=GLS([1 2 3 4],[7 8 9 11],[1 1 1 1])
%
function [o,s]=GLS(x,y,v)
X=transpose([ones(1,size(x,2));x]);
Xt=transpose(X);
Omega_X=transpose([1./v;x./v]);
Omega_Y=transpose(y./v);
ToInvert = (Xt * Omega_X);
res=inv(ToInvert)*(Xt*Omega_Y);
o=res(1);
s=res(2);
|
github | carlassmith/exampleGLRT-master | dipwatershed.m | .m | exampleGLRT-master/helperfunctions/detectionHelpers/dipwatershed.m | 3,697 | utf_8 | 4139aaa0ed5cd749b8c912d179862057 | %WATERSHED Watershed
%
% SYNOPSIS:
% image_out = watershed(image_in,connectivity,max_depth,max_size)
%
% PARAMETERS:
% connectivity: defines which pixels are considered neighbours: up to
% 'connectivity' coordinates can differ by maximally 1. Thus:
% * A connectivity of 1 indicates 4-connected neighbours in a 2D image
% and 6-connected in 3D.
% * A connectivity of 2 indicates 8-connected neighbourhood in 2D, and
% 18 in 3D.
% * A connectivity of 3 indicates a 26-connected neighbourhood in 3D.
% Connectivity can never be larger than the image dimensionality.
% max_depth, max_size: determine merging of regions.
% A region up to 'max_size' pixels and up to 'max_depth' grey-value
% difference will be merged.
%
% DEFAULTS:
% connectivity = 1
% max_depth = 0 (only merging within plateaus)
% max_size = 0 (any size)
%
% NOTE:
% If there are plateaus in the image (regions with constant grey-value),
% this function will produce poor results. A more correct watershed
% algorithm (albeit slower) is
% seeds = minima(image_in,connectivity,0);
% image_out = waterseed(seeds,image_in,connectivity,max_depth,max_size);
%
% NOTE 2:
% This algorithm skips all edge pixels, marking them as watershed pixels.
% The seeded watershed algorithm WATERSEED does not do this (and hence is
% slower).
%
% NOTE 3:
% Pixels in IMAGE_IN with a value of +INF are not processed, and will be
% marked as watershed pixels. Use this to mask out parts of the image you
% don't need processed.
%
% SEE ALSO:
% waterseed
% (C) Copyright 1999-2008 Pattern Recognition Group
% All rights reserved Faculty of Applied Physics
% Delft University of Technology
% Lorentzweg 1
% 2628 CJ Delft
% The Netherlands
%
% Cris Luengo, July 2001.
% 17 February 2005 - Added some comments to the help.
% 23 July 2008 - Added information on MINIMA and WATERSEED.
% 11 November 2009 - Added masking of +Inf pixels.
function image_out = watershed(varargin)
d = struct('menu','Segmentation',...
'display','Watershed',...
'inparams',struct('name', {'image_in', 'connectivity','max_depth', 'max_size'},...
'description',{'Input image','Connectivity','Maximum depth for merging','Maximum size for merging'},...
'type', {'image', 'array', 'array', 'array'},...
'dim_check', {0, 0, 0, 0},...
'range_check',{[], 'N+', 'R+', 'N'},...
'required', {1, 0, 0, 0},...
'default', {'a', 1, 0, 0}...
),...
'outparams',struct('name',{'image_out'},...
'description',{'Output image'},...
'type',{'image'}...
)...
);
if nargin == 1
s = varargin{1};
if ischar(s) & strcmp(s,'DIP_GetParamList')
image_out = d;
return
end
end
try
[image_in,connectivity,max_depth,max_size] = getparams(d,varargin{:});
catch
if ~isempty(paramerror)
error(paramerror)
else
error(firsterr)
end
end
mask = image_in<Inf;
image_out = dip_watershed(image_in,mask,connectivity,max_depth,max_size,1);
|
github | carlassmith/exampleGLRT-master | fdr_bh.m | .m | exampleGLRT-master/helperfunctions/detectionHelpers/fdr_bh.m | 6,427 | utf_8 | a6dc360cecf3d9af00aac66faa445497 | % fdr_bh() - Executes the Benjamini & Hochberg (1995) and the Benjamini &
% Yekutieli (2001) procedure for controlling the false discovery
% rate (FDR) of a family of hypothesis tests. FDR is the expected
% proportion of rejected hypotheses that are mistakenly rejected
% (i.e., the null hypothesis is actually true for those tests).
% FDR is a somewhat less conservative/more powerful method for
% correcting for multiple comparisons than procedures like Bonferroni
% correction that provide strong control of the family-wise
% error rate (i.e., the probability that one or more null
% hypotheses are mistakenly rejected).
%
% Usage:
% >> [h, crit_p, adj_p]=fdr_bh(pvals,q,method,report);
%
% Required Input:
% pvals - A vector or matrix (two dimensions or more) containing the
% p-value of each individual test in a family of tests.
%
% Optional Inputs:
% q - The desired false discovery rate. {default: 0.05}
% method - ['pdep' or 'dep'] If 'pdep,' the original Bejnamini & Hochberg
% FDR procedure is used, which is guaranteed to be accurate if
% the individual tests are independent or positively dependent
% (e.g., Gaussian variables that are positively correlated or
% independent). If 'dep,' the FDR procedure
% described in Benjamini & Yekutieli (2001) that is guaranteed
% to be accurate for any test dependency structure (e.g.,
% Gaussian variables with any covariance matrix) is used. 'dep'
% is always appropriate to use but is less powerful than 'pdep.'
% {default: 'pdep'}
% report - ['yes' or 'no'] If 'yes', a brief summary of FDR results are
% output to the MATLAB command line {default: 'no'}
%
%
% Outputs:
% h - A binary vector or matrix of the same size as the input "pvals."
% If the ith element of h is 1, then the test that produced the
% ith p-value in pvals is significant (i.e., the null hypothesis
% of the test is rejected).
% crit_p - All uncorrected p-values less than or equal to crit_p are
% significant (i.e., their null hypotheses are rejected). If
% no p-values are significant, crit_p=0.
% adj_p - All adjusted p-values less than or equal to q are significant
% (i.e., their null hypotheses are rejected). Note, adjusted
% p-values can be greater than 1.
%
%
% References:
% Benjamini, Y. & Hochberg, Y. (1995) Controlling the false discovery
% rate: A practical and powerful approach to multiple testing. Journal
% of the Royal Statistical Society, Series B (Methodological). 57(1),
% 289-300.
%
% Benjamini, Y. & Yekutieli, D. (2001) The control of the false discovery
% rate in multiple testing under dependency. The Annals of Statistics.
% 29(4), 1165-1188.
%
% Example:
% [dummy p_null]=ttest(randn(12,15)); %15 tests where the null hypothesis
% %is true
% [dummy p_effect]=ttest(randn(12,5)+1); %5 tests where the null
% %hypothesis is false
% [h crit_p adj_p]=fdr_bh([p_null p_effect],.05,'pdep','yes');
%
%
% For a review on false discovery rate control and other contemporary
% techniques for correcting for multiple comparisons see:
%
% Groppe, D.M., Urbach, T.P., & Kutas, M. (2011) Mass univariate analysis
% of event-related brain potentials/fields I: A critical tutorial review.
% Psychophysiology, 48(12) pp. 1711-1725, DOI: 10.1111/j.1469-8986.2011.01273.x
% http://www.cogsci.ucsd.edu/~dgroppe/PUBLICATIONS/mass_uni_preprint1.pdf
%
%
% Author:
% David M. Groppe
% Kutaslab
% Dept. of Cognitive Science
% University of California, San Diego
% March 24, 2010
%%%%%%%%%%%%%%%% REVISION LOG %%%%%%%%%%%%%%%%%
%
% 5/7/2010-Added FDR adjusted p-values
% 5/14/2013- D.H.J. Poot, Erasmus MC, improved run-time complexity
function [h crit_p adj_p]=fdr_bh(pvals,q,method,report)
if nargin<1,
error('You need to provide a vector or matrix of p-values.');
else
if ~isempty(find(pvals<0,1)),
error('Some p-values are less than 0.');
elseif ~isempty(find(pvals>1,1)),
error('Some p-values are greater than 1.');
end
end
if nargin<2,
q=.05;
end
if nargin<3,
method='pdep';
end
if nargin<4,
report='no';
end
s=size(pvals);
if (length(s)>2) || s(1)>1,
[p_sorted, sort_ids]=sort(reshape(pvals,1,prod(s)));
else
%p-values are already a row vector
[p_sorted, sort_ids]=sort(pvals);
end
[dummy, unsort_ids]=sort(sort_ids); %indexes to return p_sorted to pvals order
m=length(p_sorted); %number of tests
if strcmpi(method,'pdep'),
%BH procedure for independence or positive dependence
thresh=(1:m)*q/m;
wtd_p=m*p_sorted./(1:m);
elseif strcmpi(method,'dep')
%BH procedure for any dependency structure
denom=m*sum(1./(1:m));
thresh=(1:m)*q/denom;
wtd_p=denom*p_sorted./[1:m];
%Note, it can produce adjusted p-values greater than 1!
%compute adjusted p-values
else
error('Argument ''method'' needs to be ''pdep'' or ''dep''.');
end
if nargout>2,
%compute adjusted p-values
adj_p=zeros(1,m)*NaN;
[wtd_p_sorted, wtd_p_sindex] = sort( wtd_p );
nextfill = 1;
for k = 1 : m
if wtd_p_sindex(k)>=nextfill
adj_p(nextfill:wtd_p_sindex(k)) = wtd_p_sorted(k);
nextfill = wtd_p_sindex(k)+1;
if nextfill>m
break;
end;
end;
end;
adj_p=reshape(adj_p(unsort_ids),s);
end
rej=p_sorted<=thresh;
max_id=find(rej,1,'last'); %find greatest significant pvalue
if isempty(max_id),
crit_p=0;
h=pvals*0;
else
crit_p=p_sorted(max_id);
h=pvals<=crit_p;
end
if strcmpi(report,'yes'),
n_sig=sum(p_sorted<=crit_p);
if n_sig==1,
fprintf('Out of %d tests, %d is significant using a false discovery rate of %f.\n',m,n_sig,q);
else
fprintf('Out of %d tests, %d are significant using a false discovery rate of %f.\n',m,n_sig,q);
end
if strcmpi(method,'pdep'),
fprintf('FDR procedure used is guaranteed valid for independent or positively dependent tests.\n');
else
fprintf('FDR procedure used is guaranteed valid for independent or dependent tests.\n');
end
end
|
github | carlassmith/exampleGLRT-master | mfiniteGaussPSFerf.m | .m | exampleGLRT-master/helperfunctions/filterHelpers/gpumle/development/M_SCRIPTS/for_release/mfiniteGaussPSFerf.m | 2,364 | utf_8 | aa001c427a5d77c334d2464edfc20261 | %finiteGaussPSFerf Make Gaussian Spots using finite pixel size
%
% [out] = mfiniteGaussPSFerf(Npixels,sigma,I,bg,cor,avg,flag,max)
%
% INPUT
% Npixels: linear size in pixels
% sigma: PSF sigma in pixels, scaler gives symmetric, [sx sy] gives
% asymmetric.
% I: Photons/frame
% bg: background/pixel
% cor: coordinates array size of [2 N] where N is number of spots
% to generate.
% avg: average number of spots in an image, default = 1
% flag: if set to 0, spots are randomly drawn about the avg. if set
% to 1, there are always an avg. number of spots, default = 1
% mxe: maximum number of emitters in a given frame, default = 8
%
% OUTPUT
% out: 3D stack of images.
function [out] = mfiniteGaussPSFerf(Npixels,sigma,I,bg,cor)%,avg,flag,mxe)
calcInt=1;
% if (nargin < 8)
% mxe = 8;
% end
% if (nargin < 7)
% flag = 1;
% end
% if (nargin < 6)
% avg = 1;
% end
if (nargin < 5)
cor = [(Npixels-1)/2 (Npixels-1)/2 0];
end
if (nargin <4)
error('Minimal usage: finiteGaussPSFerf(Npixels,sigma,I,bg)');
end
if (bg == 0)
bg = 10^-10;
end
Ncor=size(cor,1);
X=xx([Npixels Npixels Ncor]);
X=single(X-min(X));
Y=yy([Npixels Npixels Ncor]);
Y=single(Y-min(Y));
Xpos=repmat(shiftdim(cor(:,1),-2),[Npixels,Npixels,1]);
Ypos=repmat(shiftdim(cor(:,2),-2),[Npixels,Npixels,1]);
if size(I,1) > 1
I=repmat(shiftdim(I,-2),[Npixels,Npixels,1]);
if max(size(Xpos) ~= size(I))
error('Size of I and maybe others are incorrect.');
end
end
if size(bg,1) > 1
bg=repmat(shiftdim(bg,-2),[Npixels,Npixels,1]);
if max(size(Xpos) ~= size(bg))
error('Size of bg and maybe others are incorrect.');
end
end
if length(sigma)==1
sigmay = sigma;
sigmax = sigma;
else
sigmax = sigma(1);
sigmay = sigma(2);
end
if calcInt
gausint=I/4.*((erf((X-Xpos+.5)./(sqrt(2)*sigmax))-erf((X-Xpos-.5)./(sqrt(2)*sigmax))).*...
(erf((Y-Ypos+.5)./(sqrt(2)*sigmay))-erf((Y-Ypos-.5)./(sqrt(2)*sigmay))))+bg;
else
gausint = I/(2*pi*sigmax*sigmay)*exp(-1/2*((X-Xpos)/sigmax).^2).*exp(-1/2*((Y-Ypos)/sigmay).^2)+bg;
end
% add multiple gaussians together depending on flag type, avg, and max
% mod by PKR, UNM December 2012
out = gausint;
%out=dip_image(gausint);
end
|
github | carlassmith/exampleGLRT-master | bfsave.m | .m | exampleGLRT-master/helperfunctions/bfmatlab/bfsave.m | 5,932 | utf_8 | d2b1be452e867d81dded1f96b061bea2 | function bfsave(I, outputPath, varargin)
% BFSAVE Save a 5D matrix into an OME-TIFF using Bio-Formats library
%
% bfsave(I, outputPath) writes the input 5D matrix into a new file
% specified by outputPath.
%
% bfsave(I, outputPath, dimensionOrder) specifies the dimension order of
% the input matrix. Default valuse is XYZCT.
%
% bfsave(I, outputPath, 'Compression', compression) specifies the
% compression to use when writing the OME-TIFF file.
%
% bfsave(I, outputPath, 'BigTiff', true) allows to save the file using
% 64-bit offsets
%
% Examples:
%
% bfsave(zeros(100, 100), outputPath)
% bfsave(zeros(100, 100, 2, 3, 4), outputPath)
% bfsave(zeros(100, 100, 20), outputPath, 'dimensionOrder', 'XYTZC')
% bfsave(zeros(100, 100), outputPath, 'Compression', 'LZW')
% bfsave(zeros(100, 100), outputPath, 'BigTiff', true)
%
% See also: BFGETREADER
% OME Bio-Formats package for reading and converting biological file formats.
%
% Copyright (C) 2012 - 2013 Open Microscopy Environment:
% - Board of Regents of the University of Wisconsin-Madison
% - Glencoe Software, Inc.
% - University of Dundee
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as
% published by the Free Software Foundation, either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
% Check loci-tools jar is in the Java path
bfCheckJavaPath();
% Not using the inputParser for first argument as it copies data
assert(isnumeric(I), 'First argument must be numeric');
% Input check
ip = inputParser;
ip.addRequired('outputPath', @ischar);
ip.addOptional('dimensionOrder', 'XYZCT', @(x) ismember(x, getDimensionOrders()));
ip.addParamValue('Compression', '', @(x) ismember(x, getCompressionTypes()));
ip.addParamValue('BigTiff', false , @islogical);
ip.parse(outputPath, varargin{:});
% Create metadata
toInt = @(x) ome.xml.model.primitives.PositiveInteger(java.lang.Integer(x));
metadata = loci.formats.MetadataTools.createOMEXMLMetadata();
metadata.createRoot();
metadata.setImageID('Image:0', 0);
metadata.setPixelsID('Pixels:0', 0);
metadata.setPixelsBinDataBigEndian(java.lang.Boolean.TRUE, 0, 0);
% Set dimension order
dimensionOrderEnumHandler = ome.xml.model.enums.handlers.DimensionOrderEnumHandler();
dimensionOrder = dimensionOrderEnumHandler.getEnumeration(ip.Results.dimensionOrder);
metadata.setPixelsDimensionOrder(dimensionOrder, 0);
% Set pixels type
pixelTypeEnumHandler = ome.xml.model.enums.handlers.PixelTypeEnumHandler();
if strcmp(class(I), 'single')
pixelsType = pixelTypeEnumHandler.getEnumeration('float');
else
pixelsType = pixelTypeEnumHandler.getEnumeration(class(I));
end
metadata.setPixelsType(pixelsType, 0);
% Read pixels size from image and set it to the metadat
sizeX = size(I, 2);
sizeY = size(I, 1);
sizeZ = size(I, find(ip.Results.dimensionOrder == 'Z'));
sizeC = size(I, find(ip.Results.dimensionOrder == 'C'));
sizeT = size(I, find(ip.Results.dimensionOrder == 'T'));
metadata.setPixelsSizeX(toInt(sizeX), 0);
metadata.setPixelsSizeY(toInt(sizeY), 0);
metadata.setPixelsSizeZ(toInt(sizeZ), 0);
metadata.setPixelsSizeC(toInt(sizeC), 0);
metadata.setPixelsSizeT(toInt(sizeT), 0);
% Set channels ID and samples per pixel
for i = 1: sizeC
metadata.setChannelID(['Channel:0:' num2str(i-1)], 0, i-1);
metadata.setChannelSamplesPerPixel(toInt(1), 0, i-1);
end
% Here you can edit the function and pass metadata using the adequate set methods, e.g.
% metadata.setPixelsPhysicalSizeX(ome.xml.model.primitives.PositiveFloat(java.lang.Double(.106)),0);
%
% For more information, see http://trac.openmicroscopy.org.uk/ome/wiki/BioFormats-Matlab
%
% For future versions of this function, we plan to support passing metadata as
% parameter/key value pairs
% Create ImageWriter
writer = loci.formats.ImageWriter();
writer.setWriteSequentially(true);
writer.setMetadataRetrieve(metadata);
if ~isempty(ip.Results.Compression)
writer.setCompression(ip.Results.Compression)
end
if ip.Results.BigTiff
writer.getWriter(outputPath).setBigTiff(ip.Results.BigTiff)
end
writer.setId(outputPath);
% Load conversion tools for saving planes
switch class(I)
case {'int8', 'uint8'}
getBytes = @(x) x(:);
case {'uint16','int16'}
getBytes = @(x) loci.common.DataTools.shortsToBytes(x(:), 0);
case {'uint32','int32'}
getBytes = @(x) loci.common.DataTools.intsToBytes(x(:), 0);
case {'single'}
getBytes = @(x) loci.common.DataTools.floatsToBytes(x(:), 0);
case 'double'
getBytes = @(x) loci.common.DataTools.doublesToBytes(x(:), 0);
end
% Save planes to the writer
nPlanes = sizeZ * sizeC * sizeT;
for index = 1 : nPlanes
[i, j, k] = ind2sub([size(I, 3) size(I, 4) size(I, 5)],index);
plane = I(:, :, i, j, k)';
writer.saveBytes(index-1, getBytes(plane));
end
writer.close();
end
function dimensionOrders = getDimensionOrders()
% List all values of DimensionOrder
dimensionOrderValues = ome.xml.model.enums.DimensionOrder.values();
dimensionOrders = cell(numel(dimensionOrderValues), 1);
for i = 1 :numel(dimensionOrderValues),
dimensionOrders{i} = char(dimensionOrderValues(i).toString());
end
end
function compressionTypes = getCompressionTypes()
% List all values of Compression
writer = loci.formats.ImageWriter();
compressionTypes = arrayfun(@char, writer.getCompressionTypes(),...
'UniformOutput', false);
end
|
github | carlassmith/exampleGLRT-master | simacquisition_gsdim_gpu.m | .m | exampleGLRT-master/helperfunctions/dstormSimHelpers/simacquisition_gsdim_gpu.m | 7,332 | utf_8 | 41842b6cc0b66ddda05a6712ae556528 | % Simacquisition_gsdim_gpu Simulate a 2d localization microscopy acquisition using the GPU
%
% function [image_out, emitter_states] = simacquisition_gsdim_gpu(object,sample_params,optics_params,camera_params,acquisition_params)
%
function varargout = simacquisition_gsdim_gpu(varargin)
d = struct('menu','FRC resolution',...
'display','GSDIM simulation',...
'inparams',struct('name', {'object_image', 'sample_params', 'optics_params', 'camera_params', 'acquisition_params'},...
'description',{'Object image', 'Sample parameters', 'Optics parameters', 'Camera parameters', 'Acquisition parameters'},...
'type', {'image', 'cellarray', 'cellarray', 'cellarray', 'cellarray'},...
'dim_check', {2, [], [], [], []},...
'range_check',{[], [], [], [], []},...
'required', {1, 0, 0, 0, 0},...
'default', {[], {[]}, {[]}, {[]}, {[]}}...
),...
'outparams',struct('name',{'image_out', 'emitter_states'},...
'description',{'Simulated acquisition', 'True emitter states'},...
'type',{'image', 'array'}...
)...
);
if nargin == 1
s = varargin{1};
if ischar(s) && strcmp(s,'DIP_GetParamList')
varargout{1} = struct('menu','none');
return
end
end
try
[object_im, ~, ~, ~, ~] = getparams(d,varargin{1});
sample_params = varargin{2};
optics_params = varargin{3};
camera_params = varargin{4};
acquisition_params = varargin{5};
catch
if ~isempty(paramerror)
error(paramerror)
else
error('Parameter parsing was unsuccessful.')
end
end
if any(object_im<0) || any(isnan(object_im)) || any(isinf(object_im))
error('Illegal values in object image.');
end
%% Input parameters
% Sample properties
N_emitters = sample_params.N; % Expected number of emitters
bg = 0; % Background [photons/pixel]
% Fluorophore properties
% Emitter switching rate constants
N_emitters = sample_params.N; % Expected number of emitters
k_on = sample_params.k_on;
k_off = sample_params.k_off;
k_b = sample_params.k_b;
n_photons = 1; % Expected collected photons per full frame
lambda = sample_params.lambda; % Emission wavelength [nm]
% Properties of optical system
NA = optics_params.NA; % Numerical aperture;
% Camera properties
sz = camera_params.fov; % Field of view [CCD pixels]
CCD_pixelsize = camera_params.ps; % Backprojected camera pixel size [nm]
CCD_offset = camera_params.offset; % Pixel offset
gain = camera_params.gain; % Gain: ADU / photon
readnoise = camera_params.readnoise; % Readout noise [ADU/pixel]
CCD_precision = camera_params.precision; % Data format precision
% Acquisition parameters
timeframes = acquisition_params.timeframes; % Duration of the acquisition
% subframes = acquisition_params.subframes; % Subframes for emitter switching
%% Compute parameters
PSFsigma = 0.3*lambda/NA/CCD_pixelsize; % Standard deviation of the Gaussian PSF
%% Draw emitter positions
object_im(object_im<0) = 0;
object_im = object_im./sum(object_im)*N_emitters;
object_im = noise(object_im,'poisson');
emitter_locs = gotopoints(object_im);
% Rescale positions to match the CCD field of view
emitter_locs(:,1) = emitter_locs(:,1)*(sz(1)/imsize(object_im,1));
emitter_locs(:,2) = emitter_locs(:,2)*(sz(2)/imsize(object_im,2));
N_emitters = size(emitter_locs,1);
% %% Switching simulation
%
% % Define Markov model
% trans_mat = [(1-k_on/subframes) k_on/subframes 0; k_off/subframes 1-(k_off+k_b)/subframes k_b/subframes; k_b 0 1];
% visible_mat = [1 0;0 1;1 0];
%
% % Simulate switching
% emitter_states = [];
%
% for nn = 1:N_emitters
% [seq states] = hmmgenerate(timeframes*subframes,trans_mat,visible_mat);
% seq = seq - 1;
% seq = sum(reshape(seq,[subframes timeframes]),1);
% % Format of emitter_states: [emitter_id x y t n_photons]
% if (sum(seq~=0) ~= 0)
% emitter_states = cat(1,emitter_states,[ones(sum(seq~=0),1)*[nn emitter_locs(nn,:)] find(seq)' nonzeros(seq)]);
% end
% end
%
% emitter_states(:,5) = emitter_states(:,5)*n_photons/subframes;
% emitter_states = sortrows(emitter_states,4);
%
% clear seq states
%% Model based state simulation
emitter_states = []; % Format of emitter_states: [emitter_id x y t n_photons]
% Define Markov model
k_act = (k_on)*(k_off+k_b)/(k_on+k_off+k_b);
k_bl = k_act - k_on*k_off/(k_on+k_off+k_b);
k_off = (k_off+k_b);
% Simulate switching
M_poisson = poissrnd(k_act*timeframes,N_emitters,1);
M_geo = 1+geornd(k_bl/k_act,N_emitters,1);
M = min(M_poisson,M_geo);
for nn = 1:N_emitters
% Activation frame numbers of emitter nn
t = sort(randperm(timeframes,M_poisson(nn)));
t = t(1:M(nn));
t_start = rand(M(nn),1); % Fractional starting time of activations
dt = exprnd(1/(k_off+k_b),M(nn),1); % Durations of on-events
M_subs = ceil(t_start+dt); % Number of frames per on-event
M_max = max(M_subs);
% For every activation event
for ll = 1:M(nn)
if M_subs(ll)==1
I_vec = dt(ll);
t_vec = t(ll);
else
% Vector of intensities during each frame of activation event ll
I_vec = ones(M_subs(ll),1);
I_vec(1) = 1-t_start(ll);
I_vec(end) = rem(t_start(ll)+dt(ll),1);
% Vector of frame numbers of frames in activation event
t_vec = t(ll)-1+(1:M_subs(ll))';
end
emitter_states = cat(1,emitter_states,[ones(M_subs(ll),1)*[nn emitter_locs(nn,:)] t_vec I_vec]);
end
end
emitter_states(:,5) = emitter_states(:,5)*n_photons;
emitter_states = sortrows(emitter_states,4);
emitter_states = emitter_states(emitter_states(:,4)<=timeframes,:);
%% Create movie
im_out = newim(sz(1),sz(2),timeframes);
% Find start and end indices of entries in emitter_states for each time
% point
ed = 1:size(emitter_states,1)-1;
ed = ed(emitter_states(2:end,4)>emitter_states(1:end-1,4));
ed = ed';
st = [1; ed+1];
ed = [ed; size(emitter_states,1)];
% Generate noisefree images on GPU
for ii = 1:length(st)
sz = single(sz);
xy_tmp = single(emitter_states(st(ii):ed(ii),2:3));
t_tmp = emitter_states(st(ii),4);
I_tmp = single(emitter_states(st(ii):ed(ii),5));
s_tmp = PSFsigma*I_tmp./I_tmp;
im_tmp = GPUgenerateBlobs(sz(1),sz(2),xy_tmp(:,1),xy_tmp(:,2),I_tmp,s_tmp,s_tmp,single(zeros(size(xy_tmp,1),1)),1);
im_out(:,:,emitter_states(st(ii),4)-1) = im_tmp;
end
varargout{1}=im_out;
varargout{2} = emitter_states; |
github | carlassmith/exampleGLRT-master | simgsdim_fitdata_model.m | .m | exampleGLRT-master/helperfunctions/dstormSimHelpers/simgsdim_fitdata_model.m | 6,095 | utf_8 | f5a789676ae17f1076d2c8bd586fda16 | % Simacquisition_gsdim_fitdata Obtain localizations of a simulated 2d localization microscopy acquisition
%
% function [coords, emitter_states] = simgsdim_fitdata_full(object,sample_params,optics_params,camera_params,acquisition_params)
%
function varargout = simgsdim_fitdata_model(varargin)
d = struct('menu','FRC resolution',...
'display','GSDIM simulation',...
'inparams',struct('name', {'object_image', 'sample_params', 'optics_params', 'camera_params', 'acquisition_params'},...
'description',{'Object image', 'Sample parameters', 'Optics parameters', 'Camera parameters', 'Acquisition parameters'},...
'type', {'image', 'cellarray', 'cellarray', 'cellarray', 'cellarray'},...
'dim_check', {2, [], [], [], []},...
'range_check',{[], [], [], [], []},...
'required', {1, 0, 0, 0, 0},...
'default', {[], {[]}, {[]}, {[]}, {[]}}...
),...
'outparams',struct('name',{'image_out', 'emitter_states'},...
'description',{'Simulated acquisition', 'True emitter states'},...
'type',{'image', 'array'}...
)...
);
if nargin == 1
s = varargin{1};
if ischar(s) && strcmp(s,'DIP_GetParamList')
varargout{1} = struct('menu','none');
return
end
end
try
[object_im, ~, ~, ~, ~] = getparams(d,varargin{1});
sample_params = varargin{2};
optics_params = varargin{3};
camera_params = varargin{4};
acquisition_params = varargin{5};
catch
if ~isempty(paramerror)
error(paramerror)
else
error('Parameter parsing was unsuccessful.')
end
end
if any(object_im<0) || any(isnan(object_im)) || any(isinf(object_im))
error('Illegal values in object image.');
end
%% Input parameters
% Sample properties
N_sites = sample_params.N_sites; % Expected number of emitters
N_persite = sample_params.N_persite;
d_label = sample_params.labelsize; % Label size [nm]
bg = sample_params.bg; % Background [photons/pixel]
% Fluorophore properties
% Emitter switching rate constants
k_on = sample_params.k_on;
k_off = sample_params.k_off;
k_b1 = sample_params.k_boff;
k_b2 = sample_params.k_bon;
n_photons = sample_params.photons; % Expected collected photons per full frame
lambda = sample_params.lambda; % Emission wavelength [nm]
% Properties of optical system
NA = optics_params.NA; % Numerical aperture;
% Camera properties
sz = camera_params.fov; % Field of view [CCD pixels]
CCD_pixelsize = camera_params.ps; % Backprojected camera pixel size [nm]
% Acquisition parameters
timeframes = acquisition_params.timeframes; % Duration of the acquisition
subframes = acquisition_params.subframes; % Subframes for emitter switching
fitboxsize = acquisition_params.fitbox; % Size of ROIs for single emitter fitting [CCD pixels]
%% Compute parameters
PSFsigma = 0.3*lambda/NA/CCD_pixelsize; % Standard deviation of the Gaussian PSF
%% Draw emitter positions
object_im(object_im<0) = 0;
object_im = object_im./sum(object_im)*N_sites;
object_im = noise(object_im,'poisson');
emitter_locs_tmp = gotopoints(object_im);
% Rescale positions to match the CCD field of view
emitter_locs_tmp(:,1) = emitter_locs_tmp(:,1)*(sz(1)/imsize(object_im,1));
emitter_locs_tmp(:,2) = emitter_locs_tmp(:,2)*(sz(2)/imsize(object_im,2));
%% Generate multiple emitters per binding site
N_sites = size(emitter_locs_tmp,1);
emitter_locs = [];
for mm = 1:N_sites
if N_persite > 0
S = poissrnd(N_persite);
else
if N_persite < 0;
beta = sample_params.dimerfrac;
S = 1+binornd(1,beta);
else
S = 1;
end
end
if S>0
emitter_locs = cat(1,emitter_locs,repmat(emitter_locs_tmp(mm,:),[S 1]));
end
end
emitter_locs = sortrows(emitter_locs);
emitter_locs = emitter_locs + (d_label/CCD_pixelsize)*randn(size(emitter_locs));
N_emitters = size(emitter_locs,1);
%% Switching simulation
% Define Markov model
k_act = (k_on+k_b1)*(k_off+k_b2)/(k_on+k_b1+k_off+k_b2);
k_bl = k_act - k_on*k_off/(k_on+k_b1+k_off+k_b2);
k_off = (k_off+k_b2);
% Simulate switching
M_poisson = poissrnd(k_act*timeframes,N_emitters,1);
M_geo = 1+geornd(k_bl/k_act,N_emitters,1);
M = min(M_poisson,M_geo);
emitter_states = [];
for nn = 1:N_emitters
% Format of emitter_states: [emitter_id x y t]
if M(nn) ~= 0
t_tmp = sort(randperm(timeframes,M_poisson(nn)))';
emitter_states = cat(1,emitter_states,[ones(M(nn),1)*[nn emitter_locs(nn,:)] t_tmp(1:M(nn))]);
end
end
clear seq states
%% Localization simulation
emitter_states = sortrows(emitter_states,4);
coords = zeros(size(emitter_states,1),8);
coords(:,1:3) = emitter_states(:,2:4);
coords(:,4) = 1+geornd(k_off/n_photons,size(emitter_states,1),1);
coords(:,8) = ceil(coords(:,4)/n_photons);
coords(:,6) = poissrnd(coords(:,8)*bg*fitboxsize^2)/fitboxsize^2;
coords(:,7) = PSFsigma*(1+0.02*randn(size(emitter_states,1),1));
tau = 2*pi*(coords(:,7).^2+1/12).*coords(:,6)./coords(:,4);
coords(:,5) = sqrt((coords(:,7).^2+1/12).^2./coords(:,4).*(1+4*tau+sqrt((2*tau)./(1+4*tau)))); % Localization uncertainty
coords(:,1:2) = coords(:,1:2) + (coords(:,5)*[1 1]).*randn(size(coords(:,1:2)));
coords = coords(~any(isnan(coords)'),:);
varargout{1} = coords;
varargout{2} = emitter_states; |
github | carlassmith/exampleGLRT-master | gotopoints.m | .m | exampleGLRT-master/helperfunctions/dstormSimHelpers/gotopoints.m | 1,813 | utf_8 | c4095833528074eb9286f385068d958f | % GOTOPOINTS Go from a binned image to point locations
% POSMAT = gotopoints(IM) converts the binned localization data in
% IM to point location data in the N-by-2 array posmat by
% taking the number of points in each pixel bin and associating them with random
% locations in the pixel area.
function out = gotopoints(varargin)
d = struct('menu','Localization Microscopy',...
'display','Go to points',...
'inparams',struct('name', {'in'},...
'description',{'Image with binned positions'},...
'type', {'image'},...
'dim_check', {0},...
'range_check',{[]},...
'required', {1},...
'default', {[]}...
),...
'outparams',struct('name',{'out'},...
'description',{'List of positions'},...
'type',{'array'}...
)...
);
if nargin == 1
s = varargin{1};
if ischar(s) & strcmp(s,'DIP_GetParamList')
out = d;
return
end
end
try
in = getparams(d,varargin{:});
catch
if ~isempty(paramerror)
error(paramerror)
else
error('Parameter parsing was unsuccessful.')
end
end
if sum(abs(round(in)-in))~=0
error('Input image can only contain integer values.')
end
%
in = im2mat(in);
out = [];
for nn = 1:max(max(in))
% Find positions of nonzero pixels and add locations to out
[y x] = find(in);
out = cat(1,out,[x y]);
% Subtract 1 from each nonzero pixel
in = in - (in>0);
end
% Add random displacement of position within the pixel
out = out - 1.5*ones(size(out))+rand(size(out)); |
github | robical/StatisticalSignalProcessing-master | spet_plo.m | .m | StatisticalSignalProcessing-master/spet_plo.m | 787 | utf_8 | 2c37b27f7a781ce1fa1f6c056b7a1520 | % funzione che plotta lo spettro in modulo e fase rappresentato dai valori
% della trasformata Z di un filtro con zeri e poli rappresentati dai
% polinomi da passare in ingresso Az(zeri) Bp(poli), calcolata sul cerchio
% unitario
function [Spettro,f]=spet_plo(Az,Bp,fc)
%Potrei a questo punto valutare la fdt per frequenze continue, z=exp(j*2*pi*(f/fc))
%Traccio la funzione di trasferimento corrispondente ad un filtro con
%trasformata Z che ha questi zeri
M=2^11; %numero di pulsazioni normalizzate nelle quali valuto la FDT
f=-fc/2+fc/M:fc/M:fc/2;
for k=1:length(f)
A=1;
for i=1:length(Az)
A=A*(1-Az(i)*exp(-1i*2*pi*(f(k)./fc)));
end
Num(k)=A;
B=1;
for i=1:length(Bp)
B=B*(1-Bp(i)*exp(-1i*2*pi*(f(k)./fc)));
end
Den(k)=B;
clear A;
clear B;
end
Spettro=Num./Den; |
github | robical/StatisticalSignalProcessing-master | zero.m | .m | StatisticalSignalProcessing-master/zero.m | 186 | utf_8 | 37d559f73a9a57ddf53cf7db273976ae | %funzione che genera la sequenza complessa pertinente ad una certa
%trasformata Z contenente solo zeri
function [A]=zero(z)
A=[1 -z(1)];
for i=2:length(z)
A=conv(A,[1 -z(i)]);
end |
github | robical/StatisticalSignalProcessing-master | dft.m | .m | StatisticalSignalProcessing-master/dft.m | 515 | utf_8 | 0ab8bf1fed495d9258e3dbb5ac8e4cd9 | %funzione che calcola la DFT in forma matriciale
% x= sequenza in ingresso
% m= numero di campioni dft da calcolare
function [X,fk]=dft(x,m,fc)
n=length(x);
%zero padding
if(n<m)
x=[x zeros(1,m-n)];
end
W=zeros(m); %matrice DFT
for k=1:m
for i=1:m
W(k,i)=exp(-j*((2*pi)/m)*k*i);
end
end
X=x*W.';
if(mod(m,2)==0)
fk=-(m/2-1)*fc/m:fc/m:(m/2)*fc/m;
X=[X(m/2+2:m) X(1:m/2+1)];
else
fk=-((m-1)/2)*fc/m:fc/m:((m-1)/2)*fc/m;
X=[X(((m-1)/2)+2:m) X(1:((m-1)/2)+1)];
end
|
github | robical/StatisticalSignalProcessing-master | LMS.m | .m | StatisticalSignalProcessing-master/LMS.m | 1,262 | utf_8 | 26a64a5e3f9a20c4fb081974a0b4594a | %INPUT
%
%
% U= matrice di convoluzione per identificazione
% h_sti= stima iniziale del filtro
% y= osservazioni con rumore
% mu= passo di aggiornamento
% h=filtro vero
%
%
%OUTPUT:
%
%
% fstim=filtro stimato
% MSE=errore quadratico medio della stima ad ogni iterazione
function [fstim,MSE]=LMS(U,h_sti,y,mu,h)
P=length(h_sti);
i=1;
while(i==1 || i==2 || J(i-1)<J(i-2) || (abs(J(i-1)/J(i-2))>(1-1e-2) && abs(J(i-1)-J(i-2))>1e-3))
%stima dell'out
the(i)=U(i,:)*h_sti(:,i); %scalare, stima dell'OUT al passo i
%calcolo del funzionale di costo
%stima campionaria della crosscorrelaz istantanea
p=(y(i)'*U(i,:)); %riga
%stima campionaria della matrice di covarianza istantanea
R=zeros(P);
R=(U(i,:)'*U(i,:));
J(i)=(y(i)'*y(i))-2*p*h_sti(:,i)+h_sti(:,i)'*R*h_sti(:,i);
%aggiornamento filtro
err(i)=y(i)-U(i,:)*h_sti(:,i); %errore istantaneo di stima
h_sti(:,i+1)=h_sti(:,i)+mu*(err(i)*U(i,:)');
i=i+1;
end
fstim=h_sti(:,end); %stima del filtro a convergenza
%errore quadratico medio di stima ad ogni iterazione
err=h_sti-repmat(h',1,size(h_sti,2));
for i=1:size(err,2)
MSE(i)=err(:,i)'*err(:,i); %calcolo MSE tra filtro vero e filtro stimato alle varie iterazioni
end |
github | robical/StatisticalSignalProcessing-master | trigiv.m | .m | StatisticalSignalProcessing-master/trigiv.m | 574 | utf_8 | 3cb4deef9841237812f4f32fd682b430 | %% Triangolarizzazione di una matrice via rotazioni di Givens
function [A_tri,Qtot1]=trigiv(A)
N=size(A,1);
M=size(A,2);
A_tri=A;
%rango (a meno di colonne o righe linearmente dipendenti)
rang=min(N,M);
k=1;
for j=1:1:(rang-1)
for i=rang:-1:(j+1)
Q=eye(rang);
the=atan(A_tri(i,j)/A_tri(j,j));
c=cos(the);
s=sin(the);
Q(j,j)=c;
Q(i,j)=-s;
Q(j,i)=s;
Q(i,i)=c;
Qt(:,:,k)=Q;
A_tri=Q*A_tri;
k=k+1;
end
end
Qtot1=eye(rang);
for k=size(Qt,3):-1:1
Qtot1=Qtot1*Qt(:,:,k);
end
|
github | robical/StatisticalSignalProcessing-master | fermat.m | .m | StatisticalSignalProcessing-master/fermat.m | 523 | utf_8 | e5ac674353476e8e222b16a22e73cca5 | %Funzione che calcola i percorsi intermedi BS-superficie e superficie-MS
%con raggio di Fermat --> l1 ed l2 rispettivamente
% d = distanza in piano BS-MS
% hBS =altezza BS in metri
% hMS = altezza MS in metri
function [l1,l2]=fermat(hBS,hMS,d)
df1=((-d*(hBS^2))+(hMS*hBS*d))/(hMS^2-hBS^2);
df2=((-d*(hBS^2))-(hMS*hBS*d))/(hMS^2-hBS^2);
if (df1>0)
df=df1;
elseif (df2>0)
df=df2;
else
df=min(df1,df2);
end
l1=sqrt(hBS^2 + df^2);
l2=sqrt((d-df)^2 + hMS^2); |
github | robical/StatisticalSignalProcessing-master | RLS.m | .m | StatisticalSignalProcessing-master/RLS.m | 735 | utf_8 | 333b21ebfc99340285205afb22f2cf1f | %Algoritmo RLS per la stima dei coefficienti del filtro
function [fil,MSE]=RLS(U,y,h)
P=length(h);
delta=0.3;
R_s= eye(P)*delta; %inizializzazione della matrice di covarianza
f_s=zeros(P,1); %inizializzazione della stima
Ri=(R_s)^-1;
i=1;
while(i<=P+20*P)
Ri=Ri - (Ri*U(i,:)'*U(i,:)*Ri)/(1+ U(i,:)*Ri*U(i,:)'); %aggiornamento dell'inversa
g=Ri*U(i,:)'; %guadagno al passo i
f_s(:,i+1)= f_s(:,i) + g* (y(i)-U(i,:)*f_s(:,i)); %aggiornamento filtro
i=i+1;
end
fil=f_s(:,end);
%errore quadratico medio di stima ad ogni iterazione
err= f_s - repmat(h',1,size(f_s,2));
for i=1:size(err,2)
MSE(i)=err(:,i)'*err(:,i); %calcolo MSE tra filtro vero e filtro stimato alle varie iterazioni
end |
github | weifanjiang/UWA_OCT_Image_Processing-master | Surface_Detection_With_Snake.m | .m | UWA_OCT_Image_Processing-master/Surface_Detection_With_Snake.m | 3,223 | utf_8 | f5042ad04244426c48af444d890f3e73 | %% <Surface_Detection_With_Snake.m>
%
% Weifan Jiang
% This function detects the surface of an OCT scan image with active
% contour algorithm (snakes).
%=========================================================================
function Surface_Detection_With_Snake(img)
%% Function Parameters:
% img: image which surface needs to be find.
%% Local Variables:
% These parameters are used for Before_Segmentation.m to pre-process
% scans, each parameter's function is specified in
% Before_Segmentation.m.
Lower_Bound = 12;
Lower_Value = 0;
Higher_Bound = 45;
Higher_Value = 45;
% Iteration_Count: the maximum iterations active contour is run. This
% number can be changed based on the complexity of exterior shape of
% image, as well as the size of image (i.e. larger image requires more
% iterations for the snake to reach inside).
Iteration_Count = 1300;
%% Display original image and process with pre-process function
figure;
subplot(2, 2, 1); imagesc(img, [Lower_Value Higher_Value]); title('Original Image'); colormap(gray);
raw = Before_Segmentation(img, Lower_Bound, Lower_Value, Higher_Bound, Higher_Value);
subplot(2, 2, 2); imagesc(raw); title('Before segmentation processing'); colormap(gray);
%% Using active contour to find the upper & lower edges of image's exterior surface.
[width, height] = size(raw);
% initial mask of active contour, can be adjusted based on property of
% original graph.
mask = zeros(width, height);
mask(10:end-10, 10:end-10) = 1;
% Outputs the background of image.
% Background should be set to black (index = 0) while image set to
% white (index = 1).
background = activecontour(raw, mask, Iteration_Count);
%% Apply mean filter to background to further remove small noises.
denoise = background;
mean_filted = zeros(width + 2, height + 2); % Applied in 3x3 window.
outer = zeros(width + 4, height + 4);
outer(3:width + 2, 3:height + 2) = denoise;
for j = [-1, 0, 1]
for k = [-1, 0, 1]
mean_filted = mean_filted + outer(2 + j:width + 3 + j, 2 + k:height + 3 + k);
end
end
mean_filted = mean_filted / 9;
%Resize to original size.
mean_filted = mean_filted(3:width + 2, 3:height + 2);
background = mean_filted;
% Binarilize background.
for j = (1:width)
for k = (1:height)
if background(j, k) ~= 1
background(j, k) = 0;
end
end
end
subplot(2, 2, 3); imagesc(background); title('Background'); colormap(gray);
%% Get the upper boundary of background and plot on picture
final = img;
for j=(1:height)
ptr = 1;
% Keep iterating until ptr represents a black pixel
while ptr < width - 10 && background(ptr, j) == 0 && min(background(ptr + 1:ptr+5, j)) == 0
ptr = ptr + 1;
end
final(ptr, j) = 255;
end
%% Display and return answer.
subplot(2, 2, 4); imagesc(final); title('Upper surface marked.'); colormap(gray);
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.