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
|
khemrajiitk/Rapidly-exploring-Random-Tree-RRT--master
|
rough.m
|
.m
|
Rapidly-exploring-Random-Tree-RRT--master/rough.m
| 3,932 |
utf_8
|
12e14596070002217eb943efa823e496
|
function main
%obstical1
radius1 = 9;
cen1.x = 25;
cen1.y= 75;
t=0:0.01:2*pi;
global xo1;
xo1 = cen1.x+cos(t)*radius1;
global yo1;
yo1 = cen1.y+sin(t)*radius1;
%storing obstical1 as obst1 object
obst1 = {};
obst1{1}=cen1;
obst1{2} =radius1;
%obstical2
radius2 = 8;
cen2.x = 81;
cen2.y= 30;
t=0:0.01:2*pi;
global xo2;
xo2 = cen2.x+cos(t)*radius2;
global yo2;
yo2 = cen2.y+sin(t)*radius2;
%storing obstical2 as obst2 object
obst2 = {};
obst2{1}=cen2;
obst2{2} =radius2;
%obstical3
radius3 = 15;
cen3.x = 70;
cen3.y= 70;
t=0:0.01:2*pi;
global xo3;
xo3 = cen3.x+cos(t)*radius3;
global yo3;
yo3 = cen3.y+sin(t)*radius3;
%storing obstical3 as obst3 object
obst3 = {};
obst3{1}=cen3;
obst3{2} =radius3;
%obstical4
radius4 = 17;
cen4.x = 32;
cen4.y= 27;
t=0:0.01:2*pi;
global xo4;
xo4 = cen4.x+cos(t)*radius4;
global yo4;
yo4 = cen4.y+sin(t)*radius4;
%storing obstical4 as obst4 object
obst4 = {};
obst4{1} = cen4;
obst4{2} =radius4;
%Plotting the workspace figure
%f1 = figure;
%rw = 10;
%xw = [0 100 100 0 0];
%xy = [0 0 100 100 0];
%plot(xw,xy),xlabel('Workspace'),axis([-5 105 -5 105 -5 105]);
hold on;
%define a goal point
goal.x = 95;
goal.y = 80;
%plotting goal point
r4 = 1.5;
cenx = goal.x;
ceny=goal.y;
t=0:0.01:2*pi;
xog = cenx+cos(t)*r4;
yog = ceny+sin(t)*r4;
patch(xog,yog,'m');
%define a start point
start.x = 1;
start.y = 1;
%plotting start point
r5 = 1.0;
cenx = start.x;
ceny=start.y;
t=0:0.01:2*pi;
xos = cenx+cos(t)*r5;
yos = ceny+sin(t)*r5;
patch(xos,yos,'c');
%drawing obstacles
patch(xo1,yo1,'r');
patch(xo2,yo2,'g');
patch(xo3,yo3,'b');
patch(xo4,yo4,'r');
%storing all obstacle objects in one single object
obstacles = {obst1,obst2,obst3,obst4};
%setting parameters for potentials calculation
k=10; %for attractive potential
m=10000000000; %for repulsive potential
step = 1.5; % step size to simulate the speed of robot
current = start; % current position of robot
%check distance between goal and robot
distance = (current.x-goal.x)^2+(current.y-goal.y)^2;
while(distance > step)
% calculating attractive and repulsive potentials & forces
[xatt,yatt] = attractive_f(current,goal,k);
[xrep,yrep] = repulsive_f(current,obstacles,m);
% resultant gradients in x and y direction
dux = xatt-xrep;
duy = yatt-yrep;
direction = atan2(duy,dux);
movx = step * cos(direction);
movy = step * sin(direction);
%updating the current position
current.x = current.x + movx;
current.y = current.y + movy;
%plotting the updates position of robot
xor = current.x+cos(t)*r5;
yor = current.y+sin(t)*r5;
patch(xor,yor,'c');
% pause of 0.001s to visualize the progress
pause(0.001);
%check distance between goal and robot
distance = (current.x-goal.x)^2+(current.y-goal.y)^2;
end
end
%End of main function
%function for finding attactive force
function [Yatx,Yaty] = attractive_f(c,g,k)
r = dist(c,g);
angle = dir(c,g);
Yatx=k*r*cos(angle);
Yaty=k*r*sin(angle);
end
%function for finding repulsive force
function [xrep,yrep]=repulsive_f(c,obstacles,m)
n = size(obstacles,2);
thres = 10;
for i=1:n
obs = obstacles{i};
center = obs{1};
radi = obs{2};
angle = dir(c,center);
dis=dist(c,center);
Po = radi + thres;
if dis > Po
x(i)=0;
y(i)=0;
else
rep=m*(1/dis-1/Po)^2*1/(dis^2);
x(i)=rep*cos(angle);
y(i)=rep*sin(angle);
end
end
xrep=sum(x);
yrep=sum(y);
end
%Function for calculate directions
function distance = dist(c,g)
distance = sqrt((c.x-g.x)^2+(c.y-g.y)^2);
end
%Function for calculate robot direction
function direction = dir(c,g)
direction = atan2((g.y-c.y),(g.x-c.x));
end
|
github
|
khemrajiitk/Rapidly-exploring-Random-Tree-RRT--master
|
main.m
|
.m
|
Rapidly-exploring-Random-Tree-RRT--master/main.m
| 5,729 |
utf_8
|
15e3bc86581e2b408990937894fd2553
|
function main
%obsticale 1
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radius1 = 13; % should be your R(theta,phi) surface in general
cen1.x = 25;
cen1.y = 75;
cen1.z = 65;
global xo1;
xo1 = cen1.x + radius1.*sin(th).*cos(ph);
global yo1;
yo1 = cen1.y + radius1.*sin(th).*sin(ph);
global zo1;
zo1 = cen1.z + radius1.*cos(th);
%storing obstical1 as obst1 object
obst1 = {};
obst1{1}=cen1;
obst1{2} =radius1;
%obsticale 2
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radius2 = 19; % should be your R(theta,phi) surface in general
cen2.x = 81;
cen2.y = 30;
cen2.z = 55;
global xo2;
xo2 = cen2.x + radius2.*sin(th).*cos(ph);
global yo2;
yo2 = cen2.y + radius2.*sin(th).*sin(ph);
global zo2;
zo2 = cen2.z + radius2.*cos(th);
%storing obstical2 as obst2 object
obst2 = {};
obst2{1}=cen2;
obst2{2} =radius2;
%obsticale 3
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radius3 = 15; % should be your R(theta,phi) surface in general
cen3.x = 70;
cen3.y = 70;
cen3.z = 80;
global xo3;
xo3 = cen3.x + radius3.*sin(th).*cos(ph);
global yo3;
yo3 = cen3.y + radius3.*sin(th).*sin(ph);
global zo3;
zo3 = cen3.z + radius3.*cos(th);
%storing obstical3 as obst3 object
obst3 = {};
obst3{1}=cen3;
obst3{2} =radius3;
%obsticale 4
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radius4 = 17; % should be your R(theta,phi) surface in general
cen4.x = 32;
cen4.y = 27;
cen4.z = 30;
global xo4;
xo4 = cen4.x + radius4.*sin(th).*cos(ph);
global yo4;
yo4 = cen4.y + radius4.*sin(th).*sin(ph);
global zo4;
zo4 = cen4.z + radius4.*cos(th);
%storing obstical4 as obst4 object
obst4 = {};
obst4{1} = cen4;
obst4{2} =radius4;
%define a star point
%plotting start point
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radiuss = 2; % should be your R(theta,phi) surface in general
start.x = 5;
start.y = 5;
start.z = 10;
global xos;
xos = start.x + radiuss.*sin(th).*cos(ph);
global yos;
yos = start.y + radiuss.*sin(th).*sin(ph);
global zos;
zos = start.z + radiuss.*cos(th);
%define a goal point
%plotting goal point
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
radiusg = 2; % should be your R(theta,phi) surface in general
goal.x = 80;
goal.y = 90;
goal.z = 95;
global xog;
xog = goal.x + radiusg.*sin(th).*cos(ph);
global yog;
yog = goal.y + radiusg.*sin(th).*sin(ph);
global zog;
zog = goal.z + radiusg.*cos(th);
figure;
surf(xo1,yo1,zo1);
hold on;
surf(xo2,yo2,zo2);
surf(xo3,yo3,zo3);
surf(xo4,yo4,zo4);
surf(xos,yos,zos);
surf(xog,yog,zog);
%storing all obstacle objects in one single object
obstacles = {obst1,obst2,obst3,obst4};
%setting parameters for potentials calculation
k=6; %for attractive potential
m=10000000000; %for repulsive potential
step = 1.0; % step size to simulate the speed of robot
current = start; % current position of robot
%check distance between goal and robot
distance = (current.x-goal.x)^2+(current.y-goal.y)^2+(current.z-goal.z)^2;
while(distance > step)
% calculating attractive and repulsive potentials & forces
[xatt,yatt,zatt] = attractive_f(current,goal,k);
[xrep,yrep,zrep] = repulsive_f(current,obstacles,m);
% resultant gradients in x and y direction
dux = xatt-xrep;
duy = yatt-yrep;
duz = zatt-zrep;
theta = atan2(duy,dux);
phy = atan2(duz,(sqrt(dux^2+duy^2)));
movx = step * cos(theta)*cos(phy);
movy = step * sin(theta)*cos(phy);
movz = step * sin(phy);
%updating the current position
current.x = current.x + movx;
current.y = current.y + movy;
current.z = current.z + movz;
%plotting the updates position of robot
N = 40;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
r5 = 1; % should be your R(theta,phi) surface in general
xor = current.x + r5.*sin(th).*cos(ph);
yor = current.y + r5.*sin(th).*sin(ph);
zor = current.z + r5.*cos(th);
surf(xor,yor,zor);
% pause of 0.001s to visualize the progress
pause(0.1);
%check distance between goal and robot
distance = (current.x-goal.x)^2+(current.y-goal.y)^2+(current.z - goal.z)^2;
end
end
%function for finding attactive force
function [Yatx,Yaty,Yatz] = attractive_f(c,g,k)
r = dist(c,g);
theta = dir1(c,g);
phy = dir2(c,g);
Yatx=k*r*cos(theta)*cos(phy);
Yaty=k*r*sin(theta)*cos(phy);
Yatz=k*r*sin(phy);
end
%function for finding repulsive force
function [xrep,yrep,zrep]=repulsive_f(c,obstacles,m)
n = size(obstacles,2);
thres = 10;
for i=1:n
obs = obstacles{i};
center = obs{1};
radi = obs{2};
theta = dir1(c,center);
phy = dir2(c,center);
dis=dist(c,center);
Po = radi + thres;
if dis > Po
x(i)=0;
y(i)=0;
z(i)=0;
else
rep=m*(1/dis-1/Po)^2*1/(dis^2);
x(i)=rep*cos(theta)*cos(phy);
y(i)=rep*sin(theta)*cos(phy);
z(i)=rep*sin(phy);
end
end
xrep=sum(x);
yrep=sum(y);
zrep=sum(z);
end
%Function for calculate directions
function distance = dist(c,g)
distance = sqrt((c.x-g.x)^2+(c.y-g.y)^2+(c.z-g.z)^2);
end
%Function for calculate robot direction
function theta = dir1(c,g)
theta = atan2((g.y-c.y),(g.x-c.x));
end
function phy = dir2(c,g)
phy = atan2((g.z-c.z),(sqrt((g.y-c.y)^2+(g.x-c.x)^2)));
end
|
github
|
jorgecote/DIstill-column-master
|
distill.m
|
.m
|
DIstill-column-master/distill.m
| 2,434 |
utf_8
|
49c81487b1801bc7ab55edad787de1f5
|
%*******************************************************************%
% Binary Distillation Column model for water-etanol mix %
% variables: %
% t --> time %
% x --> mole fraction of A at each stage %
% xdot --> state derivatives %
%*******************************************************************%
function xdot = distill(t,x)
global u
% Inputs (1):
% rr => Reflux Ratio (L/D)
rr=u.rr;
% Stages (14):
% x(1) - Reflux Drum Liquid Mole Fraction of Component A
% x(2) - Tray 1 - Liquid Mole Fraction of Component A
% .
% .
% .
% x(12) - Tray 11 - Liquid Mole Fraction of Component A (Feed Location)
% .
% .
% .
% x(13) - Tray 12 - Liquid Mole Fraction of Component A
% x(14) - Reboiler Liquid Mole Fraction of Component A
% Parameters
% Feed Flowrate (Kgmol/hr)
Feed = u.Feed;
% Mole Fraction of Feed
x_Feed = u.x_Feed;
% Distillate Flowrate (Kgmol/hr)
D=u.D;
% Flowrate of the Liquid in the Rectification Section (Kgmol/hr)
L=rr*D;
u.L=L;
% Vapor Flowrate in the Column (Kgmol/hr)
V=L+D;
u.V=V;
% Flowrate of the Liquid in the Stripping Section (Kgmol/hr)
FL=Feed+L;
u.FL=FL;
%Bottom Flowrate
B=Feed-D;
u.B=B;
% Total Molar Holdup in the Condenser (initial conditions)
Mtn=[10 1.3219 1.3383 1.3552 1.3732 1.3936 1.4176 1.4480 1.4895 1.5535 1.6730 2.3508 3.6787 10];
% Vapor Mole Fractions of Component A
% From the equilibrium assumption and mole balances
[y,T]=gammaphi(x,1.01);
% Compute xdot
xdot(1) = 1/Mtn(1)*V*(y(2)-x(1));
xdot(2) = 1/Mtn(2)*(L*(x(1)-x(2))-V*(y(2)-y(3)));
xdot(3) = 1/Mtn(3)*(L*(x(2)-x(3))-V*(y(3)-y(4)));
xdot(4) = 1/Mtn(4)*(L*(x(3)-x(4))-V*(y(4)-y(5)));
xdot(5) = 1/Mtn(5)*(L*(x(4)-x(5))-V*(y(5)-y(6)));
xdot(6) = 1/Mtn(6)*(L*(x(5)-x(6))-V*(y(6)-y(7)));
xdot(7) = 1/Mtn(7)*(L*(x(6)-x(7))-V*(y(7)-y(8)));
xdot(8) = 1/Mtn(8)*(L*(x(7)-x(8))-V*(y(8)-y(9)));
xdot(9) = 1/Mtn(9)*(L*(x(8)-x(9))-V*(y(9)-y(10)));
xdot(10) = 1/Mtn(10)*(L*(x(9)-x(10))-V*(y(10)-y(11)));
xdot(11) = 1/Mtn(11)*(L*(x(10)-x(11))-V*(y(11)-y(12)));
xdot(12) = 1/Mtn(12)*(Feed*x_Feed+L*x(11)-FL*x(12)-V*(y(12)-y(13)));
xdot(13) = 1/Mtn(13)*(FL*(x(12)-x(13))-V*(y(13)-y(14)));
xdot(14) = 1/Mtn(14)*(FL*x(13)-B*x(14)-V*y(14));
xdot = xdot'; % xdot must be a column vector
|
github
|
arunsais/Expxorcist-master
|
bounded_gaussian.m
|
.m
|
Expxorcist-master/data/bounded_gaussian.m
| 1,442 |
utf_8
|
47eadad3ed002b50f3651a74089e022a
|
% method to sample data from a gaussian graph.
function [] = bounded_gaussian(n, p, exNum, graph)
rng(p);
% generate covariance matrix
if(strcmp(graph, 'chain'))
sigma = eye(p);
rho = -0.8;
for i = 1 : p
for j = 1 : p
sigma(i,j) = rho^abs(i - j);
end
end
omega = inv(sigma);
omega(abs(omega) < 1e-5) = 0;
elseif(strcmp(graph, 'grid'))
omega = eye(p,p);
for i = 1 : p
if rem(i, 10) ~= 1
omega(i, i - 1) = 0.2;
end
if rem(i, 10) ~= 0
omega(i, i + 1) = 0.2;
end
if i > 10
omega(i, i - 10) = 0.2;
end
if i <= p - 10
omega(i, i + 10) = 0.2;
end
end
fprintf('determinant: %f\n',det(omega));
sigma = inv(omega);
end
adj = omega; adj(omega ~= 0) = 1;
adj(1:p+1:p*p) = 0;
d = diag(omega).^-0.5;
omega = diag(d)*omega*diag(d);
sigma = inv(omega);
mu = ones(p,1);
rng(n);
xTrain = cell(1, exNum);
xTest = cell(1, exNum);
for i = 1 : exNum
% generate latent variables
xTrain{i} = mvnrnd(mu, sigma, n);
xTest{i} = mvnrnd(mu, sigma, n);
disp(max(abs(xTrain{i}(:))));
assert(max(abs(xTrain{i}(:))) < 15);
end
% save to a file
TrueModel = [ 'gaussian_' graph];
if ~exist(TrueModel, 'dir')
mkdir(TrueModel);
end
fileName = [TrueModel '/data_' num2str(n) '_' num2str(p) '.mat'];
save(fileName, 'xTrain', 'xTest', 'omega', 'sigma', 'adj','mu');
end
|
github
|
arunsais/Expxorcist-master
|
bounded_nongaussian.m
|
.m
|
Expxorcist-master/data/bounded_nongaussian.m
| 3,049 |
utf_8
|
d62af227a3febf19b13053b538ac0c58
|
% sample data from non gaussian distributions
function bounded_nongaussian(n, p, exNum, graph)
rng(p);
% generate interaction terms matrix
if(strcmp(graph, 'chain'))
omega = zeros(p,p);
rho = 1;
for i = 1 : p-1
omega(i,i+1) = rho;
omega(i+1,i) = rho;
end
elseif(strcmp(graph, 'grid'))
omega = zeros(p, p);
rho = 1;
for i = 1 : p
if rem(i, 10) ~= 1
omega(i, i - 1) = rho;
end
if rem(i, 10) ~= 0
omega(i, i + 1) = rho;
end
if i > 10
omega(i, i - 10) = rho;
end
if i <= p - 10
omega(i, i + 10) = rho;
end
end
end
adj = omega; adj(omega ~= 0) = 1;
mu = 1*ones(p,1);
c = 0;
fs_type = ones(p,1);
rng(n);
xTrain = cell(1, exNum);
xTest = cell(1, exNum);
for i = 1 : exNum
% perform Gibbs sampling.
% use rejection sampling to sample from each node conditional
% distribution
xTrain{i} = gibbsSampler(mu, omega, n, c, fs_type);
xTest{i} = gibbsSampler(mu, omega, n, c, fs_type);
fprintf('done %d\n', i);
end
% save to a file
TrueModel = [ 'exp_' graph];
if ~exist(TrueModel, 'dir')
mkdir(TrueModel);
end
fileName = [TrueModel '/data_' num2str(n) '_' num2str(p) '.mat'];
save(fileName, 'xTrain', 'xTest', 'omega', 'adj','mu', 'c', 'fs_type');
end
function X = gibbsSampler(mu, omega, n, c, fs_type)
p = numel(mu);
X = ones(n, p);
x = ones(1, p);
burnin = 500; thinning = 1;
for i = 1 : n + burnin
for k = 1 : thinning
for j = 1 : p
% sample from node conditional distribution
fns = mu(j)+dot(omega(j,:), eval_fs(x, fs_type));
x(j) = sample(c, fns, fs_type(j));
end
end
if i > burnin
thinning = 10;
X(i - burnin, :) = x;
end
end
end
function v = sample(c, fns, fs_type)
xmin = -1; xmax = 1;
if fs_type == 1
proposal_max = exp(abs(fns));
while true
v = (xmax-xmin)*rand + xmin;
v2 = rand*proposal_max;
pv = exp(sin(4*pi*v)*fns + c * abs(v));
if pv >= v2
break;
end
end
elseif fs_type == 2
proposal_max = exp(1.1*abs(fns));
while true
v = (xmax-xmin)*rand + xmin;
v2 = rand*proposal_max;
pv = exp((2*(exp(-20*(v-0.5).^2) + exp(-20*(v+0.5).^2)) - 1)*fns + c * abs(v));
if pv >= v2
break;
end
end
elseif fs_type == 3
if fns > 0
proposal_max = exp(fns*log(2));
else
proposal_max = exp(abs(fns)*log(10));
end
while true
v = (xmax-xmin)*rand + xmin;
v2 = rand*proposal_max;
pv = exp(log(1.1+v)*fns + c * abs(v));
if pv >= v2
break;
end
end
end
end
function v = eval_fs(x, fs_type)
fs1 = sin(4*pi*x);
fs2 = 2*(exp(-20*(x-0.5).^2) + exp(-20*(x+0.5).^2)) - 1;
v = fs1;
v(fs_type == 2) = fs2(fs_type == 2);
end
|
github
|
arunsais/Expxorcist-master
|
exponential.m
|
.m
|
Expxorcist-master/data/exponential.m
| 2,071 |
utf_8
|
74645c17849b2c9376b0cd165f4de089
|
% instead sample from a multivariate exponential distribution
function exponential(n, p, exNum, graph)
rng(p);
% generate interaction terms matrix
if(strcmp(graph, 'chain'))
omega = zeros(p,p);
rho = 0.1;
for i = 1 : p-1
omega(i,i+1) = rho;
omega(i+1,i) = rho;
end
elseif(strcmp(graph, 'grid'))
omega = zeros(p,p);
for i = 1 : p
if rem(i, 10) ~= 1
omega(i, i - 1) = 0.2;
end
if rem(i, 10) ~= 0
omega(i, i + 1) = 0.2;
end
if i > 10
omega(i, i - 10) = -0.2;
end
if i <= p - 10
omega(i, i + 10) = -0.2;
end
end
end
adj = omega; adj(omega ~= 0) = 1;
mu = 2*ones(p,1);
rng(n);
xTrain = cell(1, exNum);
xTest = cell(1, exNum);
for i = 1 : exNum
% perform Gibbs sampling.
% use rejection sampling to sample from each node conditional
% distribution
xTrain{i} = gibbsSampler(mu, omega, n);
xTest{i} = gibbsSampler(mu, omega, n);
end
% save to a file
TrueModel = [ 'exponential_' graph];
if ~exist(TrueModel, 'dir')
mkdir(TrueModel);
end
fileName = [TrueModel '/data_' num2str(n) '_' num2str(p) '.mat'];
save(fileName, 'xTrain', 'xTest', 'omega', 'adj','mu');
end
function X = gibbsSampler(mu, omega, n)
p = numel(mu);
X = ones(n, p);
x = ones(1, p);
burnin = 500; thinning = 1;
for i = 1 : n + burnin
for k = 1 : thinning
for j = 1 : p
% sample from node conditional distribution
fns = mu(j)-dot(omega(j,:), abs(x));
x(j) = exp_sample(fns);
end
end
if i > burnin
thinning = 10;
X(i - burnin, :) = x;
end
end
end
function v = exp_sample(fns)
xmin = -15; xmax = 15;
if fns >= 0
sig = rand;
if(sig < 0.5)
sig = -1;
else
sig = 1;
end
while true
mag = exprnd(fns^-1, 1,1);
if mag < xmax
break;
end
end
v = sig*mag;
else
assert(false);
end
end
|
github
|
arunsais/Expxorcist-master
|
npglm.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/npglm.m
| 4,365 |
utf_8
|
f569956cc0c98866453cdd4faab6f825
|
%% INPUTS
% X: data matrix - n by p matrix; n - number of samples, p - number of nodes in the graph.
% Xtest: test data matrix - ntest by p matrix
% lambda: regularization parameter for group sparse regularized node conditional MLEs.
% d: truncation parameter for basis expansion.
% base_measure_type: specifies which base measure to use. look at base_measure.m file for a list of options
% base_measure_args: a float for specifying the base measure.
%% OUTPUTS
% params: returns the parameters learned by the algorithm
% adj_or: adjacency matrix of the graph learned. uses ‘or’ rule to stitch the estimates from different nodes
% adj_and: adjacency matrix of the graph learned. uses ‘and’ rule to stitch the estimates from different nodes
% train_nllk: p x 1 matrix - node conditional likelihoods of the training data evaluated at all the nodes.
% test_nllk : p x 1 matrix - node conditional likelihoods of the test data evaluated at all the nodes.
% IMPORTANT INFO
% *** current implementation assumes p > 1 ***
% *** the code infers the range of the data from X***
% *** the code uses the same range for all the p variables***
% *** currently the code only works for cosine basis functions ***
function [params, adj_or, adj_and, train_nllk, test_nllk] = npglm(X, Xtest, lambda, d, base_measure_type, base_measure_args)
%% Problem setup
[n, p] = size(X);
% Infer the range of the data
xmin = min(X(:)); xmax = max(X(:));
% grid for numerical integration
% pre-evaluate the basis functions at the grid points, for faster numerical integration
grid = xmin:(xmax-xmin)/100:xmax;
grid_basis_matrix = basis_matrix(grid', d, xmin, xmax);
args.grid = grid; args.grid_basis_matrix = grid_basis_matrix;
% params - stores the parameters estimated at each node
% params is a p x p x d matrix
% params(i,:,:) - stores parameter estimates obtained by solving node
% conditional maximum likelihood estimation at node i.
params = zeros(p,p,d);
% pre-compute the basis matrices at the training data points
% psi is a p x n x d matrix. with psi(i,:,:) corresponds to node i.
psi = basis_matrix(X, d, xmin, xmax);
%% compute node conditional ML estimates at each node
fprintf('started estimation. n = %d, p = %d, lambda = %f\n', n, p, lambda);
for s = 1 : p
%% Perform Alternating Minimization
args.grid_base_measure = base_measure(args.grid, s, base_measure_type, base_measure_args);
params(s,:,:) = alt_min(psi, s, squeeze(params(s,:,:)), lambda, args);
% TODO : use these params to initialize optimization for node (s+1).
fprintf('finished estimation of node %d\n', s);
end
% compute stats
train_nllk = zeros(p,1);
test_nllk = zeros(p,1);
for s = 1 : p
args.grid_base_measure = base_measure(args.grid, s, base_measure_type, base_measure_args);
train_nllk(s) = l(psi, s, squeeze(params(s,:,:)), args);
end
psi = basis_matrix(Xtest, d, xmin, xmax);
for s = 1 : p
args.grid_base_measure = base_measure(args.grid, s, base_measure_type, base_measure_args);
test_nllk(s) = l(psi, s, squeeze(params(s,:,:)), args);
end
[adj_or, adj_and] = getEdges(params);
end
function [adj_or, adj_and] = getEdges(params)
[p, ~, ~] = size(params);
adj_or = zeros(p,p);
adj_and = zeros(p,p);
for i = 1 : p
for j = i+1 : p
e1 = norm(squeeze(params(i,j,:)));
e2 = norm(squeeze(params(j,i,:)));
if isnan(e1) || isnan(e2)
adj_or(i,j) = 1;
adj_or(j,i) = 1;
continue;
end
if max(e1, e2) < 1e-7
continue;
end
adj_or(i,j) = 1;
adj_or(j,i) = 1;
end
end
for i = 1 : p
for j = i+1 : p
e1 = norm(squeeze(params(i,j,:)));
e2 = norm(squeeze(params(j,i,:)));
if isnan(e1) || isnan(e2)
adj_and(i,j) = 1;
adj_and(j,i) = 1;
continue;
end
if min(e1, e2) < 1e-7
continue;
end
adj_and(i,j) = 1;
adj_and(j,i) = 1;
end
end
end
|
github
|
arunsais/Expxorcist-master
|
btls.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/btls.m
| 945 |
utf_8
|
24450ff5b69531fb6e527c8b2a7d1f2c
|
% back tracking line search
% computes a step size that guarantees decrease in function value
% details of the algorithm can be found at
% http://people.eecs.berkeley.edu/~elghaoui/Teaching/EE227A/lecture18.pdf (slide 29)
% f - function
% gradf - gradient of the function
% prox - proximal operator
% x - current point
% t - step size
% f_val - function evaluated at x
function [t, x_new, f_new_val] = btls(f, gradf, prox, x, t, f_val)
beta = 0.7;
if t == []
t = 1;
end
gradfx = gradf(x);
%fprintf('%f,', norm(gradfx));
gtx = (x - prox(x - t * gradfx, t))/t;
f1 = f(x - t * gtx);
f2 = f_val - t * dot(gradfx(:), gtx(:)) + t/2 * norm(gtx(:), 2)^2;
while f1 > f2
t = beta * t;
gtx = (x - prox(x - t * gradfx, t))/t;
f1 = f(x - t * gtx);
f2 = f_val - t * dot(gradfx(:), gtx(:)) + t/2 * norm(gtx(:), 2)^2;
end
x_new = x - t * gtx;
f_new_val = f1;
end
|
github
|
arunsais/Expxorcist-master
|
accproxgd.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/accproxgd.m
| 558 |
utf_8
|
044db932cf333f3e308f9dc500174729
|
% FISTA - accelerated proximal gradient descent
% x - starting point
% T - number of iterations
% eta - step size
function x = accproxgd(f, gradf, prox, x, T, eta)
gammaO = 1;
x0 = x;
[eta, ~] = btls(f, gradf, prox, x, eta, f(x));
for i = 1 : T
t = eta/sqrt(i);
xt = prox(x - t * gradf(x), t);
gamma = 0.5 + 0.5 * sqrt(1 + 4 * gammaO^2);
alpha = (1 - gammaO)/gamma;
x = (1 - alpha) * xt + alpha * x0;
% save variables for next iteration
gammaO = gamma;
x0 = xt;
end
end
|
github
|
arunsais/Expxorcist-master
|
l.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/l.m
| 770 |
utf_8
|
c5515333c675be598d4798ced30749cc
|
% negative node conditional log likelihood function
% psi - basis expansion matrices
% s : node at which to compute the conditional log likelihood
% params : parameters for node s.
function v = l(psi, s, params, args)
[~,n,~] = size(psi);
tmp = sum(permute(repmat(params, 1,1,n), [1,3,2]).*psi, 3);
fs = tmp(s,:)';
fns = sum(tmp,1)';
fns = 1 + fns - fs;
v = -mean(fs.*fns);
% log normalization constant
% TODO: need a better integration technique.
fs_tmp = args.grid_basis_matrix*params(s,:)';
y = bsxfun(@plus, fs_tmp*fns', args.grid_base_measure');
maxy = max(y, [], 1);
y = exp(bsxfun(@minus, y, maxy));
v = v + mean(maxy) + mean(log(trapz(args.grid, y)));
if isnan(v) ||isinf(v)
warning('nan or inf detected in loss function');
end
end
|
github
|
arunsais/Expxorcist-master
|
prox_gl.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/prox_gl.m
| 234 |
utf_8
|
1099dda1ff9c36b583bde2b9ee50a941
|
% proximal operator for group lasso
function v = prox_gl(x, lambda)
norms = sum(x.^2, 2).^0.5;
shrinkage = 1 - lambda./norms;
shrinkage(norms <= lambda) = 0;
v = sparse(1:numel(shrinkage), 1:numel(shrinkage), shrinkage)*x;
end
|
github
|
arunsais/Expxorcist-master
|
gradl.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/gradl.m
| 1,859 |
utf_8
|
d33115ed777775c63a4ace7c7c9dd890
|
% gradient of negative node conditional log likelihood
% psi - basis expansion matrices
% s : node at which to compute the gradient
% opt_s : flag denoting if the gradient should be computed for variables corresponding to node s.
% params : parameters for node s.
% returns d x 1 matrix.
function v = gradl(psi, s, opt_s, params, args)
% for numerical integration
[~,n,d] = size(psi);
tmp = sum(permute(repmat(params, 1,1,n), [1,3,2]).*psi, 3);
fs = tmp(s,:)';
fns = sum(tmp,1)';
fns = 1 + fns - fs;
if opt_s == 1
v = -fns'*squeeze(psi(s,:,:))/n;
% derivative of log normalization constant
psi_s = args.grid_basis_matrix;
y = bsxfun(@plus, (psi_s*params(s,:)')*fns', args.grid_base_measure');
maxy = max(y, [], 1);
y = exp(bsxfun(@minus, y, maxy));
dens = trapz(args.grid, y)';
nums = zeros(n, d);
for i = 1 : d
tmp = bsxfun(@times, y, psi_s(:,i));
nums(:,i) = trapz(args.grid, tmp)'.*fns./dens;
end
v = v + mean(nums,1);
else
% derivative of log normalization constant
fs_tmp = args.grid_basis_matrix*params(s,:)';
y = bsxfun(@plus, fs_tmp*fns', args.grid_base_measure');
maxy = max(y, [], 1);
y = exp(bsxfun(@minus, y, maxy));
dens = trapz(args.grid, y)';
tmps = trapz(args.grid, bsxfun(@times, y, fs_tmp))'./dens;
v = zeros(size(params));
for t = 1 : size(params,1)
if t == s
continue;
end
v(t,:) = (tmps-fs)'*squeeze(psi(t,:,:))/n;
end
v(s,:) = [];
end
if any(isnan(v(:))) || any(isinf(v(:)))
warning('nan or inf detected in gradient');
end
end
|
github
|
arunsais/Expxorcist-master
|
basis_matrix.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/basis_matrix.m
| 672 |
utf_8
|
59d5e5cf512dfa37c74722eadaa1095e
|
function v = basis_matrix(X, d, xmins, xmaxs)
[n, p] = size(X);
v = zeros(p,n,d);
for i = 1 : p
if numel(xmins) == 1
xmin = xmins;
xmax = xmaxs;
else
xmin = xmins(i);
xmax = xmaxs(i);
end
v(i,:,:) = basis_matrix_h(X(:,i), d, xmin, xmax);
end
if p == 1
v = squeeze(v(1,:,:));
end
end
% do basis expansion.
% what basis to use depends on the problem.
% using cosine basis : http://www.stat.cmu.edu/~larry/=sml/functionspaces.pdf
function v = basis_matrix_h(X,d, xmin, xmax)
idx = 1:d;
v = sqrt(2/(xmax-xmin))*cos(pi*(X-xmin)/(xmax-xmin)*idx);
end
|
github
|
arunsais/Expxorcist-master
|
alt_min.m
|
.m
|
Expxorcist-master/algorithm/basis_expansion/alt_min.m
| 1,257 |
utf_8
|
3d0dbed834d074fa0f9dcc009d9e21d3
|
% Alternating optimization of the regularized node conditional log likelihood
function params = alt_min(psi, s, params, lambda, args)
alt_min_iters = 25;
for i = 1 : alt_min_iters
%% optimization of node specific params
% create anonymous functions
f = @(Z) l_h(psi, s, 1, params, Z, args);
gradf = @(Z) gradl_h(psi, s, 1, params, Z, args);
prox = @(Z, eta) prox_gl(Z, lambda * eta);
% acc_prox_gd
params(s,:) = accproxgd(f, gradf, prox, params(s,:), 40, 1);
%fprintf('%d, %f\n', s, f(params(s,:)) + lambda * norm(params(s,:)));
%% optimization of interaction params
% create anonymous functions
f = @(Z) l_h(psi, s, 0, params, Z, args);
gradf = @(Z) gradl_h(psi, s, 0, params, Z, args);
prox = @(Z, eta) prox_gl(Z, lambda * eta);
% acc_prox_gd
params([1:s-1,s+1:end],:) = accproxgd(f, gradf, prox, params([1:s-1,s+1:end],:), 40, 1);
end
end
function v = l_h(psi, s, opt_s, params, Z, args)
if opt_s == 1
params(s,:) = Z;
else
params([1:s-1,s+1:end],:) = Z;
end
v = l(psi, s, params, args);
end
function v = gradl_h(psi, s, opt_s, params, Z, args)
if opt_s == 1
params(s,:) = Z;
else
params([1:s-1,s+1:end],:) = Z;
end
v = gradl(psi, s, opt_s, params, args);
end
|
github
|
FDYdarmstadt/BoSSS-master
|
pdftops.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/pdftops.m
| 2,947 |
utf_8
|
cac024fcdfff373b191140816149e0c2
|
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.
% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
return
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.');
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 pdftops.txt.');
return
end
return
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'));
return
|
github
|
FDYdarmstadt/BoSSS-master
|
isolate_axes.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/isolate_axes.m
| 3,198 |
utf_8
|
9d34430569940dca9f8c324f61f22fbf
|
%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 specified, and
% also their associated legends and colorbars. The axes specified must all
% be in the same figure, but they will generally only be a subset of the
% axes in the figure.
%
% IN:
% ah - An array of axes 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-2012
% 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.
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, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~strcmp(get(ah(a), 'Type'), 'axes')
error('All handles must be axes handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the axes 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 axes 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 axes 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
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);
for a = 1:nAx
% Overlap test
ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &...
leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))];
end
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input axes and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
return
function ah = allchildren(ah)
ah = allchild(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
return
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
return
|
github
|
FDYdarmstadt/BoSSS-master
|
pdf2eps.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/pdf2eps.m
| 1,473 |
utf_8
|
cb8bb442a3d65a64025c32693704d89e
|
%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);
return
|
github
|
FDYdarmstadt/BoSSS-master
|
print2array.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/print2array.m
| 5,963 |
utf_8
|
c34d89e7caa47b1ffff7af835726459b
|
%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-2011
% 5/9/2011 Set EraseModes to normal when using opengl or zbuffer renderers.
% Thanks to Pawel Kocieniewski for reporting the issue.
% 21/9/2011 Bug fix: unit8 -> uint8!
% Thanks to Tobias Lamour for reporting the issue.
% 14/11/2011 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.
% 9/12/2011 Pass font path to ghostscript.
% 27/1/2012 Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 3/4/2012 Bug fix to median input. Thanks to Andy Matthews for reporting
% it.
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
% Delete the intermediate file
delete(tmp_eps);
rethrow(lasterror);
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_mode = get(fig, 'PaperPositionMode');
set(fig, 'PaperPositionMode', 'auto');
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_mode);
% 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
return
% 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);
return
|
github
|
FDYdarmstadt/BoSSS-master
|
eps2pdf.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/eps2pdf.m
| 5,017 |
utf_8
|
bc81caea32035f06d8cb08ea1ccdc81f
|
%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
% Delete the intermediate file
delete(tmp_nam);
rethrow(lasterror);
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
return
% 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);
return
|
github
|
FDYdarmstadt/BoSSS-master
|
copyfig.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/copyfig.m
| 814 |
utf_8
|
1844a9d51dbe52ce3927c9eac5ee672e
|
%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(findobj(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
return
|
github
|
FDYdarmstadt/BoSSS-master
|
user_string.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/user_string.m
| 2,339 |
utf_8
|
f9b2326571e9d13eccc99ce441efd788
|
%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
% 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.
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, 'w');
if fid == -1
string = false;
return
end
try
fwrite(fid, string, '*char');
catch
fclose(fid);
string = false;
return
end
fclose(fid);
string = true;
else
% Get string
fid = fopen(string_name, 'r');
if fid == -1
string = '';
return
end
string = fread(fid, '*char')';
fclose(fid);
end
return
|
github
|
FDYdarmstadt/BoSSS-master
|
export_fig.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/export_fig.m
| 28,666 |
utf_8
|
4a599b3b631aee3eee5a84473d8ceb83
|
%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 dimensions by when generating bitmap
% outputs. Default: '-m1'.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap outputs at, keeping the dimensions of the
% on-screen figure. Default: sprintf('-r%g', get(0,
% 'ScreenPixelsPerInch')). Note that the -m and -r options
% change the same property.
% -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 or axes (can be an array of handles
% of several axes, but these 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:
% http://sites.google.com/site/oliverwoodford/software/export_fig
%
% See also PRINT, SAVEAS.
% Copyright (C) Oliver Woodford 2008-2012
% 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.
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 = strcmp(get(fig(1), 'Type'), 'axes');
if cls
% Given handles of one or more axes, so isolate them from the rest
fig = isolate_axes(fig);
else
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 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_background(alpha, 0);
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', 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_background(A, tcol);
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};
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);
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
return
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', 3, ...
'magnify', 1, ...
'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.magnify = val ./ get(0, 'ScreenPixelsPerInch');
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
% 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(fig, '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
return
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
return
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));
return
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
return
function [A v] = crop_background(A, bcol)
% Map the foreground pixels
[h w c] = size(A);
if isscalar(bcol) && c > 1
bcol = bcol(ones(1, c));
end
bail = false;
for l = 1:w
for a = 1:c
if ~all(A(:,l,a) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(A(:,r,a) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bail = false;
for t = 1:h
for a = 1:c
if ~all(A(t,:,a) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(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-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
A = A(v(1):v(2),v(3):v(4),:);
return
function eps_remove_background(fname)
% 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 true
% 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+ +rf *[\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);
break;
end
end
% Close the file
fclose(fh);
return
function b = isvector(options)
b = options.pdf || options.eps;
return
function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
return
% Helper function
function A = make_cell(A)
if ~iscell(A)
A = {A};
end
return
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);
return
|
github
|
FDYdarmstadt/BoSSS-master
|
ghostscript.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/ghostscript.m
| 4,076 |
utf_8
|
b19fc1688d3306608d35f159509a910d
|
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-2010
% 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.
% Call ghostscript
[varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd));
return
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'};
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
bin = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(bin)
path = bin{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?');
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 ghostscript.txt.');
return
end
return
function good = check_gs_path(path)
% Check the path is valid
[good message] = system(sprintf('"%s" -h', path));
good = good == 0;
return
|
github
|
FDYdarmstadt/BoSSS-master
|
print2eps.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig/print2eps.m
| 6,118 |
utf_8
|
d51322b49255fd17900b2a402b760e8e
|
%PRINT2EPS Prints figures to eps with improved line styles
%
% Examples:
% print2eps filename
% print2eps(filename, fig_handle)
% print2eps(filename, fig_handle, options)
%
% This function saves a figure as an eps file, with two improvements over
% MATLAB's print command. First, it improves the line style, making dashed
% lines more like those on screen and giving grid lines their own dotted
% style. Secondly, it substitutes original font names back into the eps
% file, where these have been changed by MATLAB, for up to 11 different
% fonts.
%
%IN:
% filename - string containing the name (optionally including full or
% relative path) of the file the figure is to be saved as. A
% ".eps" extension is added if not there already. If a path is
% not specified, the figure is saved in the current directory.
% fig_handle - The handle of the figure to be saved. Default: gcf.
% options - Additional parameter strings to be passed to print.
% Copyright (C) Oliver Woodford 2008-2012
% 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 :)
% 14/11/2011 Fix a MATLAB bug rendering black or white text incorrectly.
% Thanks to Mathieu Morlighem for reporting the issue and obtaining a fix
% from TMW.
% 8/12/2011 Added ability to correct fonts. Several people have requested
% this at one time or another, and also pointed me to printeps (fex id:
% 7501), so thank you to them. My implementation (which was not inspired by
% printeps - I'd already had the idea for my approach) goes
% slightly further in that it allows multiple fonts to be swapped.
% 14/12/2011 Fix bug affecting font names containing spaces. Many thanks to
% David Szwer for reporting the issue.
% 25/1/2012 Add a font not to be swapped. Thanks to Anna Rafferty and Adam
% Jackson for reporting the issue. Also fix a bug whereby using a font
% alias can lead to another font being swapped in.
% 10/4/2012 Make the font swapping case insensitive.
function print2eps(name, fig, varargin)
options = {'-depsc2'};
if nargin < 2
fig = gcf;
elseif nargin > 2
options = [options varargin];
end
% Construct the filename
if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps')
name = [name '.eps']; % Add the missing extension
end
% Find all the used fonts in the figure
font_handles = findall(fig, '-property', 'FontName');
fonts = get(font_handles, 'FontName');
if ~iscell(fonts)
fonts = {fonts};
end
% Map supported font aliases onto the correct name
fontsl = lower(fonts);
for a = 1:numel(fonts)
f = fontsl{a};
f(f==' ') = [];
switch f
case {'times', 'timesnewroman', 'times-roman'}
fontsl{a} = 'times-roman';
case {'arial', 'helvetica'}
fontsl{a} = 'helvetica';
case {'newcenturyschoolbook', 'newcenturyschlbk'}
fontsl{a} = 'newcenturyschlbk';
otherwise
end
end
fontslu = unique(fontsl);
% Determine the font swap table
matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
matlab_fontsl = lower(matlab_fonts);
require_swap = find(~ismember(fontslu, matlab_fontsl));
unused_fonts = find(~ismember(matlab_fontsl, fontslu));
font_swap = cell(3, 0);
for a = 1:min(numel(require_swap), numel(unused_fonts))
ind = find(strcmp(fontslu{require_swap(a)}, fontsl));
n = numel(ind);
font_swap(1,end+1:end+n) = reshape(mat2cell(font_handles(ind), ones(n, 1)), 1, []);
font_swap(2,end-n+1:end) = matlab_fonts(unused_fonts(a));
font_swap(3,end-n+1:end) = reshape(fonts(ind), 1, []);
end
% Swap the fonts
for a = 1:size(font_swap, 2)
set(font_swap{1,a}, 'FontName', font_swap{2,a});
end
% Set paper size
old_mode = get(fig, 'PaperPositionMode');
set(fig, 'PaperPositionMode', 'auto');
% MATLAB bug fix - black and white text can come out inverted sometimes
% Find the white and black text
white_text_handles = findobj(fig, 'Type', 'text');
M = get(white_text_handles, 'Color');
if iscell(M)
M = cell2mat(M);
end
M = sum(M, 2);
black_text_handles = white_text_handles(M == 0);
white_text_handles = white_text_handles(M == 3);
% Set the font colors slightly off their correct values
set(black_text_handles, 'Color', [0 0 0] + eps);
set(white_text_handles, 'Color', [1 1 1] - eps);
% Print to eps file
print(fig, options{:}, name);
% Reset the font colors
set(black_text_handles, 'Color', [0 0 0]);
set(white_text_handles, 'Color', [1 1 1]);
% Reset paper size
set(fig, 'PaperPositionMode', old_mode);
% Correct the fonts
if ~isempty(font_swap)
% Reset the font names in the figure
for a = 1:size(font_swap, 2)
set(font_swap{1,a}, 'FontName', font_swap{3,a});
end
% Replace the font names in the eps file
font_swap = font_swap(2:3,:);
try
swap_fonts(name, font_swap{:});
catch
warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
return
end
end
% Fix the line styles
try
fix_lines(name);
catch
warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
end
return
function swap_fonts(fname, varargin)
% 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);
% Replace the font names
for a = 1:2:numel(varargin)
fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1})));
end
% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
error('Unable to open %s for writing.', fname2);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
return
|
github
|
FDYdarmstadt/BoSSS-master
|
pdftops.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/pdftops.m
| 7,301 |
utf_8
|
8ada403c52d45d5dad03264fcfcec4b7
|
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://xpdfreader.com
%
% 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)
% 22/09/2018 - Xpdf website changed to xpdfreader.com; improved popup logic
% 03/02/2019 - Fixed one-off 'pdftops not found' error after install (Mac/Linux) (issue #266)
% 15/01/2020 - Fixed reported path of pdftops.txt file in case of error; added warning ID
% 23/07/2020 - Fixed issue #311 (confusion regarding Xpdf-tools download/installation); silent check of pdftops installation in case no input arg specified
% If no command parameter specified, just check pdftops installation and bail out
if nargin < 1
xpdf_path(); % this will error if pdftops is not found
return % silent bail-out if pdftops was successfully located
end
% 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 utility not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://xpdfreader.com/download.html'; %='http://foolabs.com/xpdf';
fprintf(2, '%s%s ("Xpdf command line tools" section)\n', errMsg1, hyperlink(url1));
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 pdftops is installed, maybe Matlab is shaddowing it, as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s%s\n', errMsg2, hyperlink(url2,'issue #137'));
errMsg2 = [errMsg2 url2];
% Provide an alternative possible explanation as per issue #311
errMsg3 = 'Or perhaps you installed XpdfReader but not xpdf-tools, as described in ';
url3 = 'https://github.com/altmany/export_fig/issues/311';
fprintf(2, '%s%s\n', errMsg3, hyperlink(url3,'issue #311'));
errMsg3 = [errMsg3 url3];
state = 1;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2,'',errMsg3},'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);
state = 0;
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_)
%filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt');
[unused, filename] = user_string('pdftops'); %#ok<ASGLU>
warning('export_fig:pdftops','Path to pdftops executable could not be saved. Enter it manually in %s.', filename);
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')); %#ok<STREMP>
% Display the error message if the pdftops executable exists but fails for some reason
% Note: on Mac/Linux, exist('pdftops','file') will always return 2 due to pdftops.m => check for '/','.' (issue #266)
if ~good && exist(path_,'file') && ~isempty(regexp(path_,'[/.]')) %#ok<RGXP1> % 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
|
FDYdarmstadt/BoSSS-master
|
crop_borders.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/crop_borders.m
| 4,976 |
utf_8
|
c814ff486afb188464069b51e4b5ed8a
|
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
|
FDYdarmstadt/BoSSS-master
|
isolate_axes.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/isolate_axes.m
| 5,225 |
utf_8
|
a19c59a5f2c180ebe01ec4d766192eff
|
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-2014, Yair Altman 2015-
%{
% 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
% 02/02/21: Fix axes, figure size to preserve input axes image resolution (thanks @Optecks)
%}
% 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);
% Fix Axes & Figure size for image catpuring to have almost exact resolution
% of the Input Axes (thanks @Optecks)
allaxes = findall(fh, 'type', 'axes');
if ~isempty(ah)
sz = get(ah(1), 'Position');
set(allaxes(1), 'Position', [0 0 sz(3) sz(4)]);
set(fh, 'Position', [0 0 sz(3) sz(4)]);
end
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
|
FDYdarmstadt/BoSSS-master
|
im2gif.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/im2gif.m
| 7,413 |
utf_8
|
f09a59e5fd22ac4e0674b3c89bb053b2
|
%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
%{
% 14/02/18: Merged issue #235: reduced memory usage, improved performance (thanks to @numb7rs)
% 30/11/19: Merged issue #288: Fix im2gif.m for greyscale TIFF images (thanks @Blackbelt1221)
%}
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);
% Issue #235: Using unique(A,'rows') on the whole image stack at once causes
% massive memory usage when dealing with large images (at least on Matlab 2017b).
% Running unique(...) on individual frames, then again on the results drastically
% reduces the memory usage & slightly improves the execution time (@numb7rs).
uns = cell(1,size(A,4));
for nn=1:size(A,4)
uns{nn}=unique(reshape(A(:,:,:,nn), h*w, c),'rows');
end
map=unique(cell2mat(uns'),'rows');
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
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]));
elseif size(A{a}, 3) < 3 %Check whether TIFF has been read in as greyscale
%Convert from greyscale to RGB colorspace (issue #288)
A{a} = cat(3, A{a}, A{a}, A{a});
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
|
FDYdarmstadt/BoSSS-master
|
read_write_entire_textfile.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/read_write_entire_textfile.m
| 924 |
utf_8
|
779e56972f5d9778c40dee98ddbd677e
|
%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
|
FDYdarmstadt/BoSSS-master
|
pdf2eps.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/pdf2eps.m
| 1,648 |
utf_8
|
cbf3ee6801a32b1e1b87764248465760
|
%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://xpdfreader.com
%
% Inputs:
% 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, Yair Altman 2015-
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
% 22/09/2018 - Xpdf website changed to xpdfreader.com
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
|
FDYdarmstadt/BoSSS-master
|
print2array.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/print2array.m
| 15,841 |
utf_8
|
798ce7a86701e75be2f05fa42b7d45bf
|
function [A, bcol, alpha] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to a bitmap RGB 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, alpha] = print2array(...)
%
% This function outputs a bitmap image of a figure, at the desired resolution.
%
% When resolution==1, fast Java screen-capture is attempted first.
% If the Java screen-capture fails or if resolution~=1, the builtin print()
% function is used to create a temp TIF file, which is then loaded and reported.
% If this fails, print() is used to create a temp EPS file which is converted to
% a TIF file using Ghostcript (http://www.ghostscript.com), loaded and reported.
%
% Inputs:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Output resolution as a factor of screen resolution. Default: 1
% Note: resolution ~= 1 uses a slow print to/from image file
% renderer - The renderer to be used by print() function. Default: '-opengl'
% Note: only used when resolution ~= 1
% gs_options - optional ghostscript parameters (e.g.: '-dNoOutputFonts').
% Enclose multiple options in a cell array, e.g. {'-a','-b'}
% Note: only used when resolution ~= 1 and basic print() fails
%
% Outputs:
% A - MxNx3 uint8 bitmap image of the figure (MxN pixels x 3 RGB values)
% bcol - 1x3 uint8 vector of the background RGB color
% alpha - MxN uint8 array of alpha values (between 0=transparent, 255=opaque)
% 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.
% 29/09/18: Fixed issue #254: error in print2array>read_tif_img
% 22/03/20: Alert if ghostscript.m is required but not found on Matlab path
% 24/05/20: Significant performance speedup; added alpha values (where possible)
% 07/07/20: Fixed issue #308: bug in R2019a and earlier
% 07/10/20: Use JavaFrame_I where possible, to avoid evoking a JavaFrame warning
% 07/03/21: Fixed edge-case in case a non-figure handle was provided as input arg
% 10/03/21: Forced a repaint at top of function to ensure accurate image snapshot (issue #211)
%}
% Generate default input arguments, if needed
if nargin < 1, fig = gcf; end
if nargin < 2, res = 1; end
% Force a repaint to ensure we get an accurate snapshot image (issue #211)
drawnow
% Get the figure size in pixels
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
% Retrieve the background colour
bcol = get(fig, 'Color');
try
% Try a direct Java screen-capture first - *MUCH* faster than print() to file
% Note: we could also use A=matlab.graphics.internal.getframeWithDecorations(fig,false) but it (1) returns no alpha and (2) does not exist in older Matlabs
if res == 1
[A, alpha] = getJavaImage(fig);
else
error('magnify/downscale via print() to image file and then import');
end
catch err %#ok<NASGU>
% Warn if output is large
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
% 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 image file
try
% Print the file into a temporary image file and read it into array A
[A, alpha, err, ex] = getPrintImage(fig, res_str, renderer, tmp_nam);
if err, rethrow(ex); end
catch % error - try to print to EPS and then using Ghostscript to TIF
% Ensure that ghostscript() exists on the Matlab path
if ~exist('ghostscript','file') && isempty(which('ghostscript'))
error('export_fig:print2array:ghostscript', 'The ghostscript.m function is required by print2array.m. Install the complete export_fig package from https://www.mathworks.com/matlabcentral/fileexchange/23629-export_fig or https://github.com/altmany/export_fig')
end
% 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
else
if nargin < 3
renderer = '-opengl';
end
% Print the file into a temporary image file and read it into array A
[A, alpha, err, ex] = getPrintImage(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
end
end
% Set the background color
if isequal(bcol, 'none')
bcol = squeeze(A(1,1,:));
if ~all(bcol==0) %if not black
bcol = [255,255,255]; %=white %=[];
end
else
if all(bcol <= 1)
bcol = bcol * 255;
end
if ~isequal(bcol, round(bcol))
bcol = squeeze(A(1,1,:));
%{
% Set border pixels to the correct colour
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 = 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
end
bcol = uint8(bcol);
% Ensure that 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 any(size(A) > px) %~isequal(size(A), px)
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
if any(size(alpha) > px(1:2))
alpha = alpha(1:min(end,px(1)),1:min(end,px(2)));
end
end
end
% Get the Java-based screen-capture of the figure's JFrame content-panel
function [imgData, alpha] = getJavaImage(hFig)
% Get the figure's underlying Java frame
oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
warning('off','MATLAB:ui:javaframe:PropertyToBeRemoved');
try
jf = get(handle(hFig),'JavaFrame_I');
catch
jf = get(handle(hFig),'JavaFrame'); %#ok<JAVFM>
end
warning(oldWarn);
% Get the Java frame's root frame handle
%jframe = jf.getFigurePanelContainer.getComponent(0).getRootPane.getParent;
try
jClient = jf.fHG2Client; % This works from R2014b and up
catch
try
jClient = jf.fHG1Client; % This works from R2008b-R2014a
catch
jClient = jf.fFigureClient; % This works up to R2011a
end
end
% Get the content-pane
try
jPanel = jClient.getContentPane;
catch
jPanel = jClient.getFigurePanelContainer;
end
jPanel.repaint;
w = jPanel.getWidth;
h = jPanel.getHeight;
% Create a BufferedImage and paint the content-pane into it
% (https://coderanch.com/t/470601/java/screenshot-JPanel)
% Note: contrary to documentation and common-sense, it turns out that TYPE_INT_RGB
% ^^^^ returns non-opaque alpha, while TYPE_INT_ARGB only returns 255s in the alpha channel
jOriginalGraphics = jPanel.getGraphics;
import java.awt.image.BufferedImage
try TYPE_INT_RGB = BufferedImage.TYPE_INT_RGB; catch, TYPE_INT_RGB = 1; end
jImage = BufferedImage(w, h, TYPE_INT_RGB);
jPanel.paint(jImage.createGraphics);
jPanel.paint(jOriginalGraphics); % repaint original figure to avoid a blank window
% Extract the RGB pixels from the BufferedImage (see screencapture.m)
pixelsData = reshape(typecast(jImage.getData.getDataStorage, 'uint8'), 4, w, h);
imgData = cat(3, ...
transpose(reshape(pixelsData(3, :, :), w, h)), ...
transpose(reshape(pixelsData(2, :, :), w, h)), ...
transpose(reshape(pixelsData(1, :, :), w, h)));
% And now also the alpha channel (if available)
alpha = transpose(reshape(pixelsData(4, :, :), w, h));
% Ensure that the results are the expected size, otherwise raise an error
figSize = getpixelposition(gcf);
expectedSize = [figSize(4), figSize(3), 3];
if ~isequal(expectedSize, size(imgData))
error('bad Java screen-capture size!')
end
end
% Export an image file of the figure using print() and then read it into an array
function [imgData, alpha, err, ex] = getPrintImage(fig, res_str, renderer, tmp_nam)
imgData = []; % fix for issue #254
err = false;
ex = [];
alpha = [];
% Temporarily set the paper size
fig = ancestor(fig, 'figure'); % just in case it's not a figure...
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);
try %if using_hg2(fig) % HG2 (R2014b or newer)
% Use print('-RGBImage') directly (a bit faster than via temp image file)
imgData = print(fig, renderer, res_str, '-RGBImage');
catch %else % HG1 (R2014a or older)
% Fix issue #83: use numeric handles in HG1
fig = double(fig);
% Print to image file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
imgData = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
end
imgSize = size(imgData); imgSize = imgSize([1,2]); % Fix issue #308
alpha = 255 * ones(imgSize, 'uint8'); % =all pixels opaque
catch ex
err = true;
end
if ~isempty(fp) % this check is not really needed, but makes the code cleaner
set(fp, 'LineWidth',0.75); % restore original figure appearance
end
% Reset the paper size
set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
end
% Return (and create, where necessary) the font path (for use by ghostscript)
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
|
FDYdarmstadt/BoSSS-master
|
append_pdfs.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/append_pdfs.m
| 5,766 |
utf_8
|
a50efac82c3db7107b801335fe5de03d
|
function append_pdfs(varargin)
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(outputFilename, inputFilename1, inputFilename2, ...)
% append_pdfs(outputFilename, inputFilenames_list{:})
% append_pdfs(outputFilename, inputFilenames_cell_or_string_array)
% append_pdfs output.pdf input1.pdf input2.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-2014, Yair Altman 2015-
%{
% 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 quality issue when appending 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
% 24/01/18: Fixed error in case of existing output file (append mode)
% 24/01/18: Fixed issue #213: non-ASCII characters in folder names on Windows
% 06/12/18: Avoid an "invalid escape-char" warning upon error
% 22/03/20: Alert if ghostscript.m is not found on Matlab path
% 29/03/20: Accept a cell-array of input files (issue #299); accept both "strings", 'chars'
%}
if nargin < 2, return; end % sanity check
% Convert strings => chars; strtrim extra spaces
varargin = cellfun(@str2char,varargin,'un',false);
% Convert cell array into individual strings (issue #299)
if nargin==2 && iscell(varargin{2})
varargin = {varargin{1} varargin{2}{:}}; %#ok<CCAT>
end
% Ensure that ghostscript() exists on the Matlab path
if ~exist('ghostscript','file')
error('export_fig:append_pdfs:ghostscript', 'The ghostscript.m function is required by append_pdf.m. Install the complete export_fig package from https://www.mathworks.com/matlabcentral/fileexchange/23629-export_fig or https://github.com/altmany/export_fig')
end
% 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
prepareCmdFile(cmdfile, output, varargin{:});
% Call ghostscript
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
% Check for ghostscript execution errors
if status && ~isempty(strfind(errMsg,'undefinedfile')) && ispc %#ok<STREMP>
% Fix issue #213: non-ASCII characters in folder names on Windows
for fileIdx = 2 : numel(varargin)
[fpath,fname,fext] = fileparts(varargin{fileIdx});
varargin{fileIdx} = fullfile(normalizePath(fpath),[fname fext]);
end
% Rerun ghostscript with the normalized folder names
prepareCmdFile(cmdfile, output, varargin{:});
[status, errMsg] = ghostscript(['@"' cmdfile '"']);
end
% Delete the command file
delete(cmdfile);
% Check for ghostscript execution errors
if status
errMsg = strrep(errMsg,'\','\\'); % Avoid an "invalid escape-char" warning
error('YMA:export_fig:append_pdf',errMsg);
end
% Rename the file if needed
if append
movefile(output, varargin{1}, 'f');
end
end
% Prepare a text file with ghostscript directives
function prepareCmdFile(cmdfile, output, varargin)
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
end
% Convert long/non-ASCII folder names into their short ASCII equivalents
function pathStr = normalizePath(pathStr)
[fpath,fname,fext] = fileparts(pathStr);
if isempty(fpath) || strcmpi(fpath,pathStr), return, end
dirOutput = evalc(['system(''dir /X /AD "' pathStr '*"'')']);
shortName = strtrim(regexprep(dirOutput,{'.*> *',[fname fext '.*']},''));
if isempty(shortName)
shortName = [fname fext];
end
fpath = normalizePath(fpath); %recursive until entire fpath is processed
pathStr = fullfile(fpath, shortName);
end
% Convert a possible string => char
function value = str2char(value)
try
value = controllib.internal.util.hString2Char(value);
catch
if isa(value,'string')
value = char(value);
end
end
value = strtrim(value);
end
|
github
|
FDYdarmstadt/BoSSS-master
|
using_hg2.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/using_hg2.m
| 1,064 |
utf_8
|
a1883d15c4304cd0ac406c117e3047ea
|
%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
|
FDYdarmstadt/BoSSS-master
|
eps2pdf.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/eps2pdf.m
| 12,417 |
utf_8
|
ed3a1249a325dd22b79b3c5de74fa436
|
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 Fabio Viola for pointing out compression artifacts, leading to the quality setting.
% Thank you Scott for pointing out the subsampling of very small images, which was fixed for lossless compression settings.
% 09/12/11: 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)
% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
% 18/10/19: Workaround for GS 9.51+ .setpdfwrite removal problem (issue #285)
% 18/10/19: Warn when ignoring GS fontpath or quality options; clarified error messages
% 15/01/20: Added information about the GS/destination filepath in case of error (issue #294)
% 20/01/20: Attempted fix for issue #285: unsupported patch transparency in some Ghostscript versions
% 12/02/20: Improved fix for issue #285: add -dNOSAFER and -dALLOWPSTRANSPARENCY (thanks @linasstonys)
% 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
qualityOptions = '';
if nargin > 5 && ~isempty(quality)
qualityOptions = ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false';
if quality > 100
qualityOptions = [qualityOptions ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode'];
qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
qualityOptions = [qualityOptions ' -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);
qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDict ' s ' /GrayImageDict ' s ' >> setdistillerparams"'];
end
options = [options qualityOptions];
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 '.pdf'];
[fpath,fname,fext] = fileparts(tmp_nam);
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
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the existing (dest) pdf file to temporary folder
copyfile(dest, tmp_nam);
% Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
ghostscript([options ' -f "' source '"']);
[~,fname] = fileparts(tempname);
tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
copyfile(dest, tmp_nam2);
% Add the existing pdf and interim pdf as inputs to ghostscript
%options = [options ' -f "' tmp_nam '" "' source '"']; % append the source eps to dest pdf
options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate files and rethrow the error
delete(tmp_nam);
delete(tmp_nam2);
rethrow(me);
end
% Delete the intermediate (temporary) files
delete(tmp_nam);
delete(tmp_nam2);
else
% File doesn't exist or should be over-written
% Add the source eps file as input to ghostscript
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Catch and correct undefined .setopacityalpha errors (issue #285)
% (see explanation inside print2eps.m)
if ~isempty(regexpi(message,'undefined in .setopacityalpha'))
% First try with -dNOSAFER and -dALLOWPSTRANSPARENCY (thanks @linasstonys)
new_options = [options ' -dNOSAFER -dALLOWPSTRANSPARENCY'];
[status, message] = ghostscript(new_options);
if ~status % hurray! (no error)
return
elseif isempty(regexpi(message,'undefined in .setopacityalpha')) % still some other error
options = new_options;
else % we still get a .setopacityalpha error
% Remove the transparency and retry
fstrm = read_write_entire_textfile(source);
fstrm = regexprep(fstrm, '0?\.\d+ .setopacityalpha \w+\n', '');
read_write_entire_textfile(source, fstrm);
[status, message] = ghostscript(options);
if ~status % hurray! (no error)
% Alert the user that transparency is not supported
warning('export_fig:GS:quality','Export_fig Face/Edge alpha transparancy is ignored - not supported by your Ghostscript version')
return
end
end
end
% 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, message] = ghostscript(options);
if ~status % hurray! (no error)
warning('export_fig:GS:fontpath','Export_fig font option is ignored - not supported by your Ghostscript version')
return
end
end
% Retry without quality options (may solve problems with GS 9.51+, issue #285)
if ~isempty(qualityOptions)
options = strrep(orig_options, qualityOptions, '');
[status, message] = ghostscript(options);
if ~status % hurray! (no error)
warning('export_fig:GS:quality','Export_fig quality option is ignored - not supported by your Ghostscript version')
return
end
end
% Report error
if isempty(message)
error(['Unable to generate pdf. Ensure that the destination folder (' fileparts(dest) ') is writable.']);
elseif ~isempty(strfind(message,'/typecheck in /findfont')) %#ok<STREMP>
% 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');
[unused, gs_fonts_file] = user_string('gs_font_path'); %#ok<ASGLU>
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
gs_options = strtrim(gs_options);
fprintf(2, '\nGhostscript error: ');
msg = regexprep(message, '^Error: /([^\n]+).*', '$1');
if ~isempty(msg) && ~strcmp(msg,message)
fprintf(2,'%s',msg);
end
fprintf(2, '\n * perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' * or maybe your Ghostscript version does not accept the extra "%s" option(s) that you requested\n', gs_options);
end
fprintf(2, ' * or maybe you have another gs executable in your system''s path\n\n');
fprintf(2, 'Ghostscript path: %s\n', user_string('ghostscript'));
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
|
FDYdarmstadt/BoSSS-master
|
export_fig.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/export_fig.m
| 114,187 |
utf_8
|
60eebe0aeb4a134ee0f596a8eba2c27e
|
function [imageData, alpha] = export_fig(varargin) %#ok<*STRCL1>
%EXPORT_FIG Exports figures in a publication-quality format
%
% Examples:
% imageData = export_fig
% [imageData, alpha] = export_fig
% export_fig filename
% export_fig filename -format1 -format2
% export_fig ... -nocrop
% export_fig ... -c[<val>,<val>,<val>,<val>]
% export_fig ... -transparent
% export_fig ... -native
% export_fig ... -m<val>
% export_fig ... -r<val>
% export_fig ... -a<val>
% export_fig ... -q<val>
% export_fig ... -p<val>
% export_fig ... -d<gs_option>
% export_fig ... -depsc
% export_fig ... -<renderer>
% export_fig ... -<colorspace>
% export_fig ... -append
% export_fig ... -bookmark
% export_fig ... -clipboard<:format>
% export_fig ... -update
% export_fig ... -version
% export_fig ... -nofontswap
% export_fig ... -font_space <char>
% export_fig ... -linecaps
% export_fig ... -noinvert
% export_fig ... -preserve_size
% export_fig ... -options <optionsStruct>
% export_fig ... -silent
% export_fig ... -regexprep <pattern> <replace>
% 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, tif)
% - Semi-transparent patch objects supported (png, tif)
% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tif)
% - Variable image compression, including lossless (pdf, eps, jpg)
% - Optional rounded line-caps (pdf, eps)
% - Optionally append to file (pdf, tif)
% - Vector formats: pdf, eps, emf, svg
% - Bitmap formats: png, tif, jpg, bmp, clipboard, 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, TIF & PNG are the only formats that support a transparent
% background; only TIF & PNG formats support transparency of patch objects.
%
% The choice of renderer (opengl/zbuffer/painters) has a large impact on the
% output quality. The default value (opengl for bitmaps, painters for vector
% formats) generally gives good results, but if you aren't satisfied
% then try another renderer. Notes:
% 1) For vector formats (EPS,PDF), only painters generates vector graphics
% 2) For bitmap formats, only opengl correctly renders transparent patches
% 3) For bitmap formats, only painters correctly scales 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://xpdfreader.com
%
% SVG output uses the fig2svg (https://github.com/kupiqu/fig2svg) or plot2svg
% (https://github.com/jschwizer99/plot2svg) utilities, or Matlab's built-in
% SVG export if neither of these utilities are available on Matlab's path.
% Note: cropping/padding are not supported in export_fig's SVG and EMF output.
%
% Inputs:
% 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.
% -<format> - string(s) containing the output file extension(s). Options:
% '-pdf', '-eps', 'emf', '-svg', '-png', '-tif', '-jpg' and '-bmp'.
% Multiple formats can be specified, without restriction.
% For example: export_fig('-jpg', '-pdf', '-png', ...)
% Note: '-tif','-tiff' are equivalent, and so are '-jpg','-jpeg'.
% -transparent - option indicating that the figure background is to be made
% transparent (PNG,PDF,TIF,EPS,EMF formats only). Implies -noinvert.
% -nocrop - option indicating that empty margins should not be cropped.
% -c[<val>,<val>,<val>,<val>] - option indicating crop amounts. Must be
% a 4-element vector of numeric values: [top,right,bottom,left]
% where NaN/Inf indicates auto-cropping, 0 means no cropping, any
% other value means cropping in pixel amounts. e.g. '-c7,15,0,NaN'
% Note: this option is not supported by SVG and EMF formats.
% -p<val> - option to pad a border of width val to exported files, where
% val is either a relative size with respect to cropped image
% size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats,
% val can also be integer in units of 1/72" points (abs(val)>1).
% val can be positive (padding) or negative (extra cropping).
% If used, the -nocrop flag will be ignored, i.e. the image will
% always be cropped and then padded. Default: 0 (i.e. no padding).
% Note: this option is not supported by SVG and EMF formats.
% -m<val> - option val indicates the factor to magnify the figure dimensions
% when generating bitmap outputs (does not affect vector formats).
% Default: '-m1' (i.e. val=1). Note: val~=1 slows down export_fig.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap and vector outputs, without changing dimensions of
% the on-screen figure. Default: '-r864' (for vector output only).
% Note: -m option overides -r option for bitmap exports 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 (AA) to
% use for bitmap outputs, when GraphicsSmoothing is not available.
% '-a1'=no AA; '-a4'=max. Default: 3 for HG1, 1 for HG2.
% -<renderer> - option to force a particular renderer (painters, opengl or
% [in R2014a or older] zbuffer). Default value: opengl for bitmap
% formats or figures with patches and/or transparent annotations;
% painters for vector formats without patches/transparencies.
% -<colorspace> - option indicating which colorspace color figures should
% be saved in: RGB (default), CMYK or gray. Usage example: '-gray'.
% Note: CMYK is only supported in PDF, EPS and TIF formats.
% -q<val> - option to vary bitmap image quality (PDF, EPS, JPG formats only).
% A larger val, in the range 0-100, produces higher quality and
% lower compression. val > 100 results in 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 image type.
% -append - option indicating that if the file already exists the figure is to
% be appended as a new page, instead of being overwritten (default).
% PDF & TIF output formats only.
% -bookmark - option to indicate that a bookmark with the name of the
% figure is to be created in the output file (PDF format only).
% -clipboard - option to save output as an image on the system clipboard.
% -clipboard<:format> - copies to clipboard in the specified format:
% image (default), bitmap, emf, or pdf.
% Notes: Only -clipboard (or -clipboard:image, which is the same)
% applies export_fig parameters such as cropping, padding etc.
% Only the emf format supports -transparent background
% -clipboard:image create a bitmap image using export_fig processing
% -clipboard:bitmap create a bitmap image as-is (no auto-cropping etc.)
% -clipboard:emf is vector format without auto-cropping; Windows-only
% -clipboard:pdf is vector format without cropping; not universally supported
% -d<gs_option> - option to indicate a ghostscript setting. For example,
% -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).
% -depsc - option to use EPS level-3 rather than the default level-2 print
% device. This solves some bugs with Matlab's default -depsc2 device
% such as discolored subplot lines on images (vector formats only).
% -update - option to download and install the latest version of export_fig
% -version - return the current export_fig version, without any figure export
% -nofontswap - option to avoid font swapping. Font swapping is automatically
% done in vector formats (only): 11 standard Matlab fonts are
% replaced by the original figure fonts. This option prevents this.
% -font_space <char> - option to set a spacer character for font-names that
% contain spaces, used by EPS/PDF. Default: ''
% -linecaps - option to create rounded line-caps (vector formats only).
% -noinvert - option to avoid setting figure's InvertHardcopy property to
% 'off' during output (this solves some problems of empty outputs).
% -preserve_size - option to preserve the figure's PaperSize property in output
% file (PDF/EPS formats only; default is to not preserve it).
% -options <optionsStruct> - format-specific parameters as defined in Matlab's
% documentation of the imwrite function, contained in a struct under
% the format name. For example to specify the JPG Comment parameter,
% pass a struct such as this: options.JPG.Comment='abc'. Similarly,
% options.PNG.BitDepth=4. Valid only for PNG,TIF,JPG output formats.
% -silent - option to avoid various warning and informational messages, such
% as version update checks, transparency or renderer issues, etc.
% -regexprep <old> <new> - replaces all occurances of <old> (a regular expression
% string or array of strings; case-sensitive), with the corresponding
% <new> string(s), in EPS/PDF files (only). See regexp function's doc.
% Warning: invalid replacement can make your EPS/PDF file unreadable!
% handle - The handle of the figure, axes or uipanels (can be an array of
% handles, but the objects must be in the same figure) which is
% to be saved. Default: gcf (handle of current figure).
%
% Outputs:
% imageData - MxNxC uint8 image array of the exported image.
% alpha - MxN single array of alphamatte values in the range [0,1],
% for the case when the background is transparent.
%
% Some helpful examples and tips can be found at:
% https://github.com/altmany/export_fig
%
% See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange)
%{
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
% 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.
% 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
% 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier)
% 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b)
% 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes)
% 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany; Indented main function; Added top-level try-catch block to display useful workarounds
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
% 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue
% 26/03/15: Fixed issue #42: non-normalized annotations on HG1
% 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels
% 27/03/15: Fixed issue #39: bad export of transparent annotations/patches
% 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42
% 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk
% 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51)
% 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file
% 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358)
% 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0)
% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
% 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45)
% 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014)
% 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015)
% 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export
% 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr)
% 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen)
% 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15)
% 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21
% 29/05/15: Added informative error message in case user requested SVG output (issue #72)
% 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG
% 19/06/15: Added -update option to download and install the latest version of export_fig
% 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF
% 16/07/15: Fixed problem with anti-aliasing on old Matlab releases
% 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params
% 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108)
% 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously
% 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta)
% 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
% 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX)
% 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX)
% 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149)
% 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151)
% 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168)
% 11/12/16: Added alert in case of error creating output PDF/EPS file (issue #179)
% 13/12/16: Minor fix to the commit for issue #179 from 2 days ago
% 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present
% 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)
% 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number
% 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used
% 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194)
% 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197)
% 08/11/17: Fixed issue #220: axes exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
% 08/11/17: Fixed issue #221: alert if the requested folder does not exist
% 19/11/17: Workaround for issue #207: alert when trying to use transparent bgcolor with -opengl
% 29/11/17: Workaround for issue #206: warn if exporting PDF/EPS for a figure that contains an image
% 11/12/17: Fixed issue #230: use OpenGL renderer when exported image contains transparency (also see issue #206)
% 30/01/18: Updated SVG message to point to https://github.com/kupiqu/plot2svg and display user-selected filename if available
% 27/02/18: Fixed issue #236: axes exponent cropped from output if on right-hand axes
% 29/05/18: Fixed issue #245: process "string" inputs just like 'char' inputs
% 13/08/18: Fixed issue #249: correct black axes color to off-black to avoid extra cropping with -transparent
% 27/08/18: Added a possible file-open reason in EPS/PDF write-error message (suggested by "craq" on FEX page)
% 22/09/18: Xpdf website changed to xpdfreader.com
% 23/09/18: Fixed issue #243: only set non-bold font (workaround for issue #69) in R2015b or earlier; warn if changing font
% 23/09/18: Workaround for issue #241: don't use -r864 in EPS/PDF outputs when -native is requested (solves black lines problem)
% 18/11/18: Issue #261: Added informative alert when trying to export a uifigure (which is not currently supported)
% 13/12/18: Issue #261: Fixed last commit for cases of specifying axes/panel handle as input, rather than a figure handle
% 13/01/19: Issue #72: Added basic SVG output support
% 04/02/19: Workaround for issues #207 and #267: -transparent implies -noinvert
% 08/03/19: Issue #269: Added ability to specify format-specific options for PNG,TIF,JPG outputs; fixed help section
% 21/03/19: Fixed the workaround for issues #207 and #267 from 4/2/19 (-transparent now does *NOT* imply -noinvert; -transparent output should now be ok in all formats)
% 12/06/19: Issue #277: Enabled preservation of figure's PaperSize in output PDF/EPS file
% 06/08/19: Remove warning message about obsolete JavaFrame in R2019b
% 30/10/19: Fixed issue #261: added support for exporting uifigures and uiaxes (thanks to idea by @MarvinILA)
% 12/12/19: Added warning in case user requested anti-aliased output on an aliased HG2 figure (issue #292)
% 15/12/19: Added promo message
% 08/01/20: (3.00) Added check for newer version online (initialized to version 3.00)
% 15/01/20: (3.01) Clarified/fixed error messages; Added error IDs; easier -update; various other small fixes
% 20/01/20: (3.02) Attempted fix for issue #285 (unsupported patch transparency in some Ghostscript versions); Improved suggested fixes message upon error
% 03/03/20: (3.03) Suggest to upload problematic EPS file in case of a Ghostscript error in eps2pdf (& don't delete this file)
% 22/03/20: (3.04) Workaround for issue #15; Alert if ghostscript file not found on Matlab path
% 10/05/20: (3.05) Fix the generated SVG file, based on Cris Luengo's SVG_FIX_VIEWBOX; Don't generate PNG when only SVG is requested
% 02/07/20: (3.06) Significantly improved performance (speed) and fidelity of bitmap images; Return alpha matrix for bitmap images; Fixed issue #302 (-update bug); Added EMF output; Added -clipboard formats (image,bitmap,emf,pdf); Added hints for exportgraphics/copygraphics usage in certain use-cases; Added description of new version features in the update message; Fixed issue #306 (yyaxis cropping); Fixed EPS/PDF auto-cropping with -transparent
% 06/07/20: (3.07) Fixed issue #307 (bug in padding of bitmap images); Fixed axes transparency in -clipboard:emf with -transparent
% 07/07/20: (3.08) Fixed issue #308 (bug in R2019a and earlier)
% 18/07/20: (3.09) Fixed issue #310 (bug with tiny image on HG1); Fixed title cropping bug
% 23/07/20: (3.10) Fixed issues #313,314 (figure position changes if units ~= pixels); Display multiple versions change-log, if relevant; Fixed issue #312 (PNG: only use alpha channel if -transparent was requested)
% 30/07/20: (3.11) Fixed issue #317 (bug when exporting figure with non-pixels units); Potential solve also of issue #303 (size change upon export)
% 14/08/20: (3.12) Fixed some exportgraphics/copygraphics compatibility messages; Added -silent option to suppress non-critical messages; Reduced promo message display rate to once a week; Added progress messages during export_fig('-update')
% 07/10/20: (3.13) Added version info and change-log links to update message (issue #322); Added -version option to return the current export_fig version; Avoid JavaFrame warning message; Improved exportgraphics/copygraphics infomercial message inc. support of upcoming Matlab R2021a
% 10/12/20: (3.14) Enabled user-specified regexp replacements in generated EPS/PDF files (issue #324)
%}
if nargout
[imageData, alpha] = deal([]);
end
displaySuggestedWorkarounds = true;
% Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date
drawnow;
pause(0.02); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem)
% Display promo (just once a week!)
try promo_time = getpref('export_fig','promo_time'); catch, promo_time=-inf; end
if abs(now-promo_time) > 7 && ~isdeployed
programsCrossCheck;
msg = 'For professional Matlab assistance, please contact <$>';
url = 'https://UndocumentedMatlab.com/consulting';
displayPromoMsg(msg, url);
setpref('export_fig','promo_time',now)
end
% Parse the input arguments
fig = get(0, 'CurrentFigure');
argNames = {};
for idx = nargin:-1:1, argNames{idx} = inputname(idx); end
[fig, options] = parse_args(nargout, fig, argNames, varargin{:});
% Check for newer version and exportgraphics/copygraphics compatibility
currentVersion = 3.14;
if options.version % export_fig's version requested - return it and bail out
imageData = currentVersion;
return
end
if ~options.silent
% Check for newer version (not too often)
checkForNewerVersion(3.14); % ...(currentVersion) is better but breaks in version 3.05- due to regexp limitation in checkForNewerVersion()
% Hint to users to use exportgraphics/copygraphics in certain cases
alertForExportOrCopygraphics(options);
%return
end
% Ensure that we have a figure handle
if isequal(fig,-1)
return % silent bail-out
elseif isempty(fig)
error('export_fig:NoFigure','No figure found');
else
oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
warning off MATLAB:ui:javaframe:PropertyToBeRemoved
uifig = handle(ancestor(fig,'figure'));
try jf = get(uifig,'JavaFrame_I'); catch, try jf = get(uifig,'JavaFrame'); catch, jf=1; end, end %#ok<JAVFM>
warning(oldWarn);
if isempty(jf) % this is a uifigure
%error('export_fig:uifigures','Figures created using the uifigure command or App Designer are not supported by export_fig. See %s for details.', hyperlink('https://github.com/altmany/export_fig/issues/261','issue #261'));
if numel(fig) > 1
error('export_fig:uifigure:multipleHandles', 'export_fig only supports exporting a single uifigure handle at a time; array of handles is not currently supported.')
elseif ~any(strcmpi(fig.Type,{'figure','axes'}))
error('export_fig:uifigure:notFigureOrAxes', 'export_fig only supports exporting a uifigure or uiaxes handle; other handles of a uifigure are not currently supported.')
end
% fig is either a uifigure or uiaxes handle
isUiaxes = strcmpi(fig.Type,'axes');
if isUiaxes
% Label the specified axes so that we can find it in the legacy figure
oldUserData = fig.UserData;
tempStr = tempname;
fig.UserData = tempStr;
end
try
% Create an invisible legacy figure at the same position/size as the uifigure
hNewFig = figure('Units',uifig.Units, 'Position',uifig.Position, 'MenuBar','none', 'ToolBar','none', 'Visible','off');
% Copy the uifigure contents onto the new invisible legacy figure
try
hChildren = allchild(uifig); %=uifig.Children;
copyobj(hChildren,hNewFig);
catch
if ~options.silent
warning('export_fig:uifigure:controls', 'Some uifigure controls cannot be exported by export_fig and will not appear in the generated output.');
end
end
try fig.UserData = oldUserData; catch, end % restore axes UserData, if modified above
% Replace the uihandle in the input args with the legacy handle
if isUiaxes % uiaxes
% Locate the corresponding axes handle in the new legacy figure
hAxes = findall(hNewFig,'type','axes','UserData',tempStr);
if isempty(hAxes) % should never happen, check just in case
hNewHandle = hNewFig; % export the figure instead of the axes
else
hNewHandle = hAxes; % new axes handle found: use it instead of the uiaxes
end
else % uifigure
hNewHandle = hNewFig;
end
varargin(cellfun(@(c)isequal(c,fig),varargin)) = {hNewHandle};
% Rerun export_fig on the legacy figure (with the replaced handle)
[imageData, alpha] = export_fig(varargin{:});
% Delete the temp legacy figure and bail out
try delete(hNewFig); catch, end
return
catch err
% Clean up the temp legacy figure and report the error
try delete(hNewFig); catch, end
rethrow(err)
end
end
end
% 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('export_fig:BadHandle','Handle must be that of a figure, axes or uipanel');
end
% Get the old InvertHardcopy mode
old_mode = get(fig, 'InvertHardcopy');
end
% from this point onward, fig is assured to be a figure handle
% 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 = findall(fig, 'FontUnits', 'normalized');
if ~isempty(fontu)
% Some normalized font units found
if ~cls
fig = copyfig(fig);
set(fig, 'Visible', 'off');
fontu = findall(fig, 'FontUnits', 'normalized');
cls = true;
end
set(fontu, 'FontUnits', 'points');
end
end
try
% 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'));
Xlabel = make_cell(get(Hlims, 'XTickLabelMode'));
Ylabel = make_cell(get(Hlims, 'YTickLabelMode'));
Zlabel = make_cell(get(Hlims, 'ZTickLabelMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
% Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual');
set_tick_mode(Hlims, 'X');
set_tick_mode(Hlims, 'Y');
if ~using_hg2(fig)
set(Hlims,'ZLimMode', 'manual');
set_tick_mode(Hlims, 'Z');
end
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
% Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF)
try
if using_hg2(fig) && isvector(options)
% Set the FontWeight of axes labels/titles to 'normal'
% Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.)
% Issue #243: only set non-bold font (workaround for issue #69) in R2015b or earlier
try isPreR2016a = verLessThan('matlab','8.7'); catch, isPreR2016a = true; end
if isPreR2016a
texLabels = findall(fig, 'type','text', 'FontWeight','bold');
symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\'));
if ~isempty(symbolIdx)
set(texLabels(symbolIdx), 'FontWeight','normal');
if ~options.silent
warning('export_fig:BoldTexLabels', 'Bold labels with Tex symbols converted into non-bold in export_fig (fix for issue #69)');
end
end
end
end
catch
% ignore
end
% Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug)
annotationHandles = [];
try
if ~using_hg2(fig)
annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm');
try % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015
originalUnits = get(annotationHandles,'Units');
set(annotationHandles,'Units','norm');
catch
end
end
catch
% should never happen, but ignore in any case - issue #50
end
% Fix issue #46: Ghostscript crash if figure units <> pixels
pos = get(fig, 'Position'); % Fix issues #313, #314
oldFigUnits = get(fig,'Units');
set(fig,'Units','pixels');
pixelpos = get(fig, 'Position'); %=getpixelposition(fig);
tcol = get(fig, 'Color');
tcol_orig = tcol;
% Set to print exactly what is there
if options.invert_hardcopy
try set(fig, 'InvertHardcopy', 'off'); catch, end % fail silently in uifigures
end
% 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
try
tmp_nam = ''; % initialize
% Do the bitmap formats first
if isbitmap(options)
if abs(options.bb_padding) > 1
displaySuggestedWorkarounds = false;
error('export_fig:padding','For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1')
end
% Print large version to array
[A, tcol, alpha] = getFigImage(fig, magnify, renderer, options, pixelpos);
% Get the background colour
if options.transparent && (options.png || options.alpha)
try %options.aa_factor < 4 % default, faster but lines are not anti-aliased
% If all pixels are indicated as opaque (i.e. something went wrong with the Java screen-capture)
isBgColor = A(:,:,1) == tcol(1) & ...
A(:,:,2) == tcol(2) & ...
A(:,:,3) == tcol(3);
% Set the bgcolor pixels to be fully-transparent
A(repmat(isBgColor,[1,1,3])) = 255; %=white % TODO: more memory efficient without repmat
alpha(isBgColor) = 0;
catch % older logic - much slower and causes figure flicker
if true % to fold the code below...
% Get out an alpha channel
% MATLAB "feature": black colorbar axes can change to white and vice versa!
hCB = findall(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
% Set the background colour to black, and set size in case it was
% changed internally
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]);
% Correct black axes color to off-black (issue #249)
hAxes = findall(fig, 'Type','axes');
[hXs,hXrs] = fixBlackAxle(hAxes, 'XColor');
[hYs,hYrs] = fixBlackAxle(hAxes, 'YColor');
[hZs,hZrs] = fixBlackAxle(hAxes, 'ZColor');
% The following code might cause out-of-memory errors
try
% Print large version to array
B = print2array(fig, magnify, renderer);
% Downscale the image
B = downsize(single(B), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
B = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% 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]);
% Revert the black axes colors
set(hXs, 'XColor', [0,0,0]);
set(hYs, 'YColor', [0,0,0]);
set(hZs, 'ZColor', [0,0,0]);
set(hXrs, 'Color', [0,0,0]);
set(hYrs, 'Color', [0,0,0]);
set(hZrs, 'Color', [0,0,0]);
% The following code might cause out-of-memory errors
try
% Print large version to array
A = print2array(fig, magnify, renderer);
% Downscale the image
A = downsize(single(A), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
A = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% Workaround for issue #15
szA = size(A);
szB = size(B);
if ~isequal(szA,szB)
A = A(1:min(szA(1),szB(1)), 1:min(szA(2),szB(2)), :);
B = B(1:min(szA(1),szB(1)), 1:min(szA(2),szB(2)), :);
if ~options.silent
warning('export_fig:bitmap:sizeMismatch','Problem detected by export_fig generation of a bitmap image; the generated export may look bad. Try to reduce the figure size to fit the screen, or avoid using export_fig''s -transparent option.')
end
end
% 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
end %folded code...
end
%A = uint8(A);
end
% Downscale the image if its size was increased (for anti-aliasing)
if size(A,1) > 1.1 * options.magnify * pixelpos(4) %1.1 to avoid edge-cases
% Downscale the image
A = downsize(A, options.aa_factor);
alpha = downsize(alpha, options.aa_factor);
end
% Crop the margins based on the bgcolor, if requested
if options.crop
%[alpha, v] = crop_borders(alpha, 0, 1, options.crop_amounts);
%A = A(v(1):v(2),v(3):v(4),:);
[A, vA, vB] = crop_borders(A, tcol, options.bb_padding, options.crop_amounts);
if ~any(isnan(vB)) % positive padding
sz = size(A); % Fix issue #308
B = repmat(uint8(zeros(1,1,size(alpha,3))),sz([1,2])); % Fix issue #307 %=zeros(sz([1,2]),'uint8');
B(vB(1):vB(2), vB(3):vB(4), :) = alpha(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH
alpha = B;
else % negative padding
alpha = alpha(vA(1):vA(2), vA(3):vA(4), :);
end
end
% Get the non-alpha image (presumably unneeded with Java-based screen-capture)
%{
if isbitmap(options)
% Modify the intensity of the pixels' RGB values based on their alpha transparency
% TODO: not sure that we want this with Java screen-capture values!
alph = alpha(:,:,ones(1, size(A, 3)));
A = uint8(single(A) .* alph + 255 * (1 - alph));
end
%}
% Revert the figure properties back to their original values
set(fig, 'Units',oldFigUnits, 'Position',pos, 'Color',tcol_orig);
% Check for greyscale images
if options.colourspace == 2
% Convert to greyscale
A = rgb2grey(A);
else
% Return only one channel for greyscale
A = check_greyscale(A);
end
% Change alpha from [0:255] uint8 => [0:1] single from here onward:
alpha = single(alpha) / 255;
% Outputs
if options.im
imageData = A;
end
if options.alpha
imageData = A;
%alpha = ones(size(A, 1), size(A, 2), 'single'); %=all pixels opaque
end
% Save the images
if options.png
% Compute the resolution
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
% Save the png
[format_options, bitDepth] = getFormatOptions(options, 'png'); %Issue #269
pngOptions = {[options.name '.png'], 'ResolutionUnit','meter', 'XResolution',res, 'YResolution',res, format_options{:}}; %#ok<CCAT>
if options.transparent % Fix issue #312: only use alpha channel if -transparent was requested
pngOptions = [pngOptions 'Alpha',double(alpha)];
end
if ~isempty(bitDepth) && bitDepth < 16 && size(A,3) == 3
% BitDepth specification requires using a color-map
[A, map] = rgb2ind(A, 256);
imwrite(A, map, pngOptions{:});
else
imwrite(A, pngOptions{:});
end
end
if options.bmp
imwrite(A, [options.name '.bmp']);
end
if options.jpg
% Save jpeg with the specified quality
quality = options.quality;
if isempty(quality)
quality = 95;
end
format_options = getFormatOptions(options, 'jpg'); %Issue #269
if quality > 100
imwrite(A, [options.name '.jpg'], 'Mode','lossless', format_options{:});
else
imwrite(A, [options.name '.jpg'], 'Quality',quality, format_options{:});
end
end
if options.tif
% Save tif images in cmyk if wanted (and possible)
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'};
format_options = getFormatOptions(options, 'tif'); %Issue #269
imwrite(A, [options.name '.tif'], 'Resolution',options.magnify*get(0,'ScreenPixelsPerInch'), 'WriteMode',append_mode{options.append+1}, format_options{:});
end
end
% Now do the vector formats which are based on EPS
if isvector(options)
hImages = findall(fig,'type','image');
% Set the default renderer to painters
if ~options.renderer
% Handle transparent patches
hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1));
if hasTransparency
% Alert if trying to export transparent patches/areas to non-supported outputs (issue #108)
% http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces
% TODO - use transparency when exporting to PDF by not passing via print2eps
msg = 'export_fig currently supports transparent patches/areas only in PNG output. ';
if options.pdf && ~options.silent
warning('export_fig:transparency', '%s\nTo export transparent patches/areas to PDF, use the print command:\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name);
elseif ~options.png && ~options.tif && ~options.silent % issue #168
warning('export_fig:transparency', '%s\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg);
end
elseif ~isempty(hImages)
% Fix for issue #230: use OpenGL renderer when exported image contains transparency
for idx = 1 : numel(hImages)
cdata = get(hImages(idx),'CData');
if any(isnan(cdata(:)))
hasTransparency = true;
break
end
end
end
hasPatches = ~isempty(findall(fig,'type','patch'));
if hasTransparency || hasPatches
% This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
renderer = '-opengl';
else
renderer = '-painters';
end
end
options.rendererStr = renderer; % fix for issue #112
% Generate some filenames
tmp_nam = [tempname '.eps'];
try
% Ensure that the temp dir is writable (Javier Paredes 30/1/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the user-specified folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(options.name);
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if isTempDirOk
pdf_nam_tmp = [tempname '.pdf'];
else
pdf_nam_tmp = fullfile(fpath,[fname '.pdf']);
end
if options.pdf
pdf_nam = [options.name '.pdf'];
try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65
else
pdf_nam = pdf_nam_tmp;
end
% Generate the options for print
printArgs = {renderer};
if ~isempty(options.resolution) % issue #241
printArgs{end+1} = sprintf('-r%d', options.resolution);
end
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
%printArgs{end+1} = '-cmyk';
end
if ~options.crop
% Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism,
% therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders)
%printArgs{end+1} = '-loose';
end
if any(strcmpi(varargin,'-depsc'))
% Issue #45: lines in image subplots are exported in invalid color.
% The workaround is to use the -depsc parameter instead of the default -depsc2
printArgs{end+1} = '-depsc';
end
% Print to EPS file
try
% Remove background if requested (issue #207)
originalBgColor = get(fig, 'Color');
[hXs, hXrs, hYs, hYrs, hZs, hZrs] = deal([]);
if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
if options.renderer == 1 && ~options.silent % OpenGL
warning('export_fig:openglTransparentBG', '-opengl sometimes fails to produce transparent backgrounds; in such a case, try to use -painters instead');
end
% Fix for issue #207, #267 (corrected)
set(fig,'Color','none');
% Correct black axes color to off-black (issue #249)
hAxes = findall(fig, 'Type','axes');
[hXs,hXrs] = fixBlackAxle(hAxes, 'XColor');
[hYs,hYrs] = fixBlackAxle(hAxes, 'YColor');
[hZs,hZrs] = fixBlackAxle(hAxes, 'ZColor');
% Correct black titles to off-black
% https://www.mathworks.com/matlabcentral/answers/567027-matlab-export_fig-crops-title
try
hTitle = get(hAxes, 'Title');
for idx = numel(hTitle) : -1 : 1
color = get(hTitle,'Color');
if isequal(color,[0,0,0]) || isequal(color,'k')
set(hTitle(idx), 'Color', [0,0,0.01]); %off-black
else
hTitle(idx) = []; % remove from list
end
end
catch
hTitle = [];
end
end
% Generate an eps
print2eps(tmp_nam, fig, options, printArgs{:});
% {
% Remove the background, if desired
if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
eps_remove_background(tmp_nam, 1 + using_hg2(fig));
% Revert the black axes colors
set(hXs, 'XColor', [0,0,0]);
set(hYs, 'YColor', [0,0,0]);
set(hZs, 'ZColor', [0,0,0]);
set(hXrs, 'Color', [0,0,0]);
set(hYrs, 'Color', [0,0,0]);
set(hZrs, 'Color', [0,0,0]);
set(hTitle,'Color',[0,0,0]);
end
%}
% Restore the figure's previous background color (if modified)
try set(fig,'Color',originalBgColor); drawnow; catch, end
% Fix colorspace to CMYK, if requested (workaround for issue #33)
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
change_rgb_to_cmyk(tmp_nam);
end
% Add a bookmark to the PDF if desired
if options.bookmark
fig_nam = get(fig, 'Name');
if isempty(fig_nam) && ~options.silent
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_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
% Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file
try
% Rename the file (except if it is already the same)
% Abbie K's comment on the commit for issue #179 (#commitcomment-20173476)
if ~isequal(pdf_nam_tmp, pdf_nam)
movefile(pdf_nam_tmp, pdf_nam, 'f');
end
catch
% Alert in case of error creating output PDF/EPS file (issue #179)
if exist(pdf_nam_tmp, 'file')
errMsg = ['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions, or the file is open in another application'];
error('export_fig:PDF:create',errMsg);
else
error('export_fig:NoEPS','Could not generate the intermediary EPS file.');
end
end
catch ex
% Restore the figure's previous background color (in case it was not already restored)
try set(fig,'Color',originalBgColor); drawnow; catch, end
% Delete the temporary eps file - NOT! (Yair 3/3/2020)
%delete(tmp_nam);
% Rethrow the EPS/PDF-generation error
rethrow(ex);
end
% Delete the eps
delete(tmp_nam);
if options.eps || options.linecaps
try
% Generate an eps from the pdf
% since pdftops can't handle relative paths (e.g., '..\'), use a temp file
eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps');
pdf2eps(pdf_nam, eps_nam_tmp);
% Issue #192: enable rounded line-caps
if options.linecaps
fstrm = read_write_entire_textfile(eps_nam_tmp);
fstrm = regexprep(fstrm, '[02] J', '1 J');
read_write_entire_textfile(eps_nam_tmp, fstrm);
if options.pdf
eps2pdf(eps_nam_tmp, pdf_nam, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
end
end
if options.eps
movefile(eps_nam_tmp, [options.name '.eps'], 'f');
else % if options.pdf
try delete(eps_nam_tmp); catch, end
end
catch ex
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
try delete(eps_nam_tmp); catch, end
rethrow(ex);
end
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
end
% Issue #206: warn if the figure contains an image
if ~isempty(hImages) && strcmpi(renderer,'-opengl') && ~options.silent % see addendum to issue #206
warnMsg = ['exporting images to PDF/EPS may result in blurry images on some viewers. ' ...
'If so, try to change viewer, or increase the image''s CData resolution, or use -opengl renderer, or export via the print function. ' ...
'See ' hyperlink('https://github.com/altmany/export_fig/issues/206', 'issue #206') ' for details.'];
warning('export_fig:pdf_eps:blurry_image', warnMsg);
end
end
% SVG format
if options.svg
filename = [options.name '.svg'];
% Adapted from Dan Joshea's https://github.com/djoshea/matlab-save-figure :
try %if verLessThan('matlab', '8.4')
% Try using the fig2svg/plot2svg utilities
try
fig2svg(filename, fig); %https://github.com/kupiqu/fig2svg
catch
plot2svg(filename, fig); %https://github.com/jschwizer99/plot2svg
if ~options.silent
warning('export_fig:SVG:plot2svg', 'export_fig used the plot2svg utility for SVG output. Better results may be gotten via the fig2svg utility (https://github.com/kupiqu/fig2svg).');
end
end
catch %else % (neither fig2svg nor plot2svg are available)
% Try Matlab's built-in svg engine (from Batik Graphics2D for java)
try
set(fig,'Units','pixels'); % All data in the svg-file is saved in pixels
printArgs = {renderer};
if ~isempty(options.resolution)
printArgs{end+1} = sprintf('-r%d', options.resolution);
end
print(fig, '-dsvg', printArgs{:}, filename);
if ~options.silent
warning('export_fig:SVG:print', 'export_fig used Matlab''s built-in SVG output engine. Better results may be gotten via the fig2svg utility (https://github.com/kupiqu/fig2svg).');
end
catch err % built-in print() failed - maybe an old Matlab release (no -dsvg)
filename = strrep(filename,'export_fig_out','filename');
msg = ['SVG output is not supported for your figure: ' err.message '\n' ...
'Try one of the following alternatives:\n' ...
' 1. saveas(gcf,''' filename ''')\n' ...
' 2. fig2svg utility: https://github.com/kupiqu/fig2svg\n' ... % Note: replaced defunct https://github.com/jschwizer99/plot2svg with up-to-date fork on https://github.com/kupiqu/fig2svg
' 3. export_fig to EPS/PDF, then convert to SVG using non-Matlab tools\n'];
error('export_fig:SVG:error',msg);
end
end
% SVG output was successful if we reached this point
% Add warning about unsupported export_fig options with SVG output
if ~options.silent && (any(~isnan(options.crop_amounts)) || any(options.bb_padding))
warning('export_fig:SVG:options', 'export_fig''s SVG output does not [currently] support cropping/padding.');
end
% Fix the generated SVG file, based on Cris Luengo's SVG_FIX_VIEWBOX:
% https://www.mathworks.com/matlabcentral/fileexchange/49617-svg_fix_viewbox-in_name-varargin
try
% Read SVG file
s = read_write_entire_textfile(filename);
% Fix fonts #1: 'SansSerif' doesn't work on my browser, the correct CSS is 'sans-serif'
s = regexprep(s,'font-family:SansSerif;|font-family:''SansSerif'';','font-family:''sans-serif'';');
% Fix fonts #1: The document-wide default font is 'Dialog'. What is this anyway?
s = regexprep(s,'font-family:''Dialog'';','font-family:''sans-serif'';');
% Replace 'width="xxx" height="yyy"' with 'width="100%" viewBox="0 0 xxx yyy"'
t = regexp(s,'<svg.* width="(?<width>[0-9]*)" height="(?<height>[0-9]*)"','names');
if ~isempty(t)
relativeWidth = 100; %TODO - user-settable via input parameter?
s = regexprep(s,'(?<=<svg[^\n]*) width="[0-9]*" height="[0-9]*"',sprintf(' width="%d\\%%" viewBox="0 0 %s %s"',relativeWidth,t.width,t.height));
end
% Write updated SVG file
read_write_entire_textfile(filename, s);
catch
% never mind - ignore
end
end
% EMF format
if options.emf
try
anythingChanged = false;
% Handle transparent bgcolor request
if options.transparent && ~isequal(tcol_orig,'none')
anythingChanged = true;
set(fig, 'Color','none');
end
if ~options.silent
if ~ispc
warning('export_fig:EMF:NotWindows', 'EMF is only supported on Windows; exporting to EMF format on this machine may result in unexpected behavior.');
elseif isequal(renderer,'-painters') && (options.resolution~=864 || options.magnify~=1)
warning('export_fig:EMF:Painters', 'export_fig -r and -m options are ignored for EMF export using the -painters renderer.');
elseif abs(get(0,'ScreenPixelsPerInch')*options.magnify - options.resolution) > 1e-6
warning('export_fig:EMF:Magnify', 'export_fig -m option is ignored for EMF export.');
end
if ~isequal(options.bb_padding,0) || ~isempty(options.quality)
warning('export_fig:EMF:Options', 'export_fig cropping, padding and quality options are ignored for EMF export.');
end
if ~anythingChanged
warning('export_fig:EMF:print', 'For a figure without background transparency, export_fig uses Matlab''s built-in print(''-dmeta'') function without any extra processing, so try using it directly.');
end
end
printArgs = {renderer};
if ~isempty(options.resolution)
printArgs{end+1} = sprintf('-r%d', options.resolution);
end
filename = [options.name '.emf'];
print(fig, '-dmeta', printArgs{:}, filename);
catch err % built-in print() failed - maybe an old Matlab release (no -dsvg)
msg = ['EMF output is not supported: ' err.message '\n' ...
'Try to use export_fig with other formats, such as PDF or EPS.\n'];
error('export_fig:EMF:error',msg);
end
end
% Revert the figure or close it (if requested)
if cls || options.closeFig
% Close the created figure
close(fig);
else
% Reset the hardcopy mode
try set(fig, 'InvertHardcopy', old_mode); catch, end % fail silently in uifigures
% Reset the axes limit and tick modes
for a = 1:numel(Hlims)
try
set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},...
'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},...
'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a});
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
end
% Revert the tex-labels font weights
try set(texLabels, 'FontWeight','bold'); catch, end
% Revert annotation units
for handleIdx = 1 : numel(annotationHandles)
try
oldUnits = originalUnits{handleIdx};
catch
oldUnits = originalUnits;
end
try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end
end
% Revert figure properties in case they were changed
try set(fig, 'Units',oldFigUnits, 'Position',pos, 'Color',tcol_orig); catch, end
end
% Output to clipboard (if requested)
if options.clipboard
% Delete the output file if unchanged from the default name ('export_fig_out.png')
if strcmpi(options.name,'export_fig_out')
try
fileInfo = dir('export_fig_out.png');
if ~isempty(fileInfo)
timediff = now - fileInfo.datenum;
ONE_SEC = 1/24/60/60;
if timediff < ONE_SEC
delete('export_fig_out.png');
end
end
catch
% never mind...
end
end
% Use Java clipboard by default
if strcmpi(options.clipformat,'image')
% Save the image in the system clipboard
% credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard
try
error(javachk('awt', 'export_fig -clipboard output'));
catch
if ~options.silent
warning('export_fig:clipboardJava', 'export_fig -clipboard output failed: requires Java to work');
end
return;
end
try
% Import necessary Java classes
import java.awt.Toolkit %#ok<SIMPT>
import java.awt.image.BufferedImage %#ok<SIMPT>
import java.awt.datatransfer.DataFlavor %#ok<SIMPT>
% Get System Clipboard object (java.awt.Toolkit)
cb = Toolkit.getDefaultToolkit.getSystemClipboard();
% Add java class (ImageSelection) to the path
if ~exist('ImageSelection', 'class')
javaaddpath(fileparts(which(mfilename)), '-end');
end
% Get image size
ht = size(imageData, 1);
wd = size(imageData, 2);
% Convert to Blue-Green-Red format
try
imageData2 = imageData(:, :, [3 2 1]);
catch
% Probably gray-scaled image (2D, without the 3rd [RGB] dimension)
imageData2 = imageData(:, :, [1 1 1]);
end
% Convert to 3xWxH format
imageData2 = permute(imageData2, [3, 2, 1]);
% Append Alpha data (unused - transparency is not supported in clipboard copy)
alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8')
imageData2 = cat(1, imageData2, alphaData2);
% Create image buffer
imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);
imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd);
% Create ImageSelection object from the image buffer
imSelection = ImageSelection(imBuffer);
% Set clipboard content to the image
cb.setContents(imSelection, []);
catch
if ~options.silent
warning('export_fig:clipboardFailed', 'export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
end
end
else % use one of print()'s builtin clipboard formats
% Remove background if requested (EMF format only)
if options.transparent && strcmpi(options.clipformat,'meta')
% Set figure bgcolor to none
originalBgColor = get(fig, 'Color');
set(fig,'Color','none');
% Set axes bgcolor to none
hAxes = findall(fig, 'Type','axes');
originalAxColor = get(hAxes, 'Color');
set(hAxes,'Color','none');
drawnow; %repaint before export
end
% Call print() to create the clipboard output
clipformat = ['-d' options.clipformat];
printArgs = {renderer};
if ~isempty(options.resolution)
printArgs{end+1} = sprintf('-r%d', options.resolution);
end
print(fig, '-clipboard', clipformat, printArgs{:});
% Restore the original background color
try set(fig, 'Color',originalBgColor); catch, end
try set(hAxes, 'Color',originalAxColor); catch, end
drawnow;
end
end
% Don't output the data to console unless requested
if ~nargout
clear imageData alpha
end
catch err
% Revert figure properties in case they were changed
try set(fig,'Units',oldFigUnits, 'Position',pos, 'Color',tcol_orig); catch, end
% Display possible workarounds before the error message
if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error')
isNewerVersionAvailable = checkForNewerVersion(currentVersion); % alert if a newer version exists
if isempty(regexpi(err.message,'Ghostscript'))
fprintf(2, 'export_fig error. ');
end
fprintf(2, 'Please ensure:\n');
fprintf(2, ' * that the function you used (%s.m) version %s is from the expected location\n', mfilename('fullpath'), num2str(currentVersion));
paths = which(mfilename,'-all');
if iscell(paths) && numel(paths) > 1
fprintf(2, ' (you appear to have %s of export_fig installed)\n', hyperlink('matlab:which export_fig -all','multiple versions'));
end
if isNewerVersionAvailable
fprintf(2, ' * and that you are using the %s of export_fig (you are not: run %s to update it)\n', ...
hyperlink('https://github.com/altmany/export_fig/archive/master.zip','latest version'), ...
hyperlink('matlab:export_fig(''-update'')','export_fig(''-update'')'));
end
fprintf(2, ' * and that you did not made a mistake in export_fig''s %s\n', hyperlink('matlab:help export_fig','expected input arguments'));
if isvector(options)
if ismac
url = 'http://pages.uoregon.edu/koch';
else
url = 'http://ghostscript.com';
end
fpath = user_string('ghostscript');
fprintf(2, ' * and that %s is properly installed in %s\n', ...
hyperlink(url,'ghostscript'), ...
hyperlink(['matlab:winopen(''' fileparts(fpath) ''')'], fpath));
end
try
if options.eps
fpath = user_string('pdftops');
fprintf(2, ' * and that %s is properly installed in %s\n', ...
hyperlink('http://xpdfreader.com/download.html','pdftops'), ...
hyperlink(['matlab:winopen(''' fileparts(fpath) ''')'], fpath));
end
catch
% ignore - probably an error in parse_args
end
try
% Alert per issue #149
if ~strncmpi(get(0,'Units'),'pixel',5)
fprintf(2, ' * or try to set groot''s Units property back to its default value of ''pixels'' (%s)\n', hyperlink('https://github.com/altmany/export_fig/issues/149','details'));
end
catch
% ignore - maybe an old MAtlab release
end
fprintf(2, '\nIf the problem persists, then please %s.\n', hyperlink('https://github.com/altmany/export_fig/issues','report a new issue'));
if exist(tmp_nam,'file')
fprintf(2, 'In your report, please upload the problematic EPS file: %s (you can then delete this file).\n', tmp_nam);
end
fprintf(2, '\n');
end
rethrow(err)
end
end
function options = default_options()
% Default options used by export_fig
options = struct(...
'name', 'export_fig_out', ...
'crop', true, ...
'crop_amounts', nan(1,4), ... % auto-crop all 4 image sides
'transparent', false, ...
'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
'pdf', false, ...
'eps', false, ...
'emf', false, ...
'svg', false, ...
'png', false, ...
'tif', false, ...
'jpg', false, ...
'bmp', false, ...
'clipboard', false, ...
'clipformat', 'image', ...
'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
'append', false, ...
'im', false, ...
'alpha', false, ...
'aa_factor', 0, ...
'bb_padding', 0, ...
'magnify', [], ...
'resolution', [], ...
'bookmark', false, ...
'closeFig', false, ...
'quality', [], ...
'update', false, ...
'version', false, ...
'fontswap', true, ...
'font_space', '', ...
'linecaps', false, ...
'invert_hardcopy', true, ...
'format_options', struct, ...
'preserve_size', false, ...
'silent', false, ...
'regexprep', [], ...
'gs_options', {{}});
end
function [fig, options] = parse_args(nout, fig, argNames, varargin)
% Parse the input arguments
% Convert strings => chars
varargin = cellfun(@str2char,varargin,'un',false);
% Set the defaults
native = false; % Set resolution to native of an image
options = default_options();
options.im = (nout == 1); % user requested imageData output
options.alpha = (nout == 2); % user requested alpha output
options.handleName = ''; % default handle name
% Go through the other arguments
skipNext = 0;
for a = 1:nargin-3 % only process varargin, no other parse_args() arguments
if skipNext > 0
skipNext = skipNext-1;
continue;
end
if all(ishandle(varargin{a}))
fig = varargin{a};
options.handleName = argNames{a};
elseif ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
switch lower(varargin{a}(2:end))
case 'nocrop'
options.crop = false;
options.crop_amounts = [0,0,0,0];
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 {'emf','meta'}
options.emf = true;
case 'svg'
options.svg = 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;
case {'clipboard','clipboard:image'}
options.clipboard = true;
options.clipformat = 'image';
options.im = true; %ensure that imageData is created
options.alpha = true;
case 'clipboard:bitmap'
options.clipboard = true;
options.clipformat = 'bitmap';
case {'clipboard:emf','clipboard:meta'}
options.clipboard = true;
options.clipformat = 'meta';
case 'clipboard:pdf'
options.clipboard = true;
options.clipformat = 'pdf';
case 'update'
updateInstalledVersion();
fig = -1; % silent bail-out
case 'version'
options.version = true;
return % ignore any additional args
case 'nofontswap'
options.fontswap = false;
case 'font_space'
options.font_space = varargin{a+1};
skipNext = 1;
case 'linecaps'
options.linecaps = true;
case 'noinvert'
options.invert_hardcopy = false;
case 'preserve_size'
options.preserve_size = true;
case 'options'
% Issue #269: format-specific options
inputOptions = varargin{a+1};
%options.format_options = inputOptions;
if isempty(inputOptions), continue, end
formats = fieldnames(inputOptions(1));
for idx = 1 : numel(formats)
optionsStruct = inputOptions.(formats{idx});
%optionsCells = [fieldnames(optionsStruct) struct2cell(optionsStruct)]';
formatName = regexprep(lower(formats{idx}),{'tiff','jpeg'},{'tif','jpg'});
options.format_options.(formatName) = optionsStruct; %=optionsCells(:)';
end
skipNext = 1;
case 'silent'
options.silent = true;
case 'regexprep'
options.regexprep = varargin(a+1:a+2);
skipNext = 2;
otherwise
try
wasError = false;
if strcmpi(varargin{a}(1:2),'-d')
varargin{a}(2) = 'd'; % ensure lowercase 'd'
options.gs_options{end+1} = varargin{a};
elseif strcmpi(varargin{a}(1:2),'-c')
if strncmpi(varargin{a},'-clipboard:',11)
wasError = true;
error('export_fig:BadOptionValue','option ''%s'' cannot be parsed: only image, bitmap, emf and pdf formats are supported',varargin{a});
end
if numel(varargin{a})==2
skipNext = 1;
vals = str2num(varargin{a+1}); %#ok<ST2NM>
else
vals = str2num(varargin{a}(3:end)); %#ok<ST2NM>
end
if numel(vals)~=4
wasError = true;
error('export_fig:BadOptionValue','option -c cannot be parsed: must be a 4-element numeric vector');
end
options.crop_amounts = vals;
options.crop = true;
else % scalar parameter value
val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
if isempty(val) || isnan(val)
% Issue #51: improved processing of input args (accept space between param name & value)
val = str2double(varargin{a+1});
if isscalar(val) && ~isnan(val)
skipNext = 1;
end
end
if ~isscalar(val) || isnan(val)
wasError = true;
error('export_fig:BadOptionValue','option %s is not recognised or cannot be parsed', varargin{a});
end
switch lower(varargin{a}(2))
case 'm'
% Magnification may never be negative
if val <= 0
wasError = true;
error('export_fig:BadMagnification','Bad magnification value: %g (must be positive)', val);
end
options.magnify = val;
case 'r'
options.resolution = val;
case 'q'
options.quality = max(val, 0);
case 'p'
options.bb_padding = val;
end
end
catch err
% We might have reached here by raising an intentional error
if wasError % intentional raise
rethrow(err)
else % unintentional
error('export_fig:BadOption',['Unrecognized export_fig input option: ''' varargin{a} '''']);
end
end
end
else
[p, options.name, ext] = fileparts(varargin{a});
if ~isempty(p)
% Issue #221: alert if the requested folder does not exist
if ~exist(p,'dir'), error('export_fig:BadPath',['Folder ' p ' does not exist!']); end
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 '.emf'
options.emf = true;
case '.pdf'
options.pdf = true;
case '.fig'
% If no open figure, then load the specified .fig file and continue
figFilename = varargin{a};
if isempty(fig)
fig = openfig(figFilename,'invisible');
varargin{a} = fig;
options.closeFig = true;
options.handleName = ['openfig(''' figFilename ''')'];
else
% save the current figure as the specified .fig file and exit
saveas(fig(1),figFilename);
fig = -1;
return
end
case '.svg'
options.svg = true;
otherwise
options.name = varargin{a};
end
end
end
end
% Quick bail-out if no figure found
if isempty(fig), return; end
% Do border padding with repsect to a cropped image
if options.bb_padding
options.crop = true;
end
% Set default anti-aliasing now we know the renderer
try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end
if isAA
if options.aa_factor > 1 && ~options.silent
warning('export_fig:AntiAliasing','You requested anti-aliased export_fig output of a figure that is already anti-aliased - your -a option in export_fig is ignored.')
end
options.aa_factor = 1; % ignore -a option when the figure is already anti-aliased (HG2)
elseif options.aa_factor == 0 % default
%options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3));
options.aa_factor = 1 + 2 * (~using_hg2(fig)); % =1 in HG2, =3 in HG1
end
if options.aa_factor > 1 && ~isAA && using_hg2(fig) && ~options.silent
warning('export_fig:AntiAliasing','You requested anti-aliased export_fig output of an aliased figure (''GraphicsSmoothing''=''off''). You will see better results if you set your figure''s GraphicsSmoothing property to ''on'' before calling export_fig.')
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
% Set the format to PNG, if no other format was specified
if ~isvector(options) && ~isbitmap(options) && ~options.svg && ~options.emf
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
if isbitmap(options)
% Find a suitable image
list = findall(fig, 'Type','image', 'Tag','export_fig_native');
if isempty(list)
list = findall(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
yl = [min(yl), max(yl)]; % fix issue #151 (case of yl containing more than 2 elements)
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 = abs((height * diff(yl2)) / (pos * diff(yl))); % magnification must never be negative: issue #103
break
end
elseif options.resolution == 864 % don't use -r864 in vector mode if user asked for -native
options.resolution = []; % issue #241 (internal Matlab bug produces black lines with -r864)
end
end
end
% Convert a possible string => char (issue #245)
function value = str2char(value)
if isa(value,'string')
value = char(value);
end
end
function A = downsize(A, factor)
% Downsample an image
if factor <= 1 || isempty(A) %issue #310
% 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);
if padding < 1 || isempty(A), return, end %issue #310
onesPad = ones(1, padding);
for a = 1:size(A,3)
A2 = single(A([onesPad 1:end repmat(end,1,padding)], ...
[onesPad 1:end repmat(end,1,padding)], a));
A(:,:,a) = conv2(filt, filt', A2, '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)); % #ok<ZEROLIKE>
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('export_fig:EPS:open','Cannot 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
function [A, tcol, alpha] = getFigImage(fig, magnify, renderer, options, pos)
if options.transparent
% MATLAB "feature": figure size can change when changing color in -nodisplay mode
set(fig, 'Color', 'w', 'Position', pos);
drawnow; % repaint figure, otherwise Java screencapture will see black bgcolor
end
% Print large version to array
try
% The following code might cause out-of-memory errors
[A, tcol, alpha] = print2array(fig, magnify, renderer);
catch
% This is more conservative in memory, but perhaps kills transparency(?)
[A, tcol, alpha] = print2array(fig, magnify/options.aa_factor, renderer);
end
% In transparent mode, set the bgcolor to white
if options.transparent
% Note: tcol should already be [255,255,255] here, but just in case it's not...
tcol = uint8([255,255,255]); %=white
end
end
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('export_fig:bookmark:FileNotFound','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('export_fig:bookmark:permission','Unable to open %s for writing.', fname);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
function set_tick_mode(Hlims, ax)
% Set the tick mode of linear axes to manual
% Leave log axes alone as these are tricky
M = get(Hlims, [ax 'Scale']);
if ~iscell(M)
M = {M};
end
%idx = cellfun(@(c) strcmp(c, 'linear'), M);
idx = find(strcmp(M,'linear'));
%set(Hlims(idx), [ax 'TickMode'], 'manual'); % issue #187
%set(Hlims(idx), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2!
for idx2 = 1 : numel(idx)
try
% Fix for issue #187 - only set manual ticks when no exponent is present
hAxes = Hlims(idx(idx2));
props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'};
tickVals = get(hAxes,[ax 'Tick']);
tickStrs = get(hAxes,[ax 'TickLabel']);
try % Fix issue #236
exponents = [hAxes.([ax 'Axis']).SecondaryLabel];
catch
exponents = [hAxes.([ax 'Ruler']).SecondaryLabel];
end
if isempty([exponents.String])
% Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number
if numel(tickVals) == numel(tickStrs)
set(hAxes, props{:}); % no exponent and matching ticks, so update both ticks and tick labels to manual
end
end
catch % probably HG1
% Fix for issue #220 - exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
if isequal(tickVals, str2num(tickStrs)') %#ok<ST2NM>
set(hAxes, props{:}); % revert back to old behavior
end
end
end
end
function change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file
% Do post-processing on the eps file
try
% Read the EPS file into memory
fstrm = read_write_entire_textfile(fname);
% Replace all gray-scale colors
fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n');
% Replace all RGB colors
fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n'); % pure black
fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n');
% Overwrite the file with the modified contents
read_write_entire_textfile(fname, fstrm);
catch
% never mind - leave as is...
end
end
function [hBlackAxles, hBlackRulers] = fixBlackAxle(hAxes, axleName)
hBlackAxles = [];
hBlackRulers = [];
for idx = 1 : numel(hAxes)
ax = hAxes(idx);
axleColor = get(ax, axleName);
if isequal(axleColor,[0,0,0]) || isequal(axleColor,'k')
hBlackAxles(end+1) = ax; %#ok<AGROW>
try % Fix issue #306 - black yyaxis
if strcmpi(axleName,'Color'), continue, end %ruler, not axle
rulerName = strrep(axleName,'Color','Axis');
hRulers = get(ax, rulerName);
newBlackRulers = fixBlackAxle(hRulers,'Color');
hBlackRulers = [hBlackRulers newBlackRulers]; %#ok<AGROW>
catch
end
end
end
set(hBlackAxles, axleName, [0,0,0.01]); % off-black
end
% Issue #269: format-specific options
function [optionsCells, bitDepth] = getFormatOptions(options, formatName)
bitDepth = [];
try
optionsStruct = options.format_options.(lower(formatName));
catch
% User did not specify any extra parameters for this format
optionsCells = {};
return
end
optionNames = fieldnames(optionsStruct);
optionVals = struct2cell(optionsStruct);
optionsCells = [optionNames, optionVals]';
if nargout < 2, return, end % bail out if BitDepth is not required
try
idx = find(strcmpi(optionNames,'BitDepth'), 1, 'last');
if ~isempty(idx)
bitDepth = optionVals{idx};
end
catch
% never mind - ignore
end
end
% Check for newer version (only once a day)
function isNewerVersionAvailable = checkForNewerVersion(currentVersion)
persistent lastCheckTime lastVersion
isNewerVersionAvailable = false;
if nargin < 1 || isempty(lastCheckTime) || now - lastCheckTime > 1
url = 'https://raw.githubusercontent.com/altmany/export_fig/master/export_fig.m';
try
str = readURL(url);
[unused,unused,unused,unused,latestVerStrs] = regexp(str, '\n[^:]+: \(([^)]+)\) ([^%]+)(?=\n)'); %#ok<ASGLU>
latestVersion = str2double(latestVerStrs{end}{1});
if nargin < 1
currentVersion = lastVersion;
else
currentVersion = currentVersion + 1e3*eps;
end
isNewerVersionAvailable = latestVersion > currentVersion;
if isNewerVersionAvailable
try
verStrs = strtrim(reshape([latestVerStrs{:}],2,[]));
verNums = arrayfun(@(c)str2double(c{1}),verStrs(1,:));
isValid = verNums > currentVersion;
versionDesc = strjoin(flip(verStrs(2,isValid)),';');
catch
% Something bad happened - only display the latest version description
versionDesc = latestVerStrs{1}{2};
end
try versionDesc = strjoin(strrep(strcat(' ***', strtrim(strsplit(versionDesc,';'))),'***','* '), char(10)); catch, end %#ok<CHARTEN>
msg = sprintf(['You are using version %.2f of export_fig. ' ...
'A newer version (%g) is available, with the following improvements/fixes:\n' ...
'%s\n' ...
'A change-log of recent releases is available here; the complete change-log is included at the top of the export_fig.m file.\n' ... % issue #322
'You can download the new version from GitHub or Matlab File Exchange, ' ...
'or run export_fig(''-update'') to install it directly.' ...
], currentVersion, latestVersion, versionDesc);
msg = hyperlink('https://github.com/altmany/export_fig', 'GitHub', msg);
msg = hyperlink('https://www.mathworks.com/matlabcentral/fileexchange/23629-export_fig', 'Matlab File Exchange', msg);
msg = hyperlink('matlab:export_fig(''-update'')', 'export_fig(''-update'')', msg);
msg = hyperlink('https://github.com/altmany/export_fig/releases', 'available here', msg);
msg = hyperlink('https://github.com/altmany/export_fig/blob/master/export_fig.m#L300', 'export_fig.m file', msg);
warning('export_fig:version',msg);
end
catch
% ignore
end
lastCheckTime = now;
lastVersion = currentVersion;
end
end
% Update the installed version of export_fig from the latest version online
function updateInstalledVersion()
% Download the latest version of export_fig into the export_fig folder
zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip';
fprintf('Downloading latest version of %s from %s...\n', mfilename, zipFileName);
folderName = fileparts(which(mfilename('fullpath')));
targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));
try
folder = hyperlink(['matlab:winopen(''' folderName ''')'], folderName);
catch % hyperlink.m is not properly installed
folder = folderName;
end
try
urlwrite(zipFileName,targetFileName); %#ok<URLWR>
catch err
error('export_fig:update:download','Error downloading %s into %s: %s\n',zipFileName,targetFileName,err.message);
end
% Unzip the downloaded zip file in the export_fig folder
fprintf('Extracting %s...\n', targetFileName);
try
unzip(targetFileName,folderName);
% Fix issue #302 - zip file uses an internal folder export_fig-master
subFolder = fullfile(folderName,'export_fig-master');
try movefile(fullfile(subFolder,'*.*'),folderName, 'f'); catch, end %All OSes
try movefile(fullfile(subFolder,'*'), folderName, 'f'); catch, end %MacOS/Unix
try movefile(fullfile(subFolder,'.*'), folderName, 'f'); catch, end %MacOS/Unix
try rmdir(subFolder); catch, end
catch err
error('export_fig:update:unzip','Error unzipping %s: %s\n',targetFileName,err.message);
end
% Notify the user and rehash
fprintf('Successfully installed the latest %s version in %s\n', mfilename, folder);
clear functions %#ok<CLFUNC>
rehash
end
% Read a file from the web
function str = readURL(url)
try
str = char(webread(url));
catch err %if isempty(which('webread'))
if isempty(strfind(err.message,'404'))
v = version; % '9.6.0.1072779 (R2019a)'
if v(1) >= '8' % '8.0 (R2012b)' https://www.mathworks.com/help/matlab/release-notes.html?rntext=urlread&searchHighlight=urlread&startrelease=R2012b&endrelease=R2012b
str = urlread(url, 'Timeout',5); %#ok<URLRD>
else
str = urlread(url); %#ok<URLRD> % R2012a or older (no Timeout parameter)
end
else
rethrow(err)
end
end
if size(str,1) > 1 % ensure a row-wise string
str = str';
end
end
% Display a promo message in the Matlab console
function displayPromoMsg(msg, url)
%msg = [msg url];
msg = strrep(msg,'<$>',url);
link = ['<a href="' url];
msg = regexprep(msg,url,[link '">$0</a>']);
%msg = regexprep(msg,{'consulting','training'},[link '/$0">$0</a>']);
%warning('export_fig:promo',msg);
disp(['[' 8 msg ']' 8]);
end
% Cross-check existance of other programs
function programsCrossCheck()
try
% IQ
hasTaskList = false;
if ispc && ~exist('IQML','file')
hasIQ = exist('C:/Progra~1/DTN/IQFeed','dir') || ...
exist('C:/Progra~2/DTN/IQFeed','dir');
if ~hasIQ
[status,tasksStr] = system('tasklist'); %#ok<ASGLU>
tasksStr = lower(tasksStr);
hasIQ = ~isempty(strfind(tasksStr,'iqconnect')) || ...
~isempty(strfind(tasksStr,'iqlink')); %#ok<STREMP>
hasTaskList = true;
end
if hasIQ
displayPromoMsg('To connect Matlab to IQFeed, try the IQML connector <$>', 'https://UndocumentedMatlab.com/IQML');
end
end
% IB
if ~exist('IBMatlab','file')
hasIB = false;
possibleFolders = {'C:/Jts','C:/Programs/Jts','C:/Progra~1/Jts','C:/Progra~2/Jts','~/IBJts','~/IBJts/IBJts'};
for folderIdx = 1 : length(possibleFolders)
if exist(possibleFolders{folderIdx},'dir')
hasIB = true;
break
end
end
if ~hasIB
if ~hasTaskList
if ispc % Windows
[status,tasksStr] = system('tasklist'); %#ok<ASGLU>
else % Linux/MacOS
[status,tasksStr] = system('ps -e'); %#ok<ASGLU>
end
tasksStr = lower(tasksStr);
end
hasIB = ~isempty(strfind(tasksStr,'tws')) || ...
~isempty(strfind(tasksStr,'ibgateway')); %#ok<STREMP>
end
if hasIB
displayPromoMsg('To connect Matlab to IB try the IB-Matlab connector <$>', 'https://UndocumentedMatlab.com/IB-Matlab');
end
end
catch
% never mind - ignore error
end
end
% Hint to users to use exportgraphics/copygraphics in certain cases
function alertForExportOrCopygraphics(options)
%matlabVerNum = str2num(regexprep(version,'(\d+\.\d+).*','$1'));
try
% Bail out on R2019b- (copygraphics/exportgraphics not available/reliable)
if verLessThan('matlab','9.8') % 9.8 = R2020a
return
end
isNoRendererSpecified = options.renderer == 0;
isPainters = options.renderer == 3;
noResolutionSpecified = isempty(options.resolution) || isequal(options.resolution,864);
% First check for copygraphics compatibility (export to clipboard)
params = ',';
if options.clipboard
if options.transparent % -transparent was requested
if isPainters || isNoRendererSpecified % painters or default renderer
if noResolutionSpecified
params = '''BackgroundColor'',''none'',''ContentType'',''vector'',';
else % exception: no message
params = ',';
end
else % opengl/zbuffer renderer
if options.invert_hardcopy % default
params = '''BackgroundColor'',''white'',';
else % -noinvert was requested
params = '''BackgroundColor'',''current'','; % 'none' is 'white' when ContentType='image'
end
params = [params '''ContentType'',''image'','];
if ~noResolutionSpecified
params = [params '''Resolution'',' num2str(options.resolution) ','];
else
% don't add a resolution param
end
end
else % no -transparent
if options.invert_hardcopy % default
params = '''BackgroundColor'',''white'',';
else % -noinvert was requested
params = '''BackgroundColor'',''current'',';
end
if isPainters % painters (but not default!) renderer
if noResolutionSpecified
params = [params '''ContentType'',''vector'','];
else % exception: no message
params = ',';
end
else % opengl/zbuffer/default renderer
params = [params '''ContentType'',''image'','];
if ~noResolutionSpecified
params = [params '''Resolution'',' num2str(options.resolution) ','];
else
% don't add a resolution param
end
end
end
% If non-RGB colorspace was requested on R2021a+
if ~verLessThan('matlab','9.10') % 9.10 = R2021a
if options.colourspace == 2 % gray
params = [params '''Colorspace'',''gray'','];
end
end
end
displayMsg(params, 'copygraphics', 'clipboard', '');
% Next check for exportgraphics compatibility (export to file)
% Note: not <else>, since -clipboard can be combined with file export
params = ',';
if ~options.clipboard
if options.transparent % -transparent was requested
if isvector(options) % vector output
if isPainters || isNoRendererSpecified % painters or default renderer
if noResolutionSpecified
params = '''BackgroundColor'',''none'',''ContentType'',''vector'',';
else % exception: no message
params = ',';
end
else % opengl/zbuffer renderer
params = '''BackgroundColor'',''none'',''ContentType'',''vector'',';
end
else % non-vector output
params = ',';
end
else % no -transparent
if options.invert_hardcopy % default
params = '''BackgroundColor'',''white'',';
else % -noinvert was requested
params = '''BackgroundColor'',''current'',';
end
if isvector(options) % vector output
if isPainters || isNoRendererSpecified % painters or default renderer
if noResolutionSpecified
params = [params '''ContentType'',''vector'','];
else % exception: no message
params = ',';
end
else % opengl/zbuffer renderer
if noResolutionSpecified
params = [params '''ContentType'',''image'','];
else % exception: no message
params = ',';
end
end
else % non-vector output
if isPainters % painters (but not default!) renderer
% exception: no message
params = ',';
else % opengl/zbuffer/default renderer
if ~noResolutionSpecified
params = [params '''Resolution'',' num2str(options.resolution) ','];
end
end
end
end
% If non-RGB colorspace was requested on R2021a+
if ~verLessThan('matlab','9.10') % 9.10 = R2021a
if options.colourspace == 2 % gray
params = [params '''Colorspace'',''gray'','];
elseif options.colourspace == 1 && options.eps % cmyk (eps only)
params = [params '''Colorspace'',''cmyk'','];
end
end
end
filenameParam = 'filename,'; %=[options.name ','];
displayMsg(params, 'exportgraphics', 'file', filenameParam);
catch
% Ignore errors - do not stop export_fig processing
end
% Utility function to display an alert message
function displayMsg(params, funcName, type, filenameParam)
if length(params) > 1
% strip default param values from the message
params = strrep(params, '''BackgroundColor'',''white'',', '');
% strip the trailing ,
if ~isempty(params) && params(end)==',', params(end)=''; end
% if this message was not already displayed
try prevParams = getpref('export_fig',funcName); catch, prevParams = ''; end
if ~strcmpi(params, prevParams)
% display the message (TODO: perhaps replace warning() with fprintf()?)
if ~isempty([filenameParam params])
filenameParam = [',' filenameParam];
end
if ~isempty(filenameParam) && filenameParam(end)==',' && isempty(params)
filenameParam(end) = '';
end
handleName = options.handleName;
if isempty(options.handleName) % handle was either not specified, or via gca()/gcf() etc. [i.e. not by variable]
handleName = 'hFigure';
end
msg = ['In Matlab R2020a+ you can also use ' funcName '(' handleName filenameParam params ') for simple ' type ' export'];
oldWarn = warning('on','verbose');
warning(['export_fig:' funcName], msg);
warning(oldWarn);
setpref('export_fig',funcName,params);
end
end
end
end
|
github
|
FDYdarmstadt/BoSSS-master
|
ghostscript.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/ghostscript.m
| 8,296 |
utf_8
|
4f0e9071f894361b54efeec2a89de95c
|
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 a Ghostscript installation on your system.
% You can download Ghostscript from http://ghostscript.com (Windows/Linux)
% or http://pages.uoregon.edu/koch (MacOS).
%
% 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
% 15/01/20 - Various message cleanups/fixes in case of errors
%}
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 * %s ', hg2_str, hyperlink(url1));
if using_hg2
fprintf(2, '(GS 9.10)\n * %s (R2014a)', hyperlink(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 * %s\n\n', hyperlink(url3));
% issue #20
% TODO: in Unix/Mac, find a way to automatically determine whether to use "export" (bash) or "setenv" (csh/tcsh)
if isdeployed
url = [mfilename '.m'];
else
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
url = ['<a href="matlab:opentoline(''' fpath ''',201)">' fpath '</a>'];
end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export ..." to "setenv ..."\nat the bottom of %s\n\n', url);
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 on MacOS
uiwait(warndlg('Ghostscript installation not found - please locate the program.', 'Ghostscript'))
base = uigetdir('/', 'Ghostcript program location');
else
base = uigetdir('/', 'Ghostcript program not found - please locate it');
end
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
url = 'http://pages.uoregon.edu/koch';
else
url = 'http://ghostscript.com';
end
error('Ghostscript:NotFound', 'Ghostscript not found. Have you installed it from %s ?', hyperlink(url));
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');
[unused, filename] = user_string('ghostscript'); %#ok<ASGLU>
warning('Ghostscript:path', '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 automatically 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
|
FDYdarmstadt/BoSSS-master
|
fix_lines.m
|
.m
|
BoSSS-master/examples/Oscillating-Droplet/plotData/export_fig-master/fix_lines.m
| 6,290 |
utf_8
|
8437006b104957762090e3d875688cb6
|
%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
|
FDYdarmstadt/BoSSS-master
|
UXStagMap.m
|
.m
|
BoSSS-master/examples/PrintingNip/UXStagMap.m
| 3,577 |
utf_8
|
d53d105117d8a405e6a773708facebd8
|
clc
clear all
% create figure 11 in Pressure and shear flow singularities: fluid splitting and printing nip hydrodynamics
% Matthias Elia Rieckmann, Pauline Brumm, Hans Martin Sauer, Edgar Doersam, Florian Kummer
% Physics of Fluids, 2023
opts = detectImportOptions('PrintingNip-Part4.csv');
% preview('PrintingNip-Part4.csv', opts)
dat = readtable('PrintingNip-Part4.csv', opts);
dat = dat(~isnan(dat.dPdXatStagnationPoint),:);
uVals = sort(unique(dat.id_V_Wall));
xVals = sort(unique(dat.id_X_Stag));
uVals = uVals(2:end-1);
xVals = xVals(2:end-1);
[A, B] = meshgrid(uVals,xVals);
C = zeros(size(A));
for i=1:size(A,1)
for j=1:size(A,2)
t = dat(dat.id_V_Wall == A(i,j) & dat.id_X_Stag == B(i,j),'dPdXatStagnationPoint');
C(i,j) = t.dPdXatStagnationPoint;
end
end
dat2 = importdata('ExperimentalResults.txt');
dat2 = dat2.data;
s = 0.027;
e = 0.0395;
UExp = dat2(:,2);
PExp = 16.*dat2(:,3)*100.*dat2(:,3)*100.*s;
XExp = sqrt(sqrt(UExp.*8.*e./PExp) .* 0.1);
U = dat.id_V_Wall;
X = dat.id_X_Stag;
P = dat.dPdXatStagnationPoint;
idx = ~isnan(P);
U = U(idx);
X = X(idx);
P = P(idx);
PlotMap(A,B,C,UExp,XExp,PExp);
set(gcf,'Position',[10 10 1000 800]);
h = gcf;
% exportgraphics(h,'UXPMap.pdf','ContentType','image','Resolution',120)
% scatter3(U,X,P); hold on;
% surf(A,B,C);
% set(gca,'Xscale','log','Zscale','log','Yscale','log')
% xlabel('$u \, \left[\frac{m}{s}\right]$','Interpreter','latex')
% ylabel('$x_m \, \left[m\right]$','Interpreter','latex')
% zlabel('$\frac{\partial p}{\partial x} \, \left[\frac{N}{m^3}\right]$','Interpreter','latex')
% scatter3(UExp,XExp,PExp);
% legend('Simulation', '', 'Experiment')
%
% hold off;
function PlotMap(xdata1, ydata1, zdata1, X2, Y2, Z2)
%CREATEFIGURE(X1, Y1, Z1, S1, C1, xdata1, ydata1, zdata1, X2, Y2, Z2, C2)
% X1: scatter3 x
% Y1: scatter3 y
% Z1: scatter3 z
% S1: scatter3 s
% C1: scatter3 c
% XDATA1: surface xdata
% YDATA1: surface ydata
% ZDATA1: surface zdata
% X2: scatter3 x
% Y2: scatter3 y
% Z2: scatter3 z
% C2: scatter3 c
% Auto-generated by MATLAB on 28-Jun-2022 21:24:22
% Create figure
figure1 = figure;
% Create axes
axes1 = axes('Parent',figure1);
hold(axes1,'on');
% Create surf
surf(xdata1,ydata1,zdata1,'DisplayName','Simulation','Parent',axes1,...
'MarkerFaceColor',[0.850980401039124 0.325490206480026 0.0980392172932625],...
'MarkerEdgeColor','none',...
'MarkerSize',8,...
'Marker','o',...
'LineStyle','--',...
'FaceColor',[0.800000011920929 0.800000011920929 0.800000011920929]);
% Create scatter3
scatter3(X2,Y2,Z2,'DisplayName','Experiment','LineWidth',3,...
'Marker','square');
% Create zlabel
zlabel('$\frac{\partial p}{\partial x} \, \left[\frac{N}{m^3}\right]$',...
'Interpreter','latex');
% Create ylabel
ylabel('$x_m \, \left[m\right]$','Interpreter','latex');
% Create xlabel
xlabel('$u \, \left[\frac{m}{s}\right]$','Interpreter','latex');
view(axes1,[-70.6037109375001 15.654718798151]);
grid(axes1,'on');
hold(axes1,'off');
% Set the remaining axes properties
set(axes1,'FontSize',20,'OuterPosition',[0.13 0 0.775 0.9075],'XMinorTick',...
'on','XScale','log','YMinorTick','on','YScale','log','ZMinorTick','on',...
'ZScale','log');
% Create legend
legend1 = legend(axes1,'show');
set(legend1,...
'Position',[0.46715748823633 0.834166775403636 0.101466273527341 0.0929791245051079]);
end
|
github
|
FDYdarmstadt/BoSSS-master
|
CounterDiffusionFlameMain.m
|
.m
|
BoSSS-master/src/L4-application/XNSEC2/Worksheets/Jupyter/CounterFlowFlameMatlabCode/CounterDiffusionFlameMain.m
| 7,612 |
utf_8
|
8e42a5476f7fd7dd50e67defbda010a4
|
close all;clear; clc;
%% Problem geometry description
C.L = 0.02; % Domain length, m
C.cp = 1.3; % Heat capacity;
C.initialCellNumber = 100;
useBoSSSForInitialization = true;
C.chemActive = true;
C.variableKineticParameters = true;
velocityMultiplier = 11;
%% Boundary conditions
if useBoSSSForInitialization
% Read bosss data
path = ['C:\tmp\BoSSS_data_VariableChemParams_cpmixture_nonunityLe\', num2str(velocityMultiplier), '\'];
bosss_x = load([path, 'FullXCoord.txt']);
bosssVelocityX = load([path, 'FullVelocityX.txt']);
bosssTemperature = load([path, 'FullTemperature.txt']);
bosssY0 = load([path, 'FullMassFraction0.txt']);
bosssY1 = load([path, 'FullMassFraction1.txt']);
bosssY2 = load([path, 'FullMassFraction2.txt']);
bosssY3 = load([path, 'FullMassFraction3.txt']);
bosssY4 = ones(1, length(bosssY0)) - (bosssY0 + bosssY1 + bosssY2 + bosssY3);
C.vLeft = bosssVelocityX(1); % Velocity left (fuel)
C.vRight = bosssVelocityX(end); % Velocity right (oxidizer)
C.TF0 = bosssTemperature(1); % Temperature left (fuel)
C.TO0 = bosssTemperature(2); % Temperature right (oxidizer)
C.fuelInletConcentration = [bosssY0(1), bosssY1(1), bosssY2(1), bosssY3(1), bosssY4(1)];
C.oxidizerInletConcentration = [bosssY0(end), bosssY1(end), bosssY2(end), bosssY3(end), bosssY4(end)];
else
C.vLeft = 0.0243 * velocityMultiplier; % Velocity left (fuel)
C.vRight = -0.0243 * velocityMultiplier * 3; % Velocity right (oxidizer)
C.TF0 = 300; % Temperature left (fuel)
C.TO0 = 300; % Temperature right (oxidizer)
C.fuelInletConcentration = [0.2, 0.0, 0.0, 0.0, 0.8];
C.oxidizerInletConcentration = [0.0, 0.23, 0.0, 0.0, 0.77];
end
%% Chemistry
C.p0 = 101325; % Pressure, Pa
C.viscosity0 = 1.716e-5; % kg/( m s) ==> viscosity at T = 273.15 for air
C.Tref = 273; % Reference temperature from powerlaw
C.a = 2 / 3; % PowerLaw exponent
C.Coef_Stoic = [-1, -2, 1, 2, 0]; % Chemical reaction 1CH4 + 2O2 -> 1CO2 + 2H2O
C.MM = [16, 32, 44, 18, 28];
C.s = (C.Coef_Stoic (2) * C.MM(2)) / (C.Coef_Stoic(1) * C.MM(1));
C.phi = C.s * C.fuelInletConcentration(1) / C.oxidizerInletConcentration(2);
C.zst = 1.0 / (1.0 + C.phi);
C.Q = 50100;
C.R = 8.314 * 1000; % gas constant, kg m^2 / (s^2 K mol)
%% Calculate flame sheet (infinite reaction rate)
x = zeros(1);
newSolution = zeros(1);
lambdaOut = 100;
if C.chemActive
[mySolution, lambdaOut] = CounterFlowFlame_MixtureFraction(C);
fprintf('Finished calculation of MF\n');
% plotMixtureFractionSolution(mySolution,C);
x = mySolution(1, :);
myzeros = zeros(1, length(x)); %% initial values for the derivatives not known,
newSolution = [mySolution(2, :); mySolution(3, :); mySolution(4, :); mySolution(5, :); ...
myzeros; mySolution(6, :); myzeros; mySolution(7, :); myzeros; mySolution(8, :); ...
myzeros; mySolution(9, :); myzeros; mySolution(10, :); myzeros];
end
%% Full Problem, first strain
[xint, Sxint, calculatedStrain, calculatedMaxTemperature] = CounterFlowFlame_FullChemistry(C, newSolution, x, lambdaOut);
% plotFullProblem(xint,Sxint);
figure
hold on
plot(xint, Sxint(4, :));
hold on
plot(mySolution(1, :), mySolution(5, :));
legend('')
%% Compare Matlab with BoSSS Solution
if useBoSSSForInitialization
%bosss_x = bosss_x + 0.02; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
%VelocityX
subplot(3, 3, 1)
plot(xint, Sxint(1, :))
hold on;
plot(bosss_x, bosssVelocityX)
legend('VelocityXMatlab', 'VelocityXBoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('VelocityX')
xlabel('x')
ylabel('u')
hold off;
%Temperature
subplot(3, 3, 2)
plot(xint, Sxint(4, :))
hold on;
plot(bosss_x, bosssTemperature)
legend('Matlab', 'BoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('Temperature')
xlabel('x')
ylabel('T')
hold off;
%MassFractions
subplot(3, 3, 3)
plot(xint, Sxint(6, :))
hold on;
plot(bosss_x, bosssY0)
legend('Matlab', 'BoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('MassFraction 0')
xlabel('x')
ylabel('Y0')
%MassFractions
subplot(3, 3, 4)
plot(xint, Sxint(8, :))
hold on;
plot(bosss_x, bosssY1)
legend('Matlab', 'BoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('MassFraction 1')
xlabel('x')
ylabel('Y1')
hold off;
%MassFractions
subplot(3, 3, 5)
plot(xint, Sxint(10, :))
hold on;
plot(bosss_x, bosssY2)
legend('Matlab', 'BoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('MassFraction CO2')
xlabel('x')
ylabel('Y4')
hold off;
%MassFractions
subplot(3, 3, 6)
plot(xint, Sxint(14, :))
hold on;
plot(bosss_x, bosssY4)
legend('Matlab', 'BoSSS')
xlim([xint(1), xint(end)])
ylim auto
title('MassFraction N2')
xlabel('x')
ylabel('Y4')
hold off;
for k = 1:length(xint)
phi(k) = GetPhi(Sxint(6, k), Sxint(8, k));
if phi(k) > 1.5
phi(k) = 1.5;
end
end
subplot(3, 3, 7)
plot(xint, phi)
legend('Matlab')
xlim([xint(1), xint(end)])
ylim auto
title('Phi, local')
xlabel('x')
ylabel('phi')
hold off;
%% Reaction rate
for k = 1:length(xint)
Y0 = Sxint(6, k);
Y1 = Sxint(8, k);
Y2 = Sxint(10, k);
Y3 = Sxint(12, k);
Y4 = Sxint(14, k);
T = Sxint(4, k);
density = 101325 / (8314 * T * (Y0 / 16 + Y1 / 32 + Y2 / 44 + Y3 / 18 + Y4 / 28));
reacRate(k) = 6.9e11 * exp(-15900/T) * density * density * Y0 * Y1 / (16 * 32);
end
subplot(3, 3, 8)
plot(xint, reacRate)
legend('Matlab')
xlim([xint(1), xint(end)])
ylim auto
title('ReactionRate')
xlabel('x')
ylabel('Y0Y1')
hold off;
end
%% Save matlab result to textfile
writetable(table(xint', Sxint(1, :)'), fullfile(path, 'FullVelocityX_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(xint', Sxint(4, :)'), fullfile(path, 'FullTemperature_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(xint', Sxint(6, :)'), fullfile(path, 'FullMassFraction0_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(xint', Sxint(8, :)'), fullfile(path, 'FullMassFraction1_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(xint', Sxint(10, :)'), fullfile(path, 'FullMassFraction2_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(xint', Sxint(12, :)'), fullfile(path, 'FullMassFraction3_MATLAB.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssVelocityX'), fullfile(path, 'FullVelocityX_BOSSS.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssTemperature'), fullfile(path, 'FullTemperature_BOSSS.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssY0'), fullfile(path, 'FullMassFraction0_BOSSS.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssY1'), fullfile(path, 'FullMassFraction1_BOSSS.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssY2'), fullfile(path, 'FullMassFraction2_BOSSS.txt'), 'Delimiter', ' ')
writetable(table(bosss_x', bosssY3'), fullfile(path, 'FullMassFraction3_BOSSS.txt'), 'Delimiter', ' ')
function viscosity = mu(T)
viscosity0 = 1.716e-5; % kg/( m s) ==> viscosity at T = 273.15 for air
viscosity_constant = viscosity0;
Tref = 273;
a = 2 / 3;
viscosity_variable = viscosity0 * (T / Tref)^(a);
viscosity = viscosity_constant * (1 - multiplier) + viscosity_variable * multiplier;
end
function phi = GetPhi(YF, YO)
s = 4;
YF0 = 0.2;
YO0 = 0.23;
phi = (s * YF0 / YO0) * (s * YF - YO + YO0) / (s * (YF0 - YF) + YO);
end
|
github
|
FDYdarmstadt/BoSSS-master
|
CounterFlowFlame_FullChemistry.m
|
.m
|
BoSSS-master/src/L4-application/XNSEC2/Worksheets/Jupyter/CounterFlowFlameMatlabCode/CounterFlowFlame_FullChemistry.m
| 9,872 |
utf_8
|
7d2c1703e9d63766b0709fc2da980ec7
|
%%Initial solution is [v,U1,U2,TO0,Y1_1,Y2_1,Y3_1,Y4_1,Y5_1]
%% Solves the one-dimensional countrflow diffusion flame in cartesian coordinates
function [xint, Sxint, calculatedStrain, maxTemperature] = CounterFlowFlame_FullChemistry2(C, newSolution, xinit, lambda)
%% Solver configuration
cpconstant = true;
chemActive = C.chemActive;
variableKineticParameters = C.variableKineticParameters;
Prandtl = 0.75;
Le = [1.0,1.0,1.0,1.0,1.0];
% Prandtl = 1.0;%
%% Problem description
L = C.L; % Domain length, m
cp = C.cp; % Heat capacity;
s = C.s;
p0 = C.p0; % Pressure, Pa
R = C.R; % gas constant, kg m^2 / (s^2 K mol)
MM = C.MM;
v0 = C.vLeft;
vl = C.vRight;
Coef_Stoic = C.Coef_Stoic;
Tref = C.Tref;
B = 6.9e11; % Pre-exponential factor 6.9e14 cm3/(mol s) => 6.9e11m3/(kmol s)
Ta0 = 15900; %K
massHeatRelease = C.Q * MM(1);
viscosity0 = C.viscosity0;
%% Boundary Condition values
TF0 = C.TF0; % Temperature left (fuel)
TO0 = C.TO0; % Temperature right (oxidizer)
YLeft = C.fuelInletConcentration;
YRight = C.oxidizerInletConcentration;
YF0 = YLeft(1);
YO0 = YRight(2);
if (chemActive)
sol = bvpinit(xinit, @mat4init, lambda);
sol.y = newSolution;
else
sol = bvpinit(linspace(0, L, 100), @mat4init, 10);
end
%% =====================================================================
% Solve system
options = bvpset('stats', 'true', 'Vectorized', 'off', 'NMax', 10000, 'AbsTol', 1e-6, 'RelTol', 1e-3);
sol = bvp4c(@mat4ode, @mat4bc, sol, options);
lambda = sol.parameters;
fprintf('Turning on variable Cp\n');
cpconstant = false;
maxCpValue = 0;
max_x = 0;
Le = [0.97, 1.11, 1.39, 0.83, 1.0];
sol = bvp4c(@mat4ode, @mat4bc, sol, options);
Sxint = deval(sol, linspace(0, L, 1000));
calculatedStrain = max(abs(Sxint(2, :)));
fprintf('Strain (biggest du/dy magnitude): %7.3f.\n', calculatedStrain);
maxTemperature = max(Sxint(4, :));
fprintf('Maximum temperature: %7.3f.\n', maxTemperature);
fprintf('Maximum cp: %7.3f.\n', maxCpValue);
fprintf('Position of maximum cp: %7.6f.\n', max_x);
xint = linspace(0, L, 200);
Sxint = deval(sol, xint);
%% -----------------------------------------------------------------------
% Note: the system to be solved is of first order on v, second order on U,
% and second order on the scalars (T, Y1,Y2...)
% Second order equations are brought to a first order by introducing a
% transformation
function dydx = mat4ode(x, y, lambda) % equation being solved
v = y(1);
U1 = y(2);
U2 = y(3);
T1 = y(4); % T
T2 = y(5); % dT/dy
Y1_1 = y(6); % Y1
Y1_2 = y(7); % dY1/dy
Y2_1 = y(8);
Y2_2 = y(9);
Y3_1 = y(10);
Y3_2 = y(11);
Y4_1 = y(12);
Y4_2 = y(13);
Y5_1 = y(14);
Y5_2 = y(15);
Yk_1 = [Y1_1; Y2_1; Y3_1; Y4_1; Y5_1];
Yk_2 = [Y1_2, Y2_2, Y3_2, Y4_2, Y5_2]; % Array of derivatives
% Try to "repair" temperature and mass fractions fields by limiting their value
T1(T1 < 300) = 300;
Yk_1(Yk_1 < 0) = 0;
Yk_1(Yk_1 > 1) = 1;
%% Density and transport parameters
rho_ = rho(T1, Yk_1);
rho_p = drhody(T1, T2, Yk_1, Yk_2);
mu_ = mu(T1);
mu_p = dmu_dy(T1, T2);
if cpconstant
cp = C.cp;
else
% cp = getComponentCp(T1, 'N2');
cp = getMixtureCp(T1, Yk_1, ["CH4", "O2", "CO2", "H2O", "N2"]);
if cp > maxCpValue
max_x = x;
maxCpValue = cp;
end
end
k_cp = mu_ / (Prandtl); % k/cp = mu / pr
k_cp_p = mu_p / (Prandtl);
rhoD1 = mu_ / (Prandtl*Le(1));
rhoD2 = mu_/ (Prandtl*Le(2));
rhoD3 = mu_ / (Prandtl*Le(3));
rhoD4 = mu_ /(Prandtl* Le(4));
rhoD5 = mu_ / (Prandtl*Le(5));
rhoD1_p = mu_p / (Prandtl*Le(1));
rhoD2_p = mu_p / (Prandtl*Le(2));
rhoD3_p = mu_p /(Prandtl* Le(3));
rhoD4_p = mu_p / (Prandtl*Le(4));
rhoD5_p = mu_p /(Prandtl* Le(5));
Q = getHeatRelease(Yk_1);
omega = getReactionRate(T1, Yk_1);
%
dydx = [(-rho_ * U1 - rho_p * v) / rho_; ... %Conti
U2; ... %Mom
(lambda + rho_ * v * U2 + rho_ * U1^2 - mu_p * U2) * 1.0 / mu_; ... %Mom
T2; ... .%Energy
( rho_ * vss * T2 - k_cp_p * T2 - Q * omega/cp) / (k_cp); ... %Energy
Y1_2; ... .%MassFraction1
(rho_ * v * Y1_2 - rhoD1_p * Y1_2 - omega * Coef_Stoic(1) * MM(1)) / (rhoD1); ... %MassFraction1
Y2_2; ... .%MassFraction2
(rho_ * v * Y2_2 - rhoD2_p * Y2_2 - omega * Coef_Stoic(2) * MM(2)) / (rhoD2); ... %MassFraction2
Y3_2; ... .%MassFraction3
(rho_ * v * Y3_2 - rhoD3_p * Y3_2 - omega * Coef_Stoic(3) * MM(3)) / (rhoD3); ... %MassFraction3
Y4_2; ... .%MassFraction4
(rho_ * v * Y4_2 - rhoD4_p * Y4_2 - omega * Coef_Stoic(4) * MM(4)) / (rhoD4); ... %MassFraction4
Y5_2; ... .%MassFraction5
(rho_ * v * Y5_2 - rhoD5_p * Y5_2 - omega * Coef_Stoic(5) * MM(5)) / (rhoD5); ... %MassFraction5
];
end
% -----------------------------------------------------------------------
function res = mat4bc(ya, yb, lambda) % boundary conditions
va = ya(1);
U1a = ya(2);
TO0a = ya(4);
Y1_1a = ya(6);
Y2_1a = ya(8);
Y3_1a = ya(10);
Y4_1a = ya(12);
Y5_1a = ya(14);
vb = yb(1);
U1b = yb(2);
TO0b = yb(4);
Y1_1b = yb(6);
Y2_1b = yb(8);
Y3_1b = yb(10);
Y4_1b = yb(12);
Y5_1b = yb(14);
res = [va - v0; ... % v(0) = v0
vb - vl; ... % v(L) = vl
U1a - 0; ... % U(0) = 0
U1b - 0; ... % U(L) = 0
TO0a - TF0; ... % T(0) = TF0
TO0b - TO0; ... %T(L) = TO0
Y1_1a - YLeft(1); ... %
Y1_1b - YRight(1); ... %
Y2_1a - YLeft(2); ... %
Y2_1b - YRight(2); ... %
Y3_1a - YLeft(3); ... %
Y3_1b - YRight(3); ... %
Y4_1a - YLeft(4); ... %
Y4_1b - YRight(4); ... %
Y5_1a - YLeft(5); ... %
Y5_1b - YRight(5); ... %
];
end
%-----------------------------------------------------------------------
function yinit = mat4init(x) % initial guess function.
yinit = [0.0; ... %v
0.0; ... %U1
0.0; ... %U2
300; ... % TO0
0.0; ... % T2
1.0; ... % Y1_1
0.0; ... % Y1_2
0.0; ... % Y2_1
0.0; ... % Y2_2
0.0; ... % Y3_1
0.0; ... % Y3_2
0.0; ... % Y4_1
0.0; ... % Y4_2
0.0; ... % Y5_1
0.0; ... % Y5_2
];
end
%% Definition of helper functions for density and transport parameters
function MW = getAverageMolecularWeight(Yk)
mult = 0;
for c = 1:5
mult = mult + Yk(c) / MM(c);
end
MW = 1.0 / mult;
end
function density = rho(T, Yk)
MW = getAverageMolecularWeight(Yk);
density = p0 * MW / (R * T); % kg / m^3
end
function dRho_dy = drhody(T, dTdy, Yk, dYkdy)
dRho_dy = -p0 * dTdy / (R * T^2 * (Yk(1) / MM(1) + Yk(2) / MM(2) + Yk(3) / MM(3) + Yk(4) / MM(4) + Yk(5) / MM(5))) - ...
p0 * (dYkdy(1) / MM(1) + dYkdy(2) / MM(2) + dYkdy(3) / MM(3) + dYkdy(4) / MM(4) + dYkdy(5) / MM(5)) ...
/ (R * T * (Yk(1) / MM(1) + Yk(2) / MM(2) + Yk(3) / MM(3) + Yk(4) / MM(4) + Yk(5) / MM(5))^2);
end
%% PowerLaw
% function viscosity = mu(T)
% viscosity = viscosity0 * (T / Tref)^(a);
%
% end
% function dViscosity_dy = dmu_dy(T, dTdy)
% dViscosity_dy = (viscosity0 / Tref^a) * a * (T)^(a - 1) * dTdy;
% end
function viscosity = mu(T)
S = 110.4;
viscosity = viscosity0 * (T / Tref)^(3 / 2) * (Tref + S) / (T + S);
end
function dViscosity_dy = dmu_dy(T, dTdy)
mu0 = viscosity0;
S = 110.4;
dViscosity_dT = 0.3e1 / 0.2e1 * mu0 * sqrt(T/Tref) * (Tref + S) / (T + S) / Tref - ...
mu0 * (T / Tref)^(0.3e1 / 0.2e1) * (Tref + S) / (T + S)^2;
dViscosity_dy = dViscosity_dT * dTdy;
end
%-------------------------------------------
function reactionRate = getReactionRate(T, Yk)
Yf = Yk(1);
Yo = Yk(2);
rho_ = rho(T, Yk);
if chemActive == true
Ta = getActivationTemperature(T, Yk);
reactionRate = B * exp(-Ta./T) .* (rho_ .* Yf ./ MM(1)) .* (rho_ .* Yo ./ MM(2));
else
reactionRate = 0.0;
end
end
function heatRelease = getHeatRelease(Yk)
if variableKineticParameters
phi = GetPhi(Yk(1), Yk(2));
if phi > 1.5
phi = 1.5;
end
alpha = 0.21;
if phi > 1
heatRelease = (1.0 - alpha * (phi - 1)) * massHeatRelease;
else
heatRelease = massHeatRelease;
end
else
heatRelease = massHeatRelease;
end
end
function activationTemperature = getActivationTemperature(T, Yk)
if variableKineticParameters
phi = GetPhi(Yk(1), Yk(2));
if (phi >= 1.07)
activationTemperature = (1 + 4.443 * (phi - 1.07)^2) * Ta0;
elseif (phi <= 1.07 && phi > 0.64)
activationTemperature = Ta0;
else
activationTemperature = (1 + 8.25 * (phi - 0.64)^2) * Ta0;
end
else
activationTemperature = Ta0;
end
end
function phi = GetPhi(YF, YO)
phi = (s * YF0 / YO0) * (s * YF - YO + YO0) / (s * (YF0 - YF) + YO);
end
end
|
github
|
FDYdarmstadt/BoSSS-master
|
getComponentCp.m
|
.m
|
BoSSS-master/src/L4-application/XNSEC2/Worksheets/Jupyter/CounterFlowFlameMatlabCode/nasapolynomials/getComponentCp.m
| 1,901 |
utf_8
|
99aa6723a33c4ba5baaf099df7ac76a4
|
function cp = getComponentCp(T, component )
R = 8.314; %KJ/KgK
[mycoef, MW]= getCoefficients(T,component);
cp_R = mycoef(1) + mycoef(2)*T + mycoef(3)*T^2+ mycoef(4)*T^3+ mycoef(5)*T^4;
cp = cp_R*R/MW;
end
function [coef, MW] = getCoefficients(T, component)
limit =1000;
switch component
case 'CH4'
coef1 = [7.48514950E-02 1.33909467E-02 -5.73285809E-06 1.22292535E-09 -1.01815230E-13 -9.46834459E+03 1.84373180E+01];
coef2 = [5.14987613E+00 -1.36709788E-02 4.91800599E-05 -4.84743026E-08 1.66693956E-11 -1.02466476E+04 -4.64130376E+00];
MW = 16;
case 'O2'
coef1 = [3.28253784E+00 1.48308754E-03 -7.57966669E-07 2.09470555E-10 -2.16717794E-14 -1.08845772E+03 5.45323129E+00];
coef2 = [3.78245636E+00 -2.99673416E-03 9.84730201E-06 -9.68129509E-09 3.24372837E-12 -1.06394356E+03 3.65767573E+00];
MW = 32;
case 'CO2'
coef1 = [3.85746029E+00 4.41437026E-03 -2.21481404E-06 5.23490188E-10 -4.72084164E-14 -4.87591660E+04 2.27163806E+00];
coef2 = [2.35677352E+00 8.98459677E-03 -7.12356269E-06 2.45919022E-09 -1.43699548E-13 -4.83719697E+04 9.90105222E+00];
MW = 44;
case 'H2O'
coef1 = [3.03399249E+00 2.17691804E-03 -1.64072518E-07 -9.70419870E-11 1.68200992E-14 -3.00042971E+04 4.96677010E+00];
coef2 = [4.19864056E+00 -2.03643410E-03 6.52040211E-06 -5.48797062E-09 1.77197817E-12 -3.02937267E+04 -8.49032208E-01];
MW = 18;
case 'N2'
coef1 = [0.02926640E+02 0.14879768E-02 -0.05684760E-05 0.10097038E-09 -0.06753351E-13 -0.09227977E+04 0.05980528E+02];
coef2 = [0.03298677E+02 0.14082404E-02 -0.03963222E-04 0.05641515E-07 -0.02444854E-10 -0.10208999E+04 0.03950372E+02];
MW = 28;
otherwise
warning('Component not defined')
end
if (T > limit)
coef = coef1;
elseif (T <= limit)
coef = coef2;
end
end
|
github
|
wenjiegroup/DeepRed-master
|
supervisedstackedAEPredict.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/supervisedstackedAEPredict.m
| 1,559 |
utf_8
|
a0c8343f0fbdfdb7056c7582c6f44050
|
function [pred,M2] = supervisedstackedAEPredict(theta, hiddenSize, numClasses, netconfig, data)
% stackedAEPredict: Takes a trained theta and a test data set,
% and returns the predicted labels for each example.
% theta: trained weights from the autoencoder
% hiddenSize: the number of hidden units *at the 2nd layer*
% numClasses: the number of categories
% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example.
% Your code should produce the prediction matrix
% pred, where pred(i) is argmax_c P(y(c) | x(i)).
%% Unroll theta parameter
% We first extract the part which compute the softmax gradient
softmaxTheta = reshape(theta(1:hiddenSize*numClasses), numClasses, hiddenSize);
% Extract out the "stack"
stack = params2stack(theta(hiddenSize*numClasses+1:end), netconfig);
%% ---------- YOUR CODE HERE --------------------------------------
% Instructions: Compute pred using theta assuming that the labels start
% from 1.
for d=1:numel(stack)
data = sigmoid( bsxfun(@plus,stack{d}.w*data,stack{d}.b) );
end
% pred = softmaxTheta * data;
% [~,pred] = max(pred);
M1 = softmaxTheta * data;
M1 = bsxfun(@minus, M1, max(M1, [], 1)); %%Preventing overflows
M2 = exp(M1);
M2 = bsxfun(@rdivide, M2, sum(M2));
[~,pred] = max(M2);
% -----------------------------------------------------------
end
% You might find this useful
function sigm = sigmoid(x)
sigm = 1 ./ (1 + exp(-x));
end
|
github
|
wenjiegroup/DeepRed-master
|
emgm.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/emgm.m
| 3,012 |
utf_8
|
3e33f09eae2378fb4c43bac397dcedbf
|
function [label, model, llh] = emgm(X, init)
% Perform EM algorithm for fitting the Gaussian mixture model.
% X: d x n data matrix
% init: k (1 x 1) or label (1 x n, 1<=label(i)<=k) or center (d x k)
% Written by Michael Chen ([email protected]).
%% initialization
fprintf('EM for Gaussian mixture: running ... \n');
R = initialization(X,init);
[~,label(1,:)] = max(R,[],2);
R = R(:,unique(label));
tol = 1e-10;
maxiter = 500;
llh = -inf(1,maxiter);
converged = false;
t = 1;
while ~converged && t < maxiter
t = t+1;
model = maximization(X,R);
[R, llh(t)] = expectation(X,model);
[~,label(:)] = max(R,[],2);
u = unique(label); % non-empty components
if size(R,2) ~= size(u,2)
R = R(:,u); % remove empty components
else
converged = llh(t)-llh(t-1) < tol*abs(llh(t));
end
end
llh = llh(2:t);
if converged
fprintf('Converged in %d steps.\n',t-1);
else
fprintf('Not converged in %d steps.\n',maxiter);
end
function R = initialization(X, init)
[d,n] = size(X);
if isstruct(init) % initialize with a model
R = expectation(X,init);
elseif length(init) == 1 % random initialization
k = init;
idx = randsample(n,k);
m = X(:,idx);
[~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);
[u,~,label] = unique(label);
while k ~= length(u)
idx = randsample(n,k);
m = X(:,idx);
[~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);
[u,~,label] = unique(label);
end
R = full(sparse(1:n,label,1,n,k,n));
elseif size(init,1) == 1 && size(init,2) == n % initialize with labels
label = init;
k = max(label);
R = full(sparse(1:n,label,1,n,k,n));
elseif size(init,1) == d %initialize with only centers
k = size(init,2);
m = init;
[~,label] = max(bsxfun(@minus,m'*X,dot(m,m,1)'/2),[],1);
R = full(sparse(1:n,label,1,n,k,n));
else
error('ERROR: init is not valid.');
end
function [R, llh] = expectation(X, model)
mu = model.mu;
Sigma = model.Sigma;
w = model.weight;
n = size(X,2);
k = size(mu,2);
logRho = zeros(n,k);
for i = 1:k
logRho(:,i) = loggausspdf(X,mu(:,i),Sigma(:,:,i));
end
logRho = bsxfun(@plus,logRho,log(w));
T = logsumexp(logRho,2);
llh = sum(T)/n; % loglikelihood
logR = bsxfun(@minus,logRho,T);
R = exp(logR);
function model = maximization(X, R)
[d,n] = size(X);
k = size(R,2);
nk = sum(R,1);
w = nk/n;
mu = bsxfun(@times, X*R, 1./nk);
Sigma = zeros(d,d,k);
sqrtR = sqrt(R);
for i = 1:k
Xo = bsxfun(@minus,X,mu(:,i));
Xo = bsxfun(@times,Xo,sqrtR(:,i)');
Sigma(:,:,i) = Xo*Xo'/nk(i);
Sigma(:,:,i) = Sigma(:,:,i)+eye(d)*(1e-6); % add a prior for numerical stability
end
model.mu = mu;
model.Sigma = Sigma;
model.weight = w;
function y = loggausspdf(X, mu, Sigma)
d = size(X,1);
X = bsxfun(@minus,X,mu);
[U,p]= chol(Sigma);
if p ~= 0
error('ERROR: Sigma is not PD.');
end
Q = U'\X;
q = dot(Q,Q,1); % quadratic term (M distance)
c = d*log(2*pi)+2*sum(log(diag(U))); % normalization constant
y = -(c+q)/2;
|
github
|
wenjiegroup/DeepRed-master
|
supervisedstackedAECost.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/supervisedstackedAECost.m
| 3,980 |
utf_8
|
f18b7bda7d257c34ba8570deeb696070
|
function [ cost, grad ] = supervisedstackedAECost(theta, hiddenSize, ...
numClasses, netconfig, ...
lambda, data, labels)
% stackedAECost: Takes a trained softmaxTheta and a training data set with labels,
% and returns cost and gradient using a dbn model. Used for
% finetuning.
% theta: trained weights from the softmax and dbn
% hiddenSize: the number of hidden units *at the 2nd layer*
% numClasses: the number of categories
% netconfig: the network configuration of the stack
% lambda: the weight regularization penalty
% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example.
% labels: A vector containing labels, where labels(i) is the label for the
% i-th training example
%% Unroll softmaxTheta parameter
% We first extract the part which compute the softmax gradient
softmaxTheta = reshape(theta(1:hiddenSize*numClasses), numClasses, hiddenSize);
% Extract out the dbn
stack = params2stack(theta(hiddenSize*numClasses+1:end), netconfig);
% You will need to compute the following gradients
softmaxThetaGrad = zeros(size(softmaxTheta));
stackgrad = cell(size(stack));
for d = 1:numel(stack)
stackgrad{d}.w = zeros(size(stack{d}.w));
stackgrad{d}.b = zeros(size(stack{d}.b));
end
cost = 0; % You need to compute this
% You might find these variables useful
m = size(data, 2);
groundTruth = full(sparse(labels, 1:m, 1,numClasses,m));
%% --------------------------- YOUR CODE HERE -----------------------------
% Instructions: Compute the cost function and gradient vector for
% the stacked autoencoder.
%
% You are given a stack variable which is a cell-array of
% the weights and biases for every layer. In particular, you
% can refer to the weights of Layer d, using stack{d}.w and
% the biases using stack{d}.b . To get the total number of
% layers, you can use numel(stack).
%
% The last layer of the network is connected to the softmax
% classification layer, softmaxTheta.
%
% You should compute the gradients for the softmaxTheta,
% storing that in softmaxThetaGrad. Similarly, you should
% compute the gradients for each layer in the stack, storing
% the gradients in stackgrad{d}.w and stackgrad{d}.b
% Note that the size of the matrices in stackgrad should
% match exactly that of the size of the matrices in stack.
%
depth = numel(stack);
z = cell(depth+1,1);
a = cell(depth+1, 1);
a{1} = data;
for layer = (1:depth)
z{layer+1} = stack{layer}.w * a{layer} + repmat(stack{layer}.b, [1, size(a{layer},2)]);
a{layer+1} = sigmoid(z{layer+1});
end
M = softmaxTheta * a{depth+1};
M = bsxfun(@minus, M, max(M));
p = bsxfun(@rdivide, exp(M), sum(exp(M)));
cost = -1/m * groundTruth(:)' * log(p(:)) + lambda/2 * sum(softmaxTheta(:) .^ 2);%When adding the weight decay term to the cost, you should regularize only the softmax weights (do not regularize the weights that compute the hidden layer activations).
softmaxThetaGrad = -1/m * (groundTruth - p) * a{depth+1}' + lambda * softmaxTheta;
d = cell(depth+1);
d{depth+1} = -(softmaxTheta' * (groundTruth - p)) .* a{depth+1} .* (1-a{depth+1});
for layer = (depth:-1:2)
d{layer} = (stack{layer}.w' * d{layer+1}) .* a{layer} .* (1-a{layer});
end
for layer = (depth:-1:1)
stackgrad{layer}.w = (1/m) * d{layer+1} * a{layer}';
stackgrad{layer}.b = (1/m) * sum(d{layer+1}, 2);
end
% -------------------------------------------------------------------------
%% Roll gradient vector
grad = [softmaxThetaGrad(:) ; stack2params(stackgrad)];
end
% You might find this useful
function sigm = sigmoid(x)
sigm = 1 ./ (1 + exp(-x));
end
|
github
|
wenjiegroup/DeepRed-master
|
unsupervisedstackedAEPredict.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/unsupervisedstackedAEPredict.m
| 1,455 |
utf_8
|
e6e4f928fd00f181d643913558de16f0
|
function [data] = unsupervisedstackedAEPredict(theta, netconfig, data)
% stackedAEPredict: Takes a trained theta and a test data set,
% and returns the predicted labels for each example.
% theta: trained weights from the autoencoder
% hiddenSize: the number of hidden units *at the 2nd layer*
% numClasses: the number of categories
% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example.
% Your code should produce the prediction matrix
% pred, where pred(i) is argmax_c P(y(c) | x(i)).
%% Unroll theta parameter
% Extract out the "stack"
stack = params2stack(theta, netconfig);
%% ---------- YOUR CODE HERE --------------------------------------
% Instructions: Compute pred using theta assuming that the labels start
% from 1.
depth = numel(stack);
if rem(depth,2) ~= 0
error('the depth is not correct!');
end
for d=1:depth/2
data = sigmoid( bsxfun(@plus,stack{d}.w*data,stack{d}.b) );
end
% pred = softmaxTheta * data;
% [~,pred] = max(pred);
%
% M1 = softmaxTheta * data;
% M1 = bsxfun(@minus, M1, max(M1, [], 1)); %%Preventing overflows
% M2 = exp(M1);
% M2 = bsxfun(@rdivide, M2, sum(M2));
% [~,pred] = max(M2);
% -----------------------------------------------------------
end
% You might find this useful
function sigm = sigmoid(x)
sigm = 1 ./ (1 + exp(-x));
end
|
github
|
wenjiegroup/DeepRed-master
|
WolfeLineSearch.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/minFunc/WolfeLineSearch.m
| 11,106 |
utf_8
|
f97d9ca0bf8aab87df9aa65e74f98589
|
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...
x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)
%
% Bracketing Line Search to Satisfy Wolfe Conditions
%
% Inputs:
% x: starting location
% t: initial step size
% d: descent direction
% f: function value at starting location
% g: gradient at starting location
% gtd: directional derivative at starting location
% c1: sufficient decrease parameter
% c2: curvature parameter
% debug: display debugging information
% LS: type of interpolation
% maxLS: maximum number of iterations
% tolX: minimum allowable step length
% doPlot: do a graphical display of interpolation
% funObj: objective function
% varargin: parameters of objective function
%
% Outputs:
% t: step length
% f_new: function value at x+t*d
% g_new: gradient value at x+t*d
% funEvals: number function evaluations performed by line search
% H: Hessian at initial guess (only computed if requested
% Evaluate the Objective and Gradient at the Initial Step
if nargout == 5
[f_new,g_new,H] = feval(funObj, x + t*d, varargin{:});
else
[f_new,g_new] = feval(funObj, x + t*d, varargin{:});
end
funEvals = 1;
gtd_new = g_new'*d;
% Bracket an Interval containing a point satisfying the
% Wolfe criteria
LSiter = 0;
t_prev = 0;
f_prev = f;
g_prev = g;
gtd_prev = gtd;
done = 0;
while LSiter < maxLS
%% Bracketing Phase
if ~isLegal(f_new) || ~isLegal(g_new)
if 0
if debug
fprintf('Extrapolated into illegal region, Bisecting\n');
end
t = (t + t_prev)/2;
if ~saveHessianComp && nargout == 5
[f_new,g_new,H] = feval(funObj, x + t*d, varargin{:});
else
[f_new,g_new] = feval(funObj, x + t*d, varargin{:});
end
funEvals = funEvals + 1;
gtd_new = g_new'*d;
LSiter = LSiter+1;
continue;
else
if debug
fprintf('Extrapolated into illegal region, switching to Armijo line-search\n');
end
t = (t + t_prev)/2;
% Do Armijo
if nargout == 5
[t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...
x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...
funObj,varargin{:});
else
[t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...
x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...
funObj,varargin{:});
end
funEvals = funEvals + armijoFunEvals;
return;
end
end
if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)
bracket = [t_prev t];
bracketFval = [f_prev f_new];
bracketGval = [g_prev g_new];
break;
elseif abs(gtd_new) <= -c2*gtd
bracket = t;
bracketFval = f_new;
bracketGval = g_new;
done = 1;
break;
elseif gtd_new >= 0
bracket = [t_prev t];
bracketFval = [f_prev f_new];
bracketGval = [g_prev g_new];
break;
end
temp = t_prev;
t_prev = t;
minStep = t + 0.01*(t-temp);
maxStep = t*10;
if LS == 3
if debug
fprintf('Extending Braket\n');
end
t = maxStep;
elseif LS ==4
if debug
fprintf('Cubic Extrapolation\n');
end
t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);
else
t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);
end
f_prev = f_new;
g_prev = g_new;
gtd_prev = gtd_new;
if ~saveHessianComp && nargout == 5
[f_new,g_new,H] = feval(funObj, x + t*d, varargin{:});
else
[f_new,g_new] = feval(funObj, x + t*d, varargin{:});
end
funEvals = funEvals + 1;
gtd_new = g_new'*d;
LSiter = LSiter+1;
end
if LSiter == maxLS
bracket = [0 t];
bracketFval = [f f_new];
bracketGval = [g g_new];
end
%% Zoom Phase
% We now either have a point satisfying the criteria, or a bracket
% surrounding a point satisfying the criteria
% Refine the bracket until we find a point satisfying the criteria
insufProgress = 0;
Tpos = 2;
LOposRemoved = 0;
while ~done && LSiter < maxLS
% Find High and Low Points in bracket
[f_LO LOpos] = min(bracketFval);
HIpos = -LOpos + 3;
% Compute new trial value
if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)
if debug
fprintf('Bisecting\n');
end
t = mean(bracket);
elseif LS == 4
if debug
fprintf('Grad-Cubic Interpolation\n');
end
t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d
bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);
else
% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nonTpos = -Tpos+3;
if LOposRemoved == 0
oldLOval = bracket(nonTpos);
oldLOFval = bracketFval(nonTpos);
oldLOGval = bracketGval(:,nonTpos);
end
t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);
end
% Test that we are making sufficient progress
if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1
if debug
fprintf('Interpolation close to boundary');
end
if insufProgress || t>=max(bracket) || t <= min(bracket)
if debug
fprintf(', Evaluating at 0.1 away from boundary\n');
end
if abs(t-max(bracket)) < abs(t-min(bracket))
t = max(bracket)-0.1*(max(bracket)-min(bracket));
else
t = min(bracket)+0.1*(max(bracket)-min(bracket));
end
insufProgress = 0;
else
if debug
fprintf('\n');
end
insufProgress = 1;
end
else
insufProgress = 0;
end
% Evaluate new point
if ~saveHessianComp && nargout == 5
[f_new,g_new,H] = feval(funObj, x + t*d, varargin{:});
else
[f_new,g_new] = feval(funObj, x + t*d, varargin{:});
end
funEvals = funEvals + 1;
gtd_new = g_new'*d;
LSiter = LSiter+1;
if f_new > f + c1*t*gtd || f_new >= f_LO
% Armijo condition not satisfied or not lower than lowest
% point
bracket(HIpos) = t;
bracketFval(HIpos) = f_new;
bracketGval(:,HIpos) = g_new;
Tpos = HIpos;
else
if abs(gtd_new) <= - c2*gtd
% Wolfe conditions satisfied
done = 1;
elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0
% Old HI becomes new LO
bracket(HIpos) = bracket(LOpos);
bracketFval(HIpos) = bracketFval(LOpos);
bracketGval(:,HIpos) = bracketGval(:,LOpos);
if LS == 5
if debug
fprintf('LO Pos is being removed!\n');
end
LOposRemoved = 1;
oldLOval = bracket(LOpos);
oldLOFval = bracketFval(LOpos);
oldLOGval = bracketGval(:,LOpos);
end
end
% New point becomes new LO
bracket(LOpos) = t;
bracketFval(LOpos) = f_new;
bracketGval(:,LOpos) = g_new;
Tpos = LOpos;
end
if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX
if debug
fprintf('Line Search can not make further progress\n');
end
break;
end
end
%%
if LSiter == maxLS
if debug
fprintf('Line Search Exceeded Maximum Line Search Iterations\n');
end
end
[f_LO LOpos] = min(bracketFval);
t = bracket(LOpos);
f_new = bracketFval(LOpos);
g_new = bracketGval(:,LOpos);
% Evaluate Hessian at new point
if nargout == 5 && funEvals > 1 && saveHessianComp
[f_new,g_new,H] = feval(funObj, x + t*d, varargin{:});
funEvals = funEvals + 1;
end
end
%%
function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);
alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);
alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);
if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)
if debug
fprintf('Cubic Extrapolation\n');
end
t = alpha_c;
else
if debug
fprintf('Secant Extrapolation\n');
end
t = alpha_s;
end
end
%%
function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);
% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nonTpos = -Tpos+3;
gtdT = bracketGval(:,Tpos)'*d;
gtdNonT = bracketGval(:,nonTpos)'*d;
oldLOgtd = oldLOGval'*d;
if bracketFval(Tpos) > oldLOFval
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);
if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)
if debug
fprintf('Cubic Interpolation\n');
end
t = alpha_c;
else
if debug
fprintf('Mixed Quad/Cubic Interpolation\n');
end
t = (alpha_q + alpha_c)/2;
end
elseif gtdT'*oldLOgtd < 0
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) sqrt(-1) gtdT],doPlot);
if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))
if debug
fprintf('Cubic Interpolation\n');
end
t = alpha_c;
else
if debug
fprintf('Quad Interpolation\n');
end
t = alpha_s;
end
elseif abs(gtdT) <= abs(oldLOgtd)
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],...
doPlot,min(bracket),max(bracket));
alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],...
doPlot,min(bracket),max(bracket));
if alpha_c > min(bracket) && alpha_c < max(bracket)
if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))
if debug
fprintf('Bounded Cubic Extrapolation\n');
end
t = alpha_c;
else
if debug
fprintf('Bounded Secant Extrapolation\n');
end
t = alpha_s;
end
else
if debug
fprintf('Bounded Secant Extrapolation\n');
end
t = alpha_s;
end
if bracket(Tpos) > oldLOval
t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);
else
t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);
end
else
t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
end
end
|
github
|
wenjiegroup/DeepRed-master
|
minFunc_processInputOptions.m
|
.m
|
DeepRed-master/Matlab_code_of_DeepRed/minFunc/minFunc_processInputOptions.m
| 3,551 |
utf_8
|
ea7fbcf303b9cafeca4045921adad934
|
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...
corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...
HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...
DerivativeCheck,Damped,HvFunc,bbType,cycle,...
HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...
minFunc_processInputOptions(o)
% Constants
SD = 0;
CSD = 1;
BB = 2;
CG = 3;
PCG = 4;
LBFGS = 5;
QNEWTON = 6;
NEWTON0 = 7;
NEWTON = 8;
TENSOR = 9;
verbose = 1;
verboseI= 1;
debug = 0;
doPlot = 0;
method = LBFGS;
cgSolve = 0;
o = toUpper(o);
if isfield(o,'DISPLAY')
switch(upper(o.DISPLAY))
case 0
verbose = 0;
verboseI = 0;
case 'FINAL'
verboseI = 0;
case 'OFF'
verbose = 0;
verboseI = 0;
case 'NONE'
verbose = 0;
verboseI = 0;
case 'FULL'
debug = 1;
case 'EXCESSIVE'
debug = 1;
doPlot = 1;
end
end
LS_init = 0;
c2 = 0.9;
LS = 4;
Fref = 1;
Damped = 0;
HessianIter = 1;
if isfield(o,'METHOD')
m = upper(o.METHOD);
switch(m)
case 'TENSOR'
method = TENSOR;
case 'NEWTON'
method = NEWTON;
case 'MNEWTON'
method = NEWTON;
HessianIter = 5;
case 'PNEWTON0'
method = NEWTON0;
cgSolve = 1;
case 'NEWTON0'
method = NEWTON0;
case 'QNEWTON'
method = QNEWTON;
Damped = 1;
case 'LBFGS'
method = LBFGS;
case 'BB'
method = BB;
LS = 2;
Fref = 20;
case 'PCG'
method = PCG;
c2 = 0.2;
LS_init = 2;
case 'SCG'
method = CG;
c2 = 0.2;
LS_init = 4;
case 'CG'
method = CG;
c2 = 0.2;
LS_init = 2;
case 'CSD'
method = CSD;
c2 = 0.2;
Fref = 10;
LS_init = 2;
case 'SD'
method = SD;
LS_init = 2;
end
end
maxFunEvals = getOpt(o,'MAXFUNEVALS',1000);
maxIter = getOpt(o,'MAXITER',500);
tolFun = getOpt(o,'TOLFUN',1e-5);
tolX = getOpt(o,'TOLX',1e-9);
corrections = getOpt(o,'CORR',100);
c1 = getOpt(o,'C1',1e-4);
c2 = getOpt(o,'C2',c2);
LS_init = getOpt(o,'LS_INIT',LS_init);
LS = getOpt(o,'LS',LS);
cgSolve = getOpt(o,'CGSOLVE',cgSolve);
qnUpdate = getOpt(o,'QNUPDATE',3);
cgUpdate = getOpt(o,'CGUPDATE',2);
initialHessType = getOpt(o,'INITIALHESSTYPE',1);
HessianModify = getOpt(o,'HESSIANMODIFY',0);
Fref = getOpt(o,'FREF',Fref);
useComplex = getOpt(o,'USECOMPLEX',0);
numDiff = getOpt(o,'NUMDIFF',0);
LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);
DerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);
Damped = getOpt(o,'DAMPED',Damped);
HvFunc = getOpt(o,'HVFUNC',[]);
bbType = getOpt(o,'BBTYPE',0);
cycle = getOpt(o,'CYCLE',3);
HessianIter = getOpt(o,'HESSIANITER',HessianIter);
outputFcn = getOpt(o,'OUTPUTFCN',[]);
useMex = getOpt(o,'USEMEX',1);
useNegCurv = getOpt(o,'USENEGCURV',1);
precFunc = getOpt(o,'PRECFUNC',[]);
end
function [v] = getOpt(options,opt,default)
if isfield(options,opt)
if ~isempty(getfield(options,opt))
v = getfield(options,opt);
else
v = default;
end
else
v = default;
end
end
function [o] = toUpper(o)
if ~isempty(o)
fn = fieldnames(o);
for i = 1:length(fn)
o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
end
end
end
|
github
|
wandgibaut/GA_ELM-master
|
gen_k_folds.m
|
.m
|
GA_ELM-master/ELM/gen_k_folds.m
| 1,071 |
utf_8
|
fc334b7e3f8168ba8404252080669a36
|
% 31/05/2017 - FEEC/Unicamp
% gen_k_folds.m
% Generation of k folds from a single dataset containing X and S
%
function [] = gen_k_folds(filename,k)
load(filename);
N = length(X(:,1));
n_elem = floor(N/k);
excess = mod(N,k);
order = randperm(N);
ind = 1;
excess1 = excess;
for i=1:k,
for j=1:n_elem,
Xfold(j,:,i) = X(order(ind),:);
Sfold(j,:,i) = S(order(ind),:);
ind = ind+1;
end
if excess1 > 0,
Xfold(n_elem+1,:,i) = X(order(ind),:);
Sfold(n_elem+1,:,i) = S(order(ind),:);
ind = ind+1;
excess1 = excess1-1;
end
end
excess1 = excess;
if ~isempty(findstr(filename,'.mat')),
filename = strrep(filename,'.mat','');
end
for i=1:k,
if excess1 > 0,
X = Xfold(1:(n_elem+1),:,i);
S = Sfold(1:(n_elem+1),:,i);
save(strcat(filename,sprintf('%d',i)),'X','S');
excess1 = excess1-1;
else
X = Xfold(1:(n_elem),:,i);
S = Sfold(1:(n_elem),:,i);
save(strcat(filename,sprintf('%d',i)),'X','S');
end
end
|
github
|
wandgibaut/GA_ELM-master
|
process.m
|
.m
|
GA_ELM-master/ELM/process.m
| 1,146 |
utf_8
|
94a2a8c33c73d2acce628696527058af
|
% 05/05/2012
% function [Ew,dEw,Ewv,eqm,eqmv] = process(X,S,Xv,Sv,w1,w2,n,m,N,Nv)
% Output: Ew: Squared error for the training dataset
% dEw: Gradient vector for the training dataset
% Ewv: Squared error for the validation dataset
% Presentation of input-output patterns: batch mode
% All neurons have bias
%
function [Ew,dEw,Ewv,eqm,eqmv] = process(X,S,Xv,Sv,w1,w2)
[N,n_in] = size(X);
n_hid = length(w1(:,1));
n_out = length(S(1,:));
Nv = length(Xv(:,1));
x1 = [X ones(N,1)];
y1 = tanh(x1*w1');
x2 = [y1 ones(N,1)];
% y2 = tanh(x2*w2');
y2 = x2*w2';
erro = y2-S;
% erro2 = erro.*(1.0-y2.*y2);
erro2 = erro;
dw2 = erro2'*x2;
erro1 = (erro2*w2(:,1:n_hid)).*(1.0-y1.*y1);
dw1 = erro1'*x1;
verro = reshape(erro,N*n_out,1);
Ew = 0.5*(verro'*verro);
eqm = sqrt((1/(N*n_out))*(verro'*verro));
dEw = [reshape(dw1',n_hid*(n_in+1),1);reshape(dw2',n_out*(n_hid+1),1)];
x1v = [Xv ones(Nv,1)];
y1v = tanh(x1v*w1');
x2v = [y1v ones(Nv,1)];
% y2v = tanh(x2v*w2');
y2v = x2v*w2';
errov = y2v-Sv;
verrov = reshape(errov,Nv*n_out,1);
Ewv = 0.5*(verrov'*verrov);
eqmv = sqrt((1/(Nv*n_out))*(verrov'*verrov));
|
github
|
wandgibaut/GA_ELM-master
|
qmean.m
|
.m
|
GA_ELM-master/ELM/qmean.m
| 242 |
utf_8
|
920ee8f9f07c5fe3cd8f614cac3bb688
|
% 05/05/2012
% qmean.m
% Gives the root mean square (quadratic mean) for the elements of
% one vector or one matrix.
%
function [rms] = qmean(w)
[nr,nc] = size(w);
v = reshape(w,nr*nc,1);
n_v = length(v);
rms = sqrt(sum(v.*v)/n_v);
|
github
|
wandgibaut/GA_ELM-master
|
hprocess.m
|
.m
|
GA_ELM-master/ELM/hprocess.m
| 821 |
utf_8
|
a11949516b4e20b4345e561ca5963896
|
%
% function [s] = hprocess(X,S,w1,w2,p1,p2)
% s = product H*p (computed exactly)
%
function [s] = hprocess(X,S,w1,w2,p1,p2)
[N,n_in] = size(X);
n_hid = length(w1(:,1));
n_out = length(S(1,:));
x1 = [X ones(N,1)];
rx1 = zeros(N,n_in+1);
y1 = tanh(x1*w1');
ry1 = (x1*p1'+rx1*w1').*(1.0-y1.*y1);
x2 = [y1 ones(N,1)];
rx2 = [ry1 zeros(N,1)];
% y2 = tanh(x2*w2');
y2 = x2*w2';
% ry2 = (x2*p2'+rx2*w2').*(1.0-y2.*y2);
ry2 = x2*p2'+rx2*w2';
erro = y2-S;
% erro2 = erro.*(1.0-y2.*y2);
erro2 = erro;
rerro2 = ry2;
rw2 = erro2'*rx2+rerro2'*x2;
erro1 = (erro2*w2(:,1:n_hid)).*(1.0-y1.*y1);
rerro1 = (rerro2*w2(:,1:n_hid)+erro2*p2(:,1:n_hid)).*(1.0-y1.*y1)+(erro2*w2(:,1:n_hid)).*(-2*y1.*ry1);
rw1 = erro1'*rx1+rerro1'*x1;
rEw = [reshape(rw1',n_hid*(n_in+1),1);reshape(rw2',n_out*(n_hid+1),1)];
s = rEw;
|
github
|
wandgibaut/GA_ELM-master
|
qmean2.m
|
.m
|
GA_ELM-master/ELM/qmean2.m
| 331 |
utf_8
|
f8482b9fd3969940424c13fa914c787a
|
% 05/05/2012
% qmean2.m
% Gives a kind of root mean square (quadratic mean) for the elements of
% two matrices, taken together.
%
function [rms] = qmean2(w1,w2)
[nr1,nc1] = size(w1);
v1 = reshape(w1,nr1*nc1,1);
[nr2,nc2] = size(w2);
v2 = reshape(w2,nr2*nc2,1);
v = [v1;v2];
n_v = length(v);
rms = sqrt(sum(v.*v)/n_v);
|
github
|
wandgibaut/GA_ELM-master
|
process_options.m
|
.m
|
GA_ELM-master/ELM/process_options.m
| 4,394 |
utf_8
|
483b50d27e3bdb68fd2903a0cab9df44
|
% PROCESS_OPTIONS - Processes options passed to a Matlab function.
% This function provides a simple means of
% parsing attribute-value options. Each option is
% named by a unique string and is given a default
% value.
%
% Usage: [var1, var2, ..., varn[, unused]] = ...
% process_options(args, ...
% str1, def1, str2, def2, ..., strn, defn)
%
% Arguments:
% args - a cell array of input arguments, such
% as that provided by VARARGIN. Its contents
% should alternate between strings and
% values.
% str1, ..., strn - Strings that are associated with a
% particular variable
% def1, ..., defn - Default values returned if no option
% is supplied
%
% Returns:
% var1, ..., varn - values to be assigned to variables
% unused - an optional cell array of those
% string-value pairs that were unused;
% if this is not supplied, then a
% warning will be issued for each
% option in args that lacked a match.
%
% Examples:
%
% Suppose we wish to define a Matlab function 'func' that has
% required parameters x and y, and optional arguments 'u' and 'v'.
% With the definition
%
% function y = func(x, y, varargin)
%
% [u, v] = process_options(varargin, 'u', 0, 'v', 1);
%
% calling func(0, 1, 'v', 2) will assign 0 to x, 1 to y, 0 to u, and 2
% to v. The parameter names are insensitive to case; calling
% func(0, 1, 'V', 2) has the same effect. The function call
%
% func(0, 1, 'u', 5, 'z', 2);
%
% will result in u having the value 5 and v having value 1, but
% will issue a warning that the 'z' option has not been used. On
% the other hand, if func is defined as
%
% function y = func(x, y, varargin)
%
% [u, v, unused_args] = process_options(varargin, 'u', 0, 'v', 1);
%
% then the call func(0, 1, 'u', 5, 'z', 2) will yield no warning,
% and unused_args will have the value {'z', 2}. This behaviour is
% useful for functions with options that invoke other functions
% with options; all options can be passed to the outer function and
% its unprocessed arguments can be passed to the inner function.
% Copyright (C) 2002 Mark A. Paskin
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [varargout] = process_options(args, varargin)
% Check the number of input arguments
n = length(varargin);
if (mod(n, 2))
error('Each option must be a string/value pair.');
end
% Check the number of supplied output arguments
if (nargout < (n / 2))
error('Insufficient number of output arguments given');
elseif (nargout == (n / 2))
warn = 1;
nout = n / 2;
else
warn = 0;
nout = n / 2 + 1;
end
% Set outputs to be defaults
varargout = cell(1, nout);
for i=2:2:n
varargout{i/2} = varargin{i};
end
% Now process all arguments
nunused = 0;
for i=1:2:length(args)
found = 0;
for j=1:2:n
if strcmpi(args{i}, varargin{j})
varargout{(j + 1)/2} = args{i + 1};
found = 1;
break;
end
end
if (~found)
if (warn)
warning(sprintf('Option ''%s'' not used.', args{i}));
args{i}
else
nunused = nunused + 1;
unused{2 * nunused - 1} = args{i};
unused{2 * nunused} = args{i + 1};
end
end
end
% Assign the unused arguments
if (~warn)
if (nunused)
varargout{nout} = unused;
else
varargout{nout} = cell(0);
end
end
|
github
|
wandgibaut/GA_ELM-master
|
__ga_problem__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_problem__.m
| 4,683 |
utf_8
|
6c87b89209dd136875213e1acc4f8dd8
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 5.9
function [x fval exitflag output population scores] = __ga_problem__ (problem)
## first instruction
state.StartTime = time ();
## second instruction
output = struct ("randstate", rand ("state"),
"randnstate", randn ("state"));
## instructions not to be executed at each generation
state.Population(1:problem.options.PopulationSize, 1:problem.nvars) = \
__ga_initial_population__ (problem.nvars,
problem.fitnessfcn,
problem.options);
state.Generation = 0;
private_state = __ga_problem_private_state__ (problem.options);
state.Selection = __ga_problem_state_selection__ (private_state,
problem.options);
## instructions to be executed at each generation
state = __ga_problem_update_state_at_each_generation__ (state, problem,
private_state);
NextPopulation = zeros (problem.options.PopulationSize, problem.nvars);
while (! __ga_stop__ (problem, state)) ## fix a generation
%wanderMods
%pop_at_generation_g(state.Generation,:,:) = state.Population;
pop = state.Population;
save(strcat('pop_at_generation_',sprintf('%d',state.Generation),'.mat'),'pop');
bestScores(state.Generation +1) = min(state.Score);
meanScores(state.Generation +1) = mean(state.Score);
save('bestScore_evol.mat','bestScores');
save('meanScore_evol.mat','meanScores');
%endMods
## elite
if (private_state.ReproductionCount.elite > 0)
[trash IndexSortedScores] = sort (state.Score);
NextPopulation(state.Selection.elite, 1:problem.nvars) = \
state.Population \
(IndexSortedScores(1:private_state.ReproductionCount.elite, 1),
1:problem.nvars);
endif
## selection for crossover and mutation
parents(1, 1:private_state.nParents) = __ga_selectionfcn__ \
(state.Expectation, private_state.nParents, problem.options);
## crossover
if (private_state.ReproductionCount.crossover > 0)
NextPopulation(state.Selection.crossover, 1:problem.nvars) = \
__ga_crossoverfcn__ \
(parents(1, private_state.parentsSelection.crossover),
problem.options, problem.nvars, problem.fitnessfcn,
false, ## unused
state.Population);
endif
## mutation
if (private_state.ReproductionCount.mutation > 0)
NextPopulation(state.Selection.mutation, 1:problem.nvars) = \
__ga_mutationfcn__ \
(parents(1, private_state.parentsSelection.mutation),
problem.options, problem.nvars, problem.fitnessfcn,
state, state.Score,
state.Population);
endif
## update state structure
state.Population(1:problem.options.PopulationSize,
1:problem.nvars) = NextPopulation;
state.Generation++;
state = __ga_problem_update_state_at_each_generation__ (state, problem,
private_state);
endwhile
[x fval exitflag output population scores] = \
__ga_problem_return_variables__ (state, problem);
endfunction
#state structure fields
#DONE state.Population
#DONE state.Score
#DONE state.Generation
#DONE state.StartTime
#state.StopFlag
#DONE state.Selection
#DONE state.Expectation
#DONE state.Best
#state.LastImprovement
#state.LastImprovementTime
#state.NonlinIneq
#state.NonlinEq
|
github
|
wandgibaut/GA_ELM-master
|
gacreationuniform.m
|
.m
|
GA_ELM-master/Octave_GA_Package/gacreationuniform.m
| 2,006 |
utf_8
|
67debabecd04ecfd9bb83db91ae8c8a8
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{Population} =} gacreationuniform (@var{GenomeLength}, @var{FitnessFcn}, @var{options})
## Create a random initial population with a uniform distribution.
##
## @strong{Inputs}
## @table @var
## @item GenomeLength
## The number of indipendent variables for the fitness function.
## @item FitnessFcn
## The fitness function.
## @item options
## The options structure.
## @end table
##
## @strong{Outputs}
## @table @var
## @item Population
## The initial population for the genetic algorithm.
## @end table
##
## @seealso{ga, gaoptimset}
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 4.9
function Population = gacreationuniform (GenomeLength, FitnessFcn, options)
[LB(1, 1:GenomeLength) UB(1, 1:GenomeLength)] = \
__ga_popinitrange__ (options.PopInitRange, GenomeLength);
## pseudocode
##
## Population = Delta * RandomPopulationBetween0And1 + Offset
Population(1:options.PopulationSize, 1:GenomeLength) = \
((ones (options.PopulationSize, 1) * (UB - LB)) .* \
rand (options.PopulationSize, GenomeLength)) + \
(ones (options.PopulationSize, 1) * LB);
endfunction
## number of input arguments
# TODO
## number of output arguments
# TODO
## type of arguments
# TODO
# TODO
|
github
|
wandgibaut/GA_ELM-master
|
__ga_problem_private_state__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_problem_private_state__.m
| 2,146 |
utf_8
|
893eb63244d15752210761db85c60b8c
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.1.1
function private_state = __ga_problem_private_state__ (options)
private_state.ReproductionCount.elite = options.EliteCount;
private_state.ReproductionCount.crossover = \
fix (options.CrossoverFraction *
(options.PopulationSize - options.EliteCount));
private_state.ReproductionCount.mutation = \
options.PopulationSize - \
(private_state.ReproductionCount.elite +
private_state.ReproductionCount.crossover);
assert (private_state.ReproductionCount.elite +
private_state.ReproductionCount.crossover +
private_state.ReproductionCount.mutation,
options.PopulationSize); ## DEBUG
private_state.parentsCount.crossover = \
2 * private_state.ReproductionCount.crossover;
private_state.parentsCount.mutation = \
1 * private_state.ReproductionCount.mutation;
private_state.nParents = \
private_state.parentsCount.crossover + \
private_state.parentsCount.mutation;
private_state.parentsSelection.crossover = \
1:private_state.parentsCount.crossover;
private_state.parentsSelection.mutation = \
private_state.parentsCount.crossover + \
(1:private_state.parentsCount.mutation);
assert (length (private_state.parentsSelection.crossover) +
length (private_state.parentsSelection.mutation),
private_state.nParents); ## DEBUG
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
selectionstochunif.m
|
.m
|
GA_ELM-master/Octave_GA_Package/selectionstochunif.m
| 1,618 |
utf_8
|
87ac6650e2429e58f96db39a403276e9
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.3
function parents = selectionstochunif (expectation, nParents, options)
nc_expectation = columns (expectation);
line(1, 1:nc_expectation) = cumsum (expectation(1, 1:nc_expectation));
max_step_size = line(1, nc_expectation);
step_size = max_step_size * rand ();
steps(1, 1:nParents) = rem (step_size * (1:nParents), max_step_size);
for index_steps = 1:nParents ## fix an entry of the steps (or parents) vector
#assert (steps(1, index_steps) < max_step_size); ## DEBUG
index_line = 1;
while (steps(1, index_steps) >= line(1, index_line))
#assert ((index_line >= 1) && (index_line < nc_expectation)); ## DEBUG
index_line++;
endwhile
parents(1, index_steps) = index_line;
endfor
endfunction
## number of input arguments
# TODO
## number of output arguments
# TODO
## type of arguments
# TODO
# TODO
|
github
|
wandgibaut/GA_ELM-master
|
fitscalingrank.m
|
.m
|
GA_ELM-master/Octave_GA_Package/fitscalingrank.m
| 1,908 |
utf_8
|
bd97cb739f2daf62e15ad4a969936b28
|
## Copyright (C) 2008, 2009 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.3.3
function expectation = fitscalingrank (scores, nParents)
nr_scores = rows (scores);
r(1, 1:nr_scores) = ranks (scores(1:nr_scores, 1));
#TODO
#ranks ([7,2,2]) == [3.0,1.5,1.5]
#is [3,1,2] (or [3,2,1]) useful?
expectation_wo_nParents(1, 1:nr_scores) = arrayfun (@(n) 1 / sqrt (n), r);
expectation(1, 1:nr_scores) = \
(nParents / sum (expectation_wo_nParents)) * \
expectation_wo_nParents;
endfunction
## number of input arguments
# TODO
## number of output arguments
# TODO
## type of arguments
# TODO
# TODO
%!shared scores, nParents, expectation
%! scores = rand (20, 1);
%! nParents = 32;
%! expectation = fitscalingrank (scores, nParents);
%!assert (sum (expectation), nParents, 1e-9);
%!test
%! [trash index_min_scores] = min (scores);
%! [trash index_max_expectation] = max (expectation);
%! assert (index_min_scores, index_max_expectation);
%!test
%! [trash index_max_scores] = max (scores);
%! [trash index_min_expectation] = min (expectation);
%! assert (index_max_scores, index_min_expectation);
|
github
|
wandgibaut/GA_ELM-master
|
ga.m
|
.m
|
GA_ELM-master/Octave_GA_Package/ga.m
| 15,185 |
utf_8
|
23597e35bae5ce410cdb52ab98972bc0
|
## Copyright (C) 2008, 2010, 2012 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars})
## @deftypefnx{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars}, @var{A}, @var{b})
## @deftypefnx{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars}, @var{A}, @var{b}, @var{Aeq}, @var{beq})
## @deftypefnx{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars}, @var{A}, @var{b}, @var{Aeq}, @var{beq}, @var{LB}, @var{UB})
## @deftypefnx{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars}, @var{A}, @var{b}, @var{Aeq}, @var{beq}, @var{LB}, @var{UB}, @var{nonlcon})
## @deftypefnx{Function File} {@var{x} =} ga (@var{fitnessfcn}, @var{nvars}, @var{A}, @var{b}, @var{Aeq}, @var{beq}, @var{LB}, @var{UB}, @var{nonlcon}, @var{options})
## @deftypefnx{Function File} {@var{x} =} ga (@var{problem})
## @deftypefnx{Function File} {[@var{x}, @var{fval}] =} ga (@dots{})
## @deftypefnx{Function File} {[@var{x}, @var{fval}, @var{exitflag}] =} ga (@dots{})
## @deftypefnx{Function File} {[@var{x}, @var{fval}, @var{exitflag}, @var{output}] =} ga (@dots{})
## @deftypefnx{Function File} {[@var{x}, @var{fval}, @var{exitflag}, @var{output}, @var{population}] =} ga (@dots{})
## @deftypefnx{Function File} {[@var{x}, @var{fval}, @var{exitflag}, @var{output}, @var{population}, @var{scores}] =} ga (@dots{})
## Find minimum of function using genetic algorithm.
##
## @strong{Inputs}
## @table @var
## @item fitnessfcn
## The objective function to minimize. It accepts a vector @var{x} of
## size 1-by-@var{nvars}, and returns a scalar evaluated at @var{x}.
## @item nvars
## The dimension (number of design variables) of @var{fitnessfcn}.
## @item options
## The structure of the optimization parameters; can be created using
## the @code{gaoptimset} function. If not specified, @code{ga} minimizes
## with the default optimization parameters.
## @item problem
## A structure containing the following fields:
## @itemize @bullet
## @item @code{fitnessfcn}
## @item @code{nvars}
## @item @code{Aineq}
## @item @code{Bineq}
## @item @code{Aeq}
## @item @code{Beq}
## @item @code{lb}
## @item @code{ub}
## @item @code{nonlcon}
## @item @code{randstate}
## @item @code{randnstate}
## @item @code{solver}
## @item @code{options}
## @end itemize
## @end table
##
## @strong{Outputs}
## @table @var
## @item x
## The local unconstrained found minimum to the objective function,
## @var{fitnessfcn}.
## @item fval
## The value of the fitness function at @var{x}.
## @end table
##
## @seealso{gaoptimset}
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 6.0.1
function [x fval exitflag output population scores] = \
ga (fitnessfcn_or_problem,
nvars,
A = [], b = [],
Aeq = [], beq = [],
LB = [], UB = [],
nonlcon = [],
options = gaoptimset ())
if ((nargout > 6) ||
(nargin < 1) ||
(nargin == 3) ||
(nargin == 5) ||
(nargin == 7) ||
(nargin > 10))
print_usage ();
else
## retrieve the problem structure
if (nargin == 1)
problem = fitnessfcn_or_problem;
else
problem.fitnessfcn = fitnessfcn_or_problem;
problem.nvars = nvars;
problem.Aineq = A;
problem.Bineq = b;
problem.Aeq = Aeq;
problem.Beq = beq;
problem.lb = LB;
problem.ub = UB;
problem.nonlcon = nonlcon;
problem.randstate = rand ("state");
problem.randnstate = randn ("state");
problem.solver = "ga";
problem.options = options;
endif
## call the function that manages the problem structure
[x fval exitflag output population scores] = __ga_problem__ (problem);
endif
endfunction
## number of input arguments
%!shared f, nvars
%! f = @rastriginsfcn;
%! nvars = 2;
%!error x = ga ()
%!error x = ga (f)
%!error x = ga (f, nvars, [])
%!error x = ga (f, nvars, [], [], [])
%!error x = ga (f, nvars, [], [], [], [], [])
%!error x = ga (f, nvars, [], [], [], [], [], [], @(x) [[], []], gaoptimset (), [])
## number of output arguments
# TODO
## type of arguments
%!function f = ff (nvars)
%! f = @(x) sum (x(:, 1:nvars) .** 2, 2);
%!error x = ga (ff (3), 2);
# TODO
# TODO: test that each field in the user-specified "problem" structure is checked
## flawless execution with right arguments
%!shared f, nvars
%! f = @rastriginsfcn;
%! nvars = 2;
%!function [C, Ceq] = nonlcon (x)
%! C = [];
%! Ceq = [];
%!test x = ga (f, nvars);
%!test x = ga (f, nvars, [], []);
%!test x = ga (f, nvars, ones (3, nvars), ones (3, 1));
%!test x = ga (f, nvars, [], [], [], []);
%!test x = ga (f, nvars, [], [], ones (4, nvars), ones (4, 1));
%!test x = ga (f, nvars, [], [], [], [], [], []);
%!test x = ga (f, nvars, [], [], [], [], - Inf (1, nvars), Inf (1, nvars));
%!test x = ga (f, nvars, [], [], [], [], - ones (1, nvars), ones (1, nvars));
%!test x = ga (f, nvars, [], [], [], [], [], [], @(x) [[], []]);
%!test x = ga (f, nvars, [], [], [], [], [], [], @nonlcon);
%!test x = ga (f, nvars, [], [], [], [], [], [], @(x) [[], []], gaoptimset ());
%!test # TODO: convert to error after implementing private ga-specific createOptimProblem. All fields in the user-specified structure should be checked
%! problem = struct ("fitnessfcn", @rastriginsfcn,
%! "nvars", 2,
%! "options", gaoptimset ());
%! x = ga (problem);
## flawless execution with any nvars
%!function f = ff (nvars)
%! f = @(x) sum (x(:, 1:nvars) .** 2, 2);
%!test
%! nvars = 1;
%! x = ga (ff (nvars), nvars);
%!test
%! nvars = 2;
%! x = ga (ff (nvars), nvars);
%!test
%! nvars = 3;
%! x = ga (ff (nvars), nvars);
## flawless execution with any supported optimization parameter
## different from the default value
%!shared f, nvars, default_options
%! f = @rastriginsfcn;
%! nvars = 2;
%! default_options = gaoptimset ();
%!function [C, Ceq] = nonlcon (x)
%! C = [];
%! Ceq = [];
%!test
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, default_options);
%!test # TODO: use non-default value
%! options = gaoptimset ("CreationFcn", @gacreationuniform);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # TODO: use non-default value
%! options = gaoptimset ("CrossoverFcn", @crossoverscattered);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! options = gaoptimset ("CrossoverFraction", rand);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! ps = getfield (default_options, "PopulationSize");
%! options = gaoptimset ("EliteCount", randi ([0, ps]));
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! options = gaoptimset ("FitnessLimit", 1e-7);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # TODO: use non-default value
%! options = gaoptimset ("FitnessScalingFcn", @fitscalingrank);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! g = getfield (default_options, "Generations");
%! options = gaoptimset ("Generations", g + 1);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! ps = getfield (default_options, "PopulationSize");
%! ## Initial population can be partial
%! options_w_full_ip = \
%! gaoptimset ("InitialPopulation", rand (ps, nvars));
%! partial_ip = randi ([0, ps - 1]);
%! options_w_partial_ip = \
%! gaoptimset ("InitialPopulation", rand (partial_ip, nvars));
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options_w_full_ip);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options_w_partial_ip);
%!test
%! ps = getfield (default_options, "PopulationSize");
%! ## Initial scores needs initial population
%!
%! options_w_full_ip_full_is = \
%! gaoptimset ("InitialPopulation", rand (ps, nvars),
%! "InitialScores", rand (ps, 1 ));
%! partial_ip = randi ([2, ps - 1]);
%! options_w_partial_ip_full_is = \
%! gaoptimset ("InitialPopulation", rand (partial_ip, nvars),
%! "InitialScores", rand (partial_ip, 1 ));
%!
%! ## Initial scores can be partial
%! partial_is_when_full_ip = randi ([1, ps - 1]);
%! partial_is_when_partial_ip = randi ([1, partial_ip - 1]);
%! options_w_full_ip_partial_is = \
%! gaoptimset ("InitialPopulation", rand (ps, nvars),
%! "InitialScores", rand (partial_is_when_full_ip, 1 ));
%! options_w_partial_ip_partial_is = \
%! gaoptimset ("InitialPopulation", rand (partial_ip, nvars),
%! "InitialScores", rand (partial_is_when_partial_ip, 1 ));
%!
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon,
%! options_w_full_ip_full_is);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon,
%! options_w_partial_ip_full_is);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon,
%! options_w_full_ip_partial_is);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon,
%! options_w_partial_ip_partial_is);
%!test # TODO: use non-default value
%! options = gaoptimset ("MutationFcn", {@mutationgaussian, 1, 1});
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! options = gaoptimset ("PopInitRange", [-2; 2]);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! options = gaoptimset ("PopulationSize", 200);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # TODO: use non-default value
%! options = gaoptimset ("SelectionFcn", @selectionstochunif);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # TODO: use non-default value
%! options = gaoptimset ("TimeLimit", Inf);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!error # TODO: this should become test
%! options = gaoptimset ("UseParallel", "always");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test
%! options = gaoptimset ("Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
## error with conflicting optimization parameters: population size et al.
%!shared f, nvars
%! f = @rastriginsfcn;
%! nvars = 2;
%!function [C, Ceq] = nonlcon (x)
%! C = [];
%! Ceq = [];
%!error # Elite count cannot be greater than the population size
%! ps = 3;
%! bad_options = gaoptimset ("PopulationSize", ps,
%! "EliteCount", ps + 1);
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error # The number of individuals in the initial population cannot be greater of the population size
%! ps = 3;
%! bad_options = gaoptimset ("PopulationSize", ps,
%! "InitialPopulation", zeros (ps + 1, nvars));
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error # Initial scores cannot be specified without specifying the initial population too
%! bad_options = gaoptimset ("InitialScores", zeros (3, 1));
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error # The number of initial scores specified cannot be greater of the number of individuals in the initial population
%! ip = 3;
%! bad_options = gaoptimset ("InitialPopulation", zeros (ip, nvars),
%! "InitialScores", zeros (ip + 1, 1));
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
## error with vectorized evaluation of objective function. Vectorized
## objective functions are better because can be evaluated both as
## serial and vectorized.
%!shared nvars
%! nvars = 2;
%!function [C, Ceq] = nonlcon (x)
%! C = [];
%! Ceq = [];
%!function f = ff (nvars)
%! f = @(x) sum (x(:, 1:nvars) .** 2, 2);
%!function f_not_vectorized = ff_not_vectorized (nvars)
%! f_not_vectorized = @(x) sum (x(1:nvars) .** 2);
%!test # A non-vectorized objective function works when no vectorization is required
%! f = ff_not_vectorized (nvars);
%! options = gaoptimset ("Vectorized", "off");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!error # A non-vectorized objective function does not work when vectorization is required
%! f = ff_not_vectorized (nvars);
%! options = gaoptimset ("Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # A vectorized objective function works when no vectorization is required
%! f = ff (nvars);
%! options = gaoptimset ("Vectorized", "off");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!test # A vectorized objective function works when vectorization is required
%! f = ff (nvars);
%! options = gaoptimset ("Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
## error with conflicting optimization parameters: parallel and
## vectorized evaluation of objective function
%!shared f, nvars
%! f = @rastriginsfcn;
%! nvars = 2;
%!function [C, Ceq] = nonlcon (x)
%! C = [];
%! Ceq = [];
%!test
%! options = gaoptimset ("UseParallel", "never",
%! "Vectorized", "off");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!error # TODO: this should become test
%! options = gaoptimset ("UseParallel", "always",
%! "Vectorized", "off");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!error
%! bad_options = gaoptimset ("UseParallel", "garbage",
%! "Vectorized", "off");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!test
%! options = gaoptimset ("UseParallel", "never",
%! "Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, options);
%!warning
%! bad_options = gaoptimset ("UseParallel", "always",
%! "Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!warning
%! bad_options = gaoptimset ("UseParallel", "garbage",
%! "Vectorized", "on");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error
%! bad_options = gaoptimset ("UseParallel", "never",
%! "Vectorized", "garbage");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error
%! bad_options = gaoptimset ("UseParallel", "always",
%! "Vectorized", "garbage");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
%!error
%! bad_options = gaoptimset ("UseParallel", "garbage",
%! "Vectorized", "garbage");
%! x = ga (f, nvars, [], [], [], [], [], [], @nonlcon, bad_options);
|
github
|
wandgibaut/GA_ELM-master
|
gaoptimset.m
|
.m
|
GA_ELM-master/Octave_GA_Package/gaoptimset.m
| 4,063 |
utf_8
|
46b7597649d783633f30acd9ce5f5b0d
|
## Copyright (C) 2008, 2009, 2010 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{options} =} gaoptimset
## @deftypefnx{Function File} {@var{options} =} gaoptimset ('@var{param1}', @var{value1}, '@var{param2}', @var{value2}, @dots{})
## Create genetic algorithm options structure.
##
## @strong{Inputs}
## @table @var
## @item param
## Parameter to set. Unspecified parameters are set to their default
## values; specifying no parameters is allowed.
## @item value
## Value of @var{param}.
## @end table
##
## @strong{Outputs}
## @table @var
## @item options
## Structure containing the options, or parameters, for the genetic algorithm.
## @end table
##
## @strong{Options}
## @table @code
## @item CreationFcn
## @item CrossoverFcn
## @item CrossoverFraction
## @item EliteCount
## @item FitnessLimit
## @item FitnessScalingFcn
## @item Generations
## @item InitialPopulation
## Can be partial.
## @item InitialScores
## column vector | [] (default) . Can be partial.
## @item MutationFcn
## @item PopInitRange
## @item PopulationSize
## @item SelectionFcn
## @item TimeLimit
## @item UseParallel
## "always" | "never" (default) . Parallel evaluation of objective function. TODO: parallel evaluation of nonlinear constraints
## @item Vectorized
## "on" | "off" (default) . Vectorized evaluation of objective function. TODO: vectorized evaluation of nonlinear constraints
## @end table
##
## @seealso{ga}
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 4.4.7
function options = gaoptimset (varargin)
if ((nargout != 1) ||
(mod (length (varargin), 2) == 1))
print_usage ();
else
## initialize the return variable to a structure with all parameters
## set to their default value
options = __gaoptimset_default_options__ ();
## set custom options
for i = 1:2:length (varargin)
param = varargin{i};
value = varargin{i + 1};
if (! isfield (options, param))
error ("wrong parameter");
else
options = setfield (options, param, value);
endif
endfor
endif
endfunction
## number of input arguments
%!error options = gaoptimset ("odd number of arguments")
%!error options = gaoptimset ("Generations", 123, "odd number of arguments")
## number of output arguments
%!error gaoptimset ("Generations", 123)
%!error [a, b] = gaoptimset ("Generations", 123)
## type of arguments
# TODO
%!#error options = gaoptimset ("Vectorized", "bad value") # TODO: fix
%!#error options = gaoptimset ("UseParallel", "bad value") # TODO: fix
# TODO: structure/add tests below
%!assert (getfield (gaoptimset ("Generations", 123), "Generations"), 123)
%!test
%! options = gaoptimset ("EliteCount", 1,
%! "FitnessLimit", 1e-7,
%! "Generations", 1000,
%! "PopInitRange", [-5; 5],
%! "PopulationSize", 200);
%!
%! ## "CrossoverFraction" is not specified, so gaoptimset should put the default value: testing this too
%! assert ([(getfield (options, "CrossoverFraction"));
%! (getfield (options, "EliteCount"));
%! (getfield (options, "FitnessLimit"));
%! (getfield (options, "Generations"));
%! (getfield (options, "PopInitRange"));
%! (getfield (options, "PopulationSize"))],
%! [0.8; 1; 1e-7; 1000; [-5; 5]; 200])
|
github
|
wandgibaut/GA_ELM-master
|
crossoverscattered.m
|
.m
|
GA_ELM-master/Octave_GA_Package/crossoverscattered.m
| 1,680 |
utf_8
|
698869bc98516ecc5c198b58eb033ec5
|
## Copyright (C) 2008, 2009, 2011 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 7.0
function xoverKids = crossoverscattered (parents, options, nvars, FitnessFcn,
unused,
thisPopulation)
## simplified example (nvars == 4)
## p1 = [varA varB varC varD]
## p2 = [var1 var2 var3 var4]
## b = [1 1 0 1]
## child = [varA varB var3 varD]
nc_parents = columns (parents);
n_children = nc_parents / 2;
p1(1:n_children, 1:nvars) = \
thisPopulation(parents(1, 1:n_children), 1:nvars);
p2(1:n_children, 1:nvars) = \
thisPopulation(parents(1, n_children + (1:n_children)), 1:nvars);
b(1:n_children, 1:nvars) = randi (1, n_children, nvars); ## TODO: test randi
xoverKids(1:n_children, 1:nvars) = \
b .* p1 + (ones (n_children, nvars) - b) .* p2;
endfunction
## number of input arguments
# TODO
## number of output arguments
# TODO
## type of arguments
# TODO
# TODO
|
github
|
wandgibaut/GA_ELM-master
|
__ga_selectionfcn__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_selectionfcn__.m
| 952 |
utf_8
|
026c5478931e97701612fe06e3a49d46
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.2
function parents = __ga_selectionfcn__ (expectation, nParents, options)
parents(1, 1:nParents) = \
options.SelectionFcn (expectation(1, :), nParents, options);
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_problem_state_selection__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_problem_state_selection__.m
| 1,392 |
utf_8
|
0aef374341c65d3b13b8576932f64e2e
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.1.1
function Selection = __ga_problem_state_selection__ (private_state, options)
Selection.elite = 1:private_state.ReproductionCount.elite;
Selection.crossover = \
private_state.ReproductionCount.elite + \
(1:private_state.ReproductionCount.crossover);
Selection.mutation = \
private_state.ReproductionCount.elite + \
private_state.ReproductionCount.crossover + \
(1:private_state.ReproductionCount.mutation);
#assert (length (Selection.elite) +
# length (Selection.crossover) +
# length (Selection.mutation),
# options.PopulationSize); ##DEBUG
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
rastriginsfcn.m
|
.m
|
GA_ELM-master/Octave_GA_Package/rastriginsfcn.m
| 1,699 |
utf_8
|
725e76ddbfb107653df2227561cf0364
|
## Copyright (C) 2008, 2009, 2010, 2012 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{y} =} rastriginsfcn (@var{x})
## Rastrigin's function.
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 2.0
function retval = rastriginsfcn (x)
if ((nargout != 1) ||
(nargin != 1) || (columns (x) != 2))
print_usage ();
else
x1 = x(:, 1);
x2 = x(:, 2);
retval = 20 + (x1 .** 2) + (x2 .** 2) - 10 .* (cos (2 .* pi .* x1) +
cos (2 .* pi .* x2));
endif
endfunction
## number of input arguments
%!error y = rastriginsfcn ()
%!error y = rastriginsfcn ([0, 0], "other argument")
## number of output arguments
%!error [y1, y2] = rastriginsfcn ([0, 0])
## type of arguments
%!error y = rastriginsfcn ([0; 0])
%!error y = rastriginsfcn (zeros (2, 3)) # TODO: document size of x
%!assert (rastriginsfcn ([0, 0]), 0)
%!assert (rastriginsfcn ([0, 0; 0, 0]), [0; 0])
%!assert (rastriginsfcn (zeros (3, 2)), [0; 0; 0])
|
github
|
wandgibaut/GA_ELM-master
|
__ga_scores__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_scores__.m
| 2,052 |
utf_8
|
6d15bb39ebed458bfa7614898207a0c5
|
## Copyright (C) 2008, 2010 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 5.7
function Scores = __ga_scores__ (problem, Population)
[nrP ncP] = size (Population);
switch problem.options.Vectorized
case "on" ## using vectorized evaluation
switch problem.options.UseParallel
case "always"
warning ("'Vectorized' option is 'on': ignoring 'UseParallel' option, even if it is 'always'");
case "never"
## Nothing.
otherwise
warning ("'Vectorized' option is 'on': ignoring invalid 'UseParallel' option value (it should be 'always' or 'never')");
endswitch
Scores = (problem.fitnessfcn (Population))(1:nrP, 1);
case "off" ## not using vectorized evaluation
switch problem.options.UseParallel
case "always" ## using parallel evaluation
error ("TODO: implement parallel evaluation of objective function");
case "never" ## using serial evaluation (i.e. loop)
tmp = zeros (nrP, 1);
for index = 1:nrP
tmp(index, 1) = problem.fitnessfcn (Population(index, 1:ncP));
endfor
Scores = tmp(1:nrP, 1);
otherwise
error ("'UseParallel' option must be 'always' or 'never'");
endswitch
otherwise
error ("'Vectorized' option must be 'on' or 'off'");
endswitch
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_initial_population__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_initial_population__.m
| 3,743 |
utf_8
|
579d807d29e60e12ff66b41cb6b4a6eb
|
## Copyright (C) 2008, 2010 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{Population} =} __ga_initial_population__ (@var{GenomeLength}, @var{FitnessFcn}, @var{options})
## Create an initial population.
##
## @seealso{__ga_problem__}
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 3.3
#TODO consider PopulationSize as a
#vector for multiple subpopolations
function Population = \
__ga_initial_population__ (GenomeLength, FitnessFcn, options)
if (isempty (options.InitialPopulation))
Population(1:options.PopulationSize, 1:GenomeLength) = \
options.CreationFcn (GenomeLength, FitnessFcn, options);
else
if (columns (options.InitialPopulation) != GenomeLength) ## columns (InitialPopulation) > 0
error ("nonempty 'InitialPopulation' must have 'GenomeLength' columns");
else ## rows (InitialPopulation) > 0
nrIP = rows (options.InitialPopulation);
if (nrIP > options.PopulationSize)
error ("nonempty 'InitialPopulation' must have no more than \
'PopulationSize' rows");
elseif (nrIP == options.PopulationSize)
Population(1:options.PopulationSize, 1:GenomeLength) = \
options.InitialPopulation;
else # rows (InitialPopulation) < PopulationSize
## create a complete new population, and then select only needed
## individuals (creating only a partial population is difficult)
CreatedPopulation(1:options.PopulationSize, 1:GenomeLength) = \
options.CreationFcn (GenomeLength, FitnessFcn, options);
Population(1:options.PopulationSize, 1:GenomeLength) = vertcat \
(options.InitialPopulation(1:nrIP, 1:GenomeLength),
CreatedPopulation(1:(options.PopulationSize - nrIP),
1:GenomeLength));
endif
endif
endif
endfunction
%!test
%! GenomeLength = 2;
%! options = gaoptimset ();
%! Population = __ga_initial_population__ (GenomeLength, @rastriginsfcn, options);
%! assert (size (Population), [options.PopulationSize, GenomeLength]);
%!test
%! GenomeLength = 2;
%! options = gaoptimset ("InitialPopulation", [1, 2; 3, 4; 5, 6]);
%! Population = __ga_initial_population__ (GenomeLength, @rastriginsfcn, options);
%! assert (size (Population), [options.PopulationSize, GenomeLength]);
## nonempty 'InitialPopulation' must have 'GenomeLength' columns
%!error
%! GenomeLength = 2;
%! options = gaoptimset ("InitialPopulation", [1; 3; 5]);
%! __ga_initial_population__ (GenomeLength, @rastriginsfcn, options);
%!error
%! GenomeLength = 2;
%! options = gaoptimset ("InitialPopulation", [1, 1, 1; 3, 3, 3; 5, 5, 5]);
%! __ga_initial_population__ (GenomeLength, @rastriginsfcn, options);
## nonempty 'InitialPopulation' must have no more than 'PopulationSize' rows
%!error
%! GenomeLength = 2;
%! options = gaoptimset ("InitialPopulation", [1, 2; 3, 4; 5, 6], "PopulationSize", 2);
%! __ga_initial_population__ (GenomeLength, @rastriginsfcn, options);
|
github
|
wandgibaut/GA_ELM-master
|
__gaoptimset_default_options__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__gaoptimset_default_options__.m
| 2,759 |
utf_8
|
7402f2ba9c19e10c5f76e27a241bae8b
|
## Copyright (C) 2008, 2009, 2010 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.2.3
function default_options = __gaoptimset_default_options__ ()
default_options.CreationFcn = @gacreationuniform;
default_options.CrossoverFcn = @crossoverscattered;
default_options.CrossoverFraction = 0.8;
#default_options.Display = "final";
#default_options.DistanceMeasureFcn gamultiobj
default_options.EliteCount = 2;
default_options.FitnessLimit = -Inf;
default_options.FitnessScalingFcn = @fitscalingrank;
default_options.Generations = 100;
#default_options.HybridFcn = [];
#default_options.InitialPenalty = 10;
default_options.InitialPopulation = [];
default_options.InitialScores = [];
#default_options.MigrationDirection = "forward";
#default_options.MigrationFraction = 0.2;
#default_options.MigrationInterval = 20;
default_options.MutationFcn = {@mutationgaussian, 1, 1};
#default_options.OutputFcns = [];
#default_options.ParetoFraction = 0.35;
#default_options.PenaltyFactor = 100;
#default_options.PlotFcns = [];
#default_options.PlotInterval = 1;
default_options.PopInitRange = [0; 1];
default_options.PopulationSize = 20;
#default_options.PopulationType = "doubleVector";
default_options.SelectionFcn = @selectionstochunif;
#default_options.StallGenLimit = 50;
#default_options.StallTimeLimit = Inf;
default_options.TimeLimit = Inf;
#default_options.TolCon = 1e-6;
#default_options.TolFun = 1e-6;
default_options.UseParallel = "never";
default_options.Vectorized = "off";
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_crossoverfcn__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_crossoverfcn__.m
| 1,307 |
utf_8
|
f1d436df0343bf3a94cdcb9f12b75e43
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.3.3
function xoverKids = __ga_crossoverfcn__ (parents, options, nvars, FitnessFcn,
unused,
thisPopulation)
## preconditions
nc_parents = columns (parents);
if (rem (nc_parents, 2) != 0)
error ("'parents' must have an even number of columns");
endif
xoverKids(1:(nc_parents / 2), 1:nvars) = options.CrossoverFcn \
(parents(1, 1:nc_parents), options, nvars, FitnessFcn,
unused,
thisPopulation(:, 1:nvars));
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
mutationgaussian.m
|
.m
|
GA_ELM-master/Octave_GA_Package/mutationgaussian.m
| 2,017 |
utf_8
|
a6b09d87d973e9079bc72dc013297750
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.7.1
function mutationChildren = \
mutationgaussian (parents, options, nvars, FitnessFcn,
state, thisScore,
thisPopulation)
[LB(1, 1:nvars) UB(1, 1:nvars)] = \
__ga_popinitrange__ (options.PopInitRange, nvars);
## start mutationgaussian logic
Scale = options.MutationFcn{1, 2};
#assert (size (Scale), [1 1]); ## DEBUG
Shrink = options.MutationFcn{1, 3};
#assert (size (Shrink), [1 1]); ## DEBUG
## initial standard deviation (i.e. when state.Generation == 0)
tmp_std = Scale * (UB - LB); ## vector = scalar * vector
## recursively compute current standard deviation
for k = 1:state.Generation
tmp_std(1, 1:nvars) = (1 - Shrink * (k / options.Generations)) * tmp_std;
endfor
current_std(1, 1:nvars) = tmp_std;
nc_parents = columns (parents);
expanded_current_std(1:nc_parents, 1:nvars) = \
ones (nc_parents, 1) * current_std;
## finally add random numbers
mutationChildren(1:nc_parents, 1:nvars) = \
thisPopulation(parents(1, 1:nc_parents), 1:nvars) + \
expanded_current_std .* randn (nc_parents, nvars);
endfunction
## number of input arguments
# TODO
## number of output arguments
# TODO
## type of arguments
# TODO
# TODO
|
github
|
wandgibaut/GA_ELM-master
|
__ga_popinitrange__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_popinitrange__.m
| 1,121 |
utf_8
|
f98dae69d0cd512e69ac3eb6377c54e1
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 2.1
function [LB UB] = __ga_popinitrange__ (PopInitRange, nvars)
switch (columns (PopInitRange))
case 1
tmpPIR(1:2, 1:nvars) = PopInitRange(1:2, 1) * ones (1, nvars);
case nvars
tmpPIR(1:2, 1:nvars) = PopInitRange(1:2, 1:nvars);
endswitch
LB(1, 1:nvars) = tmpPIR(1, 1:nvars);
UB(1, 1:nvars) = tmpPIR(2, 1:nvars);
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_problem_update_state_at_each_generation__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_problem_update_state_at_each_generation__.m
| 2,203 |
utf_8
|
586dff9dd0d38a2fc88633cd01617b11
|
## Copyright (C) 2008, 2010 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.3.1
function state = \
__ga_problem_update_state_at_each_generation__ (state, problem,
private_state)
if ((state.Generation > 0) || isempty (problem.options.InitialScores))
state.Score(1:problem.options.PopulationSize, 1) = \
__ga_scores__ (problem, state.Population);
else ## (Generation == 0) && (! isempty (InitialScores))
nrIS = rows (problem.options.InitialScores);
#assert (rows (problem.options.InitialPopulation) <= problem.options.PopulationSize); ## DEBUG
if (nrIS <= rows (problem.options.InitialPopulation))
missing_rows = (nrIS+1):problem.options.PopulationSize;
state.Score(1:problem.options.PopulationSize, 1) = \
[problem.options.InitialScores(:, 1);
(__ga_scores__ (problem, state.Population(missing_rows, :)))
];
else
error ("rows (InitialScores) > rows (InitialPopulation)");
endif
endif
state.Expectation(1, 1:problem.options.PopulationSize) = \
problem.options.FitnessScalingFcn (state.Score, private_state.nParents);
state.Best(state.Generation + 1, 1) = min (state.Score);
endfunction
%!error
%! state.Generation = 0;
%! problem = struct ("fitnessfcn", @rastriginsfcn, "nvars", 2, "options", gaoptimset ("Generations", 10, "InitialScores", [0; 0; 0]));
%! unused = 0;
%! __ga_problem_update_state_at_each_generation__ (state, problem, unused);
|
github
|
wandgibaut/GA_ELM-master
|
__ga_stop__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_stop__.m
| 1,368 |
utf_8
|
b34fdecdf33b5422089dc5db4c75e620
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn{Function File} {@var{stop} =} __ga_stop__ (@var{problem}, @var{state})
## Determine whether the genetic algorithm should stop.
##
## @seealso{__ga_problem__}
## @end deftypefn
## Author: Luca Favatella <[email protected]>
## Version: 5.1
function stop = __ga_stop__ (problem, state)
Generations = \
(state.Generation >= problem.options.Generations);
TimeLimit = \
((time () - state.StartTime) >= problem.options.TimeLimit);
FitnessLimit = \
(state.Best(state.Generation + 1, 1) <= problem.options.FitnessLimit);
stop = (Generations ||
TimeLimit ||
FitnessLimit);
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_mutationfcn__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_mutationfcn__.m
| 1,207 |
utf_8
|
a433a51276b4b8b7cb444715e2e92239
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.3
function mutationChildren = \
__ga_mutationfcn__ (parents, options, nvars, FitnessFcn,
state, thisScore,
thisPopulation)
mutationChildren(1:(columns (parents)), 1:nvars) = \
options.MutationFcn{1, 1} (parents(1, :), options, nvars, FitnessFcn,
state, thisScore,
thisPopulation(:, 1:nvars));
endfunction
|
github
|
wandgibaut/GA_ELM-master
|
__ga_problem_return_variables__.m
|
.m
|
GA_ELM-master/Octave_GA_Package/__ga_problem_return_variables__.m
| 1,442 |
utf_8
|
0c5e1d8e6f778ab2420548ca30b40a46
|
## Copyright (C) 2008 Luca Favatella <[email protected]>
##
## 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, see <http://www.gnu.org/licenses/>.
## Author: Luca Favatella <[email protected]>
## Version: 1.1
function [x fval exitflag output population scores] = \
__ga_problem_return_variables__ (state, problem)
[trash IndexMinScore] = min (state.Score);
x = state.Population(IndexMinScore, 1:problem.nvars);
fval = problem.fitnessfcn (x);
#TODO exitflag
## output.randstate and output.randnstate must be assigned at the
## start of the algorithm
output.generations = state.Generation;
#TODO output.funccount
#TODO output.message
#TODO output.maxconstraint
population = state.Population;
scores = state.Score;
endfunction
|
github
|
mdaddysman/Thorlabs-CMOS-USB-cameras-in-Matlab-master
|
ThorVideo.m
|
.m
|
Thorlabs-CMOS-USB-cameras-in-Matlab-master/ThorVideo.m
| 4,539 |
utf_8
|
01dc204a517fc072f92090a252806475
|
function ThorVideo()
[hCam, width, height] = LoadCamera();
maxgain = GetMaxGain(hCam);
gain = GetGain(hCam);
expset = GetExposureInfo(hCam);
gboost = SetGainBoost(hCam,-1);
cm = 1;
if exist('ThorCamSaveSettings.mat', 'file') == 2
settings = load('ThorCamSaveSettings.mat');
gain = settings.sgain;
result = SetGain(hCam,gain);
expset(1) = settings.sexp;
result = SetExposure(hCam,expset(1));
gboost = settings.sgainb;
SetGainBoost(hCam,gboost);
cm = settings.scm;
end
image = GetImage(hCam,width,height);
image = flipud(rot90(reshape(image,1280,1024)));
fh = figure('Name','ThorCam Image','NumberTitle','off');
ih = imshow(image,'InitialMagnification',67);
ThorCam_ColorMapLookup(cm);
colorbar
th = title(['FPS: ' num2str(0) ' Ms/frame: ' num2str(0)]);
set(fh,'Resize','off','Position',[329 166 1022 773],'MenuBar','none','ToolBar','none','CloseRequestFcn',{@ThorCam_SafeShutdown,hCam});
exph = uicontrol('Style','slider','Position',[80 50 370 15]);
gainh = uicontrol('Style','slider','Position',[500 50 370 15]);
expth = uicontrol('Style','text','Position',[80 30 370 15],'String',['Exposure Time: ' num2str(expset(1)) ' ms']);
set(expth,'BackgroundColor',get(fh,'Color'));
gainth = uicontrol('Style','text','Position',[500 30 370/2 15],'String',['Gain: ' num2str(gain,'%.2f') 'X']);
set(gainth,'BackgroundColor',get(fh,'Color'));
gainbh = uicontrol('Style','checkbox','Position',[500+370/2+370/4 30 370/4 15],'String','Gain Boost');
set(gainbh,'BackgroundColor',get(fh,'Color'),'Value',gboost,'Callback',{@ThorCam_SetGainBoostCallback,hCam});
minexpstep = expset(4)/(expset(3) - expset(2));
maxexpstep = 10*minexpstep;
set(exph,'Callback',{@ThorCam_ExpCallback,expth,expset(4),hCam},'Min',expset(2),'Max',expset(3),'Value',expset(1),'SliderStep',[minexpstep maxexpstep]);
mingainstep = 0.1/(maxgain-1);
maxgainstep = 1/(maxgain-1);
set(gainh,'Callback',{@ThorCam_GainCallback,gainth,hCam},'Min',1,'Max',maxgain,'Value',gain,'SliderStep',[mingainstep maxgainstep]);
cmh = uicontrol('Style','popupmenu','Position',[82 726 75 15],'String',{'Jet','Gray','Hot','Cool','Spring','Summer','Autumn','Winter'},'Value',cm,'Callback',{@ThorCam_ChangeColorMap,fh});
uicontrol('Style','pushbutton','String','Save Image','Position',[772 720 100 30],'Callback',{@ThorCam_SaveImageCallback,ih});
uicontrol('Style','pushbutton','String','Save Settings','Position',[425 5 100 30],'Callback',{@ThorCam_SaveSettingsCallback,exph,gainh,gainbh,cmh});
while(ishghandle(fh))
tic
image = GetImage(hCam,width,height);
image = flipud(rot90(reshape(image,1280,1024)));
set(ih,'CData',image);
drawnow
ctime = toc;
if(ishghandle(fh))
set(th,'String',['FPS: ' num2str(1/ctime,'%.2f') ' Ms/frame: ' num2str(ctime*1000,'%.0f')]);
end
end
close all
clearvars;
end
function ThorCam_ExpCallback(src,~,expth,inc,hCam)
exptime = get(src,'Value');
factor = floor(exptime/inc);
exptime = factor*inc;
set(src,'Value',exptime);
set(expth,'String',['Exposure Time: ' num2str(exptime) ' ms']);
result = SetExposure(hCam,exptime);
end
function ThorCam_GainCallback(src,~,gainth,hCam)
gain = get(src,'Value');
gain = floor(gain*100)/100;
set(src,'Value',gain);
set(gainth,'String',['Gain: ' num2str(gain,'%.2f') 'X']);
result = SetGain(hCam,gain);
end
function ThorCam_SetGainBoostCallback(src,~,hCam)
check = get(src,'Value');
SetGainBoost(hCam,check);
end
function ThorCam_SafeShutdown(src,~,hCam)
CloseCamera(hCam);
delete(src);
end
function ThorCam_SaveImageCallback(~,~,ih)
image = get(ih,'CData');
imwrite(image,[datestr(now,'yymmdd_HHMMSS') '_ThorCamImage.bmp']);
end
function ThorCam_SaveSettingsCallback(~,~,exph,gainh,gainbh,cmh)
sexp = get(exph,'Value');
sgain = get(gainh,'Value');
sgainb = get(gainbh,'Value');
scm = get(cmh,'Value');
save('ThorCamSaveSettings.mat','sexp','sgain','sgainb','scm');
end
function ThorCam_ChangeColorMap(src,~,fh)
%{'Jet','Gray','Hot','Cool','Spring','Summer','Autumn','Winter'}
cm = get(src,'Value');
figure(fh);
ThorCam_ColorMapLookup(cm);
end
function ThorCam_ColorMapLookup(cm)
switch cm
case 1
colormap jet
case 2
colormap gray
case 3
colormap hot
case 4
colormap cool
case 5
colormap spring
case 6
colormap summer
case 7
colormap autumn
case 8
colormap winter
otherwise
colormap jet
end
end
|
github
|
mdaddysman/Thorlabs-CMOS-USB-cameras-in-Matlab-master
|
ThorVideo_Functions.m
|
.m
|
Thorlabs-CMOS-USB-cameras-in-Matlab-master/ThorVideo_Functions.m
| 4,891 |
utf_8
|
412e322011293194dda9b72043652539
|
function ThorVideo_Functions()
rh = ThorCam_Open();
while(ishghandle(rh.fh))
ThorCam_RunLoop(rh);
end
close all
clearvars;
end
function ThorCam_RunLoop(runhandles)
tic
image = GetImage(runhandles.hCam,runhandles.width,runhandles.height);
image = flipud(rot90(reshape(image,runhandles.width,runhandles.height)));
set(runhandles.ih,'CData',image);
drawnow
ctime = toc;
if(ishghandle(runhandles.fh))
set(runhandles.th,'String',['FPS: ' num2str(1/ctime,'%.2f') ' Ms/frame: ' num2str(ctime*1000,'%.0f')]);
end
end
function runhandles = ThorCam_Open()
[hCam, width, height] = LoadCamera();
maxgain = GetMaxGain(hCam);
gain = GetGain(hCam);
expset = GetExposureInfo(hCam);
gboost = SetGainBoost(hCam,-1);
cm = 1;
if exist('ThorCamSaveSettings.mat', 'file') == 2
settings = load('ThorCamSaveSettings.mat');
gain = settings.sgain;
result = SetGain(hCam,gain);
expset(1) = settings.sexp;
result = SetExposure(hCam,expset(1));
gboost = settings.sgainb;
SetGainBoost(hCam,gboost);
cm = settings.scm;
end
image = GetImage(hCam,width,height);
image = flipud(rot90(reshape(image,width,height)));
fh = figure('Name','ThorCam Image','NumberTitle','off');
ih = imshow(image,'InitialMagnification',67);
ThorCam_ColorMapLookup(cm);
colorbar
th = title(['FPS: ' num2str(0) ' Ms/frame: ' num2str(0)]);
set(fh,'Resize','off','Position',[329 166 1022 773],'MenuBar','none','ToolBar','none','CloseRequestFcn',{@ThorCam_SafeShutdown,hCam});
exph = uicontrol('Style','slider','Position',[80 50 370 15]);
gainh = uicontrol('Style','slider','Position',[500 50 370 15]);
expth = uicontrol('Style','text','Position',[80 30 370 15],'String',['Exposure Time: ' num2str(expset(1)) ' ms']);
set(expth,'BackgroundColor',get(fh,'Color'));
gainth = uicontrol('Style','text','Position',[500 30 370/2 15],'String',['Gain: ' num2str(gain,'%.2f') 'X']);
set(gainth,'BackgroundColor',get(fh,'Color'));
gainbh = uicontrol('Style','checkbox','Position',[500+370/2+370/4 30 370/4 15],'String','Gain Boost');
set(gainbh,'BackgroundColor',get(fh,'Color'),'Value',gboost,'Callback',{@ThorCam_SetGainBoostCallback,hCam});
minexpstep = expset(4)/(expset(3) - expset(2));
maxexpstep = 10*minexpstep;
set(exph,'Callback',{@ThorCam_ExpCallback,expth,expset(4),hCam},'Min',expset(2),'Max',expset(3),'Value',expset(1),'SliderStep',[minexpstep maxexpstep]);
mingainstep = 0.1/(maxgain-1);
maxgainstep = 1/(maxgain-1);
set(gainh,'Callback',{@ThorCam_GainCallback,gainth,hCam},'Min',1,'Max',maxgain,'Value',gain,'SliderStep',[mingainstep maxgainstep]);
cmh = uicontrol('Style','popupmenu','Position',[82 726 75 15],'String',{'Jet','Gray','Hot','Cool','Spring','Summer','Autumn','Winter'},'Value',cm,'Callback',{@ThorCam_ChangeColorMap,fh});
uicontrol('Style','pushbutton','String','Save Image','Position',[772 720 100 30],'Callback',{@ThorCam_SaveImageCallback,ih});
uicontrol('Style','pushbutton','String','Save Settings','Position',[425 5 100 30],'Callback',{@ThorCam_SaveSettingsCallback,exph,gainh,gainbh,cmh});
runhandles.fh = fh;
runhandles.hCam = hCam;
runhandles.width = width;
runhandles.height = height;
runhandles.ih = ih;
runhandles.th = th;
end
function ThorCam_ExpCallback(src,~,expth,inc,hCam)
exptime = get(src,'Value');
factor = floor(exptime/inc);
exptime = factor*inc;
set(src,'Value',exptime);
set(expth,'String',['Exposure Time: ' num2str(exptime) ' ms']);
result = SetExposure(hCam,exptime);
end
function ThorCam_GainCallback(src,~,gainth,hCam)
gain = get(src,'Value');
gain = floor(gain*100)/100;
set(src,'Value',gain);
set(gainth,'String',['Gain: ' num2str(gain,'%.2f') 'X']);
result = SetGain(hCam,gain);
end
function ThorCam_SetGainBoostCallback(src,~,hCam)
check = get(src,'Value');
SetGainBoost(hCam,check);
end
function ThorCam_SafeShutdown(src,~,hCam)
CloseCamera(hCam);
delete(src);
end
function ThorCam_SaveImageCallback(~,~,ih)
image = get(ih,'CData');
imwrite(image,[datestr(now,'yymmdd_HHMMSS') '_ThorCamImage.bmp']);
end
function ThorCam_SaveSettingsCallback(~,~,exph,gainh,gainbh,cmh)
sexp = get(exph,'Value');
sgain = get(gainh,'Value');
sgainb = get(gainbh,'Value');
scm = get(cmh,'Value');
save('ThorCamSaveSettings.mat','sexp','sgain','sgainb','scm');
end
function ThorCam_ChangeColorMap(src,~,fh)
%{'Jet','Gray','Hot','Cool','Spring','Summer','Autumn','Winter'}
cm = get(src,'Value');
figure(fh);
ThorCam_ColorMapLookup(cm);
end
function ThorCam_ColorMapLookup(cm)
switch cm
case 1
colormap jet
case 2
colormap gray
case 3
colormap hot
case 4
colormap cool
case 5
colormap spring
case 6
colormap summer
case 7
colormap autumn
case 8
colormap winter
otherwise
colormap jet
end
end
|
github
|
rasthana522/Classification-of-Breast-Cancer-Tumors-master
|
clusterings.m
|
.m
|
Classification-of-Breast-Cancer-Tumors-master/clusterings.m
| 9,466 |
utf_8
|
7a58c73d86f75014af01d4f5cd526ab0
|
fig_num = 0;
filename = 'BreastData.xlsx';
xlrange = 'B2:AF19';
X = xlsread(filename, xlrange);
X1 = [X(:,1) X(:,17:30)];
rng(1);
%%% Creating Color Matrix for Plotting
green = [0.3 0.8 0.3];
red = [1 0 0];
C = cell(18, 3);
[C(1:9,1),C(1:9,2),C(1:9,3)] = deal({green(1)},{green(2)},{green(3)});
[C(10:18,1),C(10:18,2),C(10:18,3)] = deal({red(1)},{red(2)},{red(3)});
color_mat = cell2mat(C);
clear C;
clust_cols = [[0 0 0]; [0.15 0 1]; [0.45 0 0.7]; [0.6 0.3 0.3]; [0.3 0.6 1]; [1 0.4 0]; [0.65 0.5 0]];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% K-means Clustering %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% k = 4;
% gene_labels = string({'COX2','DBC2','MYC','CCND1','CHD1','P53','HER2'});
% length = size(gene_labels);
% for index = 1:length(2)
% gene = gene_labels(index);
% i = 2*index;
% X_gain_loss = X1(:,i:i+1);
% [idx,centroids] = kmeans(X_gain_loss,k);
% group = string(idx);
%
% fig_num = fig_num + 1;
% figure(fig_num)
% v = 1:18;
% sz = 30;
% scatter(X_gain_loss(intersect(v(group == '1'),1:9),1),X_gain_loss(intersect(v(group == '1'),1:9),2),sz,green,'o');
% hold on
% scatter(X_gain_loss(intersect(v(group == '1'),10:18),1),X_gain_loss(intersect(v(group == '1'),10:18),2),sz,'r','o');
% scatter(X_gain_loss(intersect(v(group == '2'),1:9),1),X_gain_loss(intersect(v(group == '2'),1:9),2),sz,green,'x');
% scatter(X_gain_loss(intersect(v(group == '2'),10:18),1),X_gain_loss(intersect(v(group == '2'),10:18),2),sz,'r','x');
% scatter(X_gain_loss(intersect(v(group == '3'),1:9),1),X_gain_loss(intersect(v(group == '3'),1:9),2),sz,green,'+');
% scatter(X_gain_loss(intersect(v(group == '3'),10:18),1),X_gain_loss(intersect(v(group == '3'),10:18),2),sz,'r','+');
% scatter(X_gain_loss(intersect(v(group == '4'),1:9),1),X_gain_loss(intersect(v(group == '4'),1:9),2),sz,green,'s');
% scatter(X_gain_loss(intersect(v(group == '4'),10:18),1),X_gain_loss(intersect(v(group == '4'),10:18),2),sz,'r','s');
% scatter(X_gain_loss(intersect(v(group == '5'),1:9),1),X_gain_loss(intersect(v(group == '5'),1:9),2),sz,green,'p');
% scatter(X_gain_loss(intersect(v(group == '5'),10:18),1),X_gain_loss(intersect(v(group == '5'),10:18),2),sz,'r','p');
% scatter(X_gain_loss(intersect(v(group == '6'),1:9),1),X_gain_loss(intersect(v(group == '6'),1:9),2),sz,green,'*');
% scatter(X_gain_loss(intersect(v(group == '6'),10:18),1),X_gain_loss(intersect(v(group == '6'),10:18),2),sz,'r','*');
% title(strcat(sprintf('K=%d-means Clustering on Gain/Loss ',k),{' '},gene));
% xlabel(strcat('Gain ',{' '},gene));
% ylabel(strcat('Loss ',{' '},gene));
% hold off
% % str = strcat(sprintf('k%d_means',k),{'_'},gene);
% % str = str{1};
% % saveas(gcf,str,'jpeg');
% clear str i idx centroids gene X_gain_loss group v sz
% end
% clear gene_labels index length k
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Hierarchical Clustering %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
k0 = 5;
TreeWeightedCorr = linkage(X1(:,2:15), 'weighted', 'correlation');
cutoff_wei_corr = get_maxcluster_cutoff(TreeWeightedCorr, k0);
fig_num = fig_num + 1;
figure(fig_num)
[H_wei_corr,cluster_wei_corr,perm_wei_corr] = dendrogram(TreeWeightedCorr, 'ColorThreshold', cutoff_wei_corr);
H_wei_corr = recolor_dendrogram(H_wei_corr, clust_cols);
set(H_wei_corr,'LineWidth',2)
title('Hierarchical Clustering with Correlation Distance');
xlabel('Sample Number');
ylabel('Height');
% str = sprintf('hier_weighted_corr_k%d',k0);
% saveas(gcf,str,'jpeg');
clear str k0 cutoff_wei_corr cluster_wei_corr perm_wei_corr H_wei_corr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Laplace Embedding (KNN) %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
k = 5;
m = 15;
[LapKX1,LambdaLapK] = lap_embed_knn(X1(:,2:15), k, m);
clear m
%%% 3-D Plots of Laplace Embedding (KNN)
% fig_num = fig_num + 1;
% figure(fig_num)
% [i1,i2,i3] = deal(3,4,5);
% scatter3(LapKX1(:,i1),LapKX1(:,i2),LapKX1(:,i3),15,color_mat,'fill');
% %axis([-0.1 0.1 -0.1 0.1 -0.1 0.1]);
% title(sprintf('Laplace Embedding (K=%d-NN) with %d,%d,%d',k,i1,i2,i3));
% xlabel(sprintf('Eig %d',i1));
% ylabel(sprintf('Eig %d',i2));
% zlabel(sprintf('Eig %d',i3));
% clear i1 i2 i3
%%% 2-D Plots of Laplace Embedding (KNN)
% fig_num = fig_num + 1;
% figure(fig_num)
% [j1,j2] = deal(2,4);
% scatter(LapKX1(:,j1),LapKX1(:,j2),30,color_mat,'fill');
% %axis([-0.1 0.1 -0.1 0.1 -0.1 0.1]);
% title(sprintf('Laplace Embedding (K=%d-NN) with %d,%d',k,j1,j2));
% xlabel(sprintf('Eig %d',j1));
% ylabel(sprintf('Eig %d',j2));
% % str = sprintf('lap_knn_k%d',k);
% % saveas(gcf,str,'jpeg');
% clear str j1 j2
%%% Hierarchical Clustering of Embedding (KNN)
k0 = 5;
TreeLapKWard = linkage(LapKX1(:,1:k0), 'ward', 'euclidean');
cutoff_lapK_ward = get_maxcluster_cutoff(TreeLapKWard, k0);
fig_num = fig_num + 1;
figure(fig_num)
[H_lapK_ward,cluster_lapK_ward,perm_lapK_ward] = dendrogram(TreeLapKWard, 'ColorThreshold', cutoff_lapK_ward);
H_lapK_ward = recolor_dendrogram(H_lapK_ward, clust_cols);
set(H_lapK_ward,'LineWidth',2)
title(sprintf('Hierarchical Clustering (after Laplace Embedding from K=%d-NN)',k));
xlabel('Sample Number');
ylabel('Height');
% str = sprintf('hier_lapK%d_ward_k%d',k,k0);
% saveas(gcf,str,'jpeg');
clear str k0 cutoff_lapK_ward cluster_lapK_ward perm_lapK_ward H_lapK_ward
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Laplace Embedding (Correlation) %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
m = 15;
[LapCX1,LambdaLapC] = lap_embed_corr(X1(:,2:15), m);
clear m
%%% 3-D Plots of Laplace Embedding (Correlation)
% fig_num = fig_num + 1;
% figure(fig_num)
% [i1,i2,i3] = deal(2,3,4);
% scatter3(LapCX1(:,i1),LapCX1(:,i2),LapCX1(:,i3),15,color_mat,'fill');
% %axis([-0.1 0.1 -0.1 0.1 -0.1 0.1]);
% title(sprintf('Laplace Embedding (Correlation) with %d,%d,%d',i1,i2,i3));
% xlabel(sprintf('Eig %d',i1));
% ylabel(sprintf('Eig %d',i2));
% zlabel(sprintf('Eig %d',i3));
% clear i1 i2 i3
%%% 2-D Plots of Laplace Embedding (Correlation)
% fig_num = fig_num + 1;
% figure(fig_num)
% [j1,j2] = deal(2,4);
% scatter(LapCX1(:,j1),LapCX1(:,j2),30,color_mat,'fill');
% %axis([-0.1 0.1 -0.1 0.1 -0.1 0.1]);
% title(sprintf('Laplace Embedding (Correlation) with %d,%d',j1,j2));
% xlabel(sprintf('Eig %d',j1));
% ylabel(sprintf('Eig %d',j2));
% % str = 'lap_corr';
% % saveas(gcf,str,'jpeg');
% clear str j1 j2
%%% Hierarchical Clustering of Embedding (Correlation)
k0 = 5;
TreeLapCWard = linkage(LapCX1(:,1:k0), 'ward', 'euclidean');
cutoff_lapC_ward = get_maxcluster_cutoff(TreeLapCWard, k0);
fig_num = fig_num + 1;
figure(fig_num)
[H_lapC_ward,cluster_lapC_ward,perm_lapC_ward] = dendrogram(TreeLapCWard, 'ColorThreshold', cutoff_lapC_ward);
H_lapC_ward = recolor_dendrogram(H_lapC_ward, clust_cols);
set(H_lapC_ward,'LineWidth',2)
title('Hierarchical Clustering (after Laplace Embedding from Correlation)');
xlabel('Sample Number');
ylabel('Height');
% str = sprintf('hier_lapC_ward_k%d',k0);
% saveas(gcf,str,'jpeg');
clear str k0 cutoff_lapC_ward cluster_lapC_ward perm_lapC_ward H_lapC_ward
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Functions %%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cutoff = get_maxcluster_cutoff(Z, k)
cutoff = Z(end-k+2,3)-eps;
end
function S = similarity_matrix_knn(X, k)
sz = size(X);
n1 = sz(1);
S = double(zeros(n1));
IDX = knnsearch(X, X, 'K', k);
for i=1:n1
for j=1:n1
sij = (sum(IDX(i,:) == j) > 0);
sji = (sum(IDX(j,:) == i) > 0);
if (sij || sji) S(i,j) = 1; else S(i,j) = 0; end;
end
end
end
function [LapX,Lambda] = lap_embed_knn(X, k, m)
S = similarity_matrix_knn(X, k);
n = length(S);
d = double(zeros(1,n));
for i=1:n
d(i) = sum(S(i,:));
end
P = double(zeros(n));
for i=1:n
for j=1:n
P(i,j) = S(i,j)/d(i);
end
end
[V,Lam] = eig(P);
Lambda = diag(Lam);
[list,I] = sort(abs(Lambda),'descend');
Lambda = Lambda(I);
Lambda = Lambda.';
V = V(:, I);
LapX = V(:,1:min(m,n));
Lambda = Lambda(1:min(m,n));
end
function S = similarity_matrix_corr(X)
S = squareform(pdist(X,'correlation'));
end
function [LapX,Lambda] = lap_embed_corr(X, m)
S = similarity_matrix_corr(X);
n = length(S);
d = double(zeros(1,n));
for i=1:n
d(i) = sum(S(i,:));
end
P = double(zeros(n));
for i=1:n
for j=1:n
P(i,j) = S(i,j)/d(i);
end
end
[V,Lam] = eig(P);
Lambda = diag(Lam);
[list,I] = sort(abs(Lambda),'descend');
Lambda = Lambda(I);
Lambda = Lambda.';
V = V(:, I);
LapX = V(:,1:min(m,n));
Lambda = Lambda(1:min(m,n));
end
function H = recolor_dendrogram(H, clust_cols)
n = length(H);
H_color = [1:n; 1:n; 1:n; 1:n; 1:n];
for i = 1:n
H_color(2:4,i) = H(i).Color;
H_color(5,i) = 100*H_color(2,i)+10*H_color(3,i)+H_color(4,i);
end
H_color_sorted = transpose(sortrows(transpose(H_color), [2 3 4 1]));
%disp(H_color_sorted);
index_list = unique(H_color_sorted(5,:));
num_colors = length(index_list);
for i = 1:num_colors
for j = 1:n
if H_color_sorted(5,j) == index_list(i)
H_color_sorted(2:4,j) = deal(clust_cols(i,:));
end
end
end
H_color = transpose(sortrows(transpose(H_color_sorted), 1));
for i = 1:n
H(i).Color = H_color(2:4,i);
end
end
|
github
|
jsbenjamins/gazecode-master
|
gazecode.m
|
.m
|
gazecode-master/code/gazecode.m
| 22,328 |
utf_8
|
d5406938333a82349e3999f2c9dd6bef
|
function gazecode()
% GazeCode (alpha version)
%
% This software allows for fast and flexible manual classification of any
% mobile eye-tracking data. Currently Pupil Labs and Tobii Pro Glasses data
% are supported. The software loads an exported visualisation (video file)
% and the data of a mobile eye-tracking measurement, runs a fixation
% detection algorithm (Hooge and Camps, 2013, Frontiers in Psychology, 4,
% 996) and offers a simple to use interface to browse through and
% categorise the detected fixations.
%
% How to use:
% 1) Place the GazeCode files in a directory to which you can navigate easily
% in Matlab
%
% 2) Export both a visualisation video of raw mobile eye-tracking data and
% the data itself.
% (demo data is available at http://tinyurl.com/gazecodedemodata)
%
% 3) Put the video file and the data file in the data folder of GazeCode
%
% 4) Find a set of nine 100 x 100 non-transparant PNGs reflecting the
% different categories you want to use (thenounproject.com is good place to
% start). Use white empty PNGs if you have less than 9 categories. Put
% these files in the categories folder of GazeCode.
%
% 5) In Matlab set the working directory to the code folder of GazeCode and
% type gazecode in the Matlab command window to start GazeCode.
%
% 6) When prompted, point GazeCode to the category set, files and folders it
% requests.
%
% 7) Browse through the detected fixations using the arrow buttons (or Z
% and X keys on the keyboard) in the left panel of GazeCode.
%
% 8) Assign a category to a fixation by using the category buttons in the
% right panel of GazeCode or use (numpad) keyboard keys 1-9. Category
% buttons are numbered left-to-right, bottom-to-top (analogue to the
% keyboard numpad).
%
% 9) Category codes of fixations can be exported to a file using the Save
% option in the menu of GazeCode.
%
% This open-source toolbox has been developed by J.S. Benjamins, R.S.
% Hessels and I.T.C. Hooge. When you use it, please cite:
% J.S. Benjamins, R.S. Hessels, I.T.C. Hooge (2017). GazeCode: an
% open-source toolbox for mobile eye-tracking data analysis. Journal of Eye
% Movement Research.
%
% For more information, questions, or to check whether we have updated to a
% better version, e-mail: [email protected]
% GazeCode is available from www.github.com/jsbenjamins/gazecode
%
% Most parts of GazeCode are licensed under the Creative Commons
% Attribution 4.0 (CC BY 4.0) license. Some functions are under MIT
% license, and some may be under other licenses.
%
% Tested on
% Matlab 2014a on Mac OSX 10.10.5
% Matlab 2013a on Windows 7 Enterprise, Service Pack 1
%% start fresh
clear all; close all; clc;
%% ========================================================================
% BIG NOTE: every variable that is needed somewhere in this code is stored
% in a structure array called gv that is added to the main window with the
% handle hm as userdata. When changing or adding variables in this struct
% it is thus needed to fetch using gv = get(hm, 'userdata') an update using
% use set(hm,'userdata',gv);
%% ========================================================================
% global gv;
gv.curframe = 1;
gv.minframe = 1;
gv.maxframe = 1;
gv.curfix = 1;
gv.maxfix = 1;
skipdataload = false;
% buttons
gv.fwdbut = 'x'; % move forward (next fixation)
gv.bckbut = 'z'; % move backward (previous fixation)
gv.cat1but = {'1','numpad1'};
gv.cat2but = {'2','numpad2'};
gv.cat3but = {'3','numpad3'};
gv.cat4but = {'4','numpad4'};
gv.cat5but = {'5','numpad5'};
gv.cat6but = {'6','numpad6'};
gv.cat7but = {'7','numpad7'};
gv.cat8but = {'8','numpad8'};
gv.cat9but = {'9','numpad9'};
gv.cat0but = {'0','numpad0'};
%% directories and settings
gv.foldnaam = 0;
gv.catfoldnaam = 0;
gv.fs = filesep;
gv.codedir = pwd;
addpath(gv.codedir);
gv.rootdir = pwd;
cd ..;
gv.resdir = [cd gv.fs 'results'];
cd(gv.resdir);
cd ..;
gv.catdir = [cd gv.fs 'categories'];
cd(gv.catdir);
cd ..;
gv.appdir = [cd gv.fs 'images'];
cd(gv.appdir);
cd ..;
gv.datadir = [cd gv.fs 'data'];
cd(gv.datadir);
gv.splashh = gazesplash([gv.appdir gv.fs 'splash.png']);
pause(1);
close(gv.splashh);
%% Select type of data you want to code (currently a version for Pupil Labs and Tobii Pro Glasses are implemented
% this is now a question dialog, but needs to be changed to a dropdown for
% more options. Question dialog allows for only three options
gv.datatype = questdlg(['What type of of mobile eye-tracking data do you want to code?'],'Data type?','Pupil Labs','Tobii Pro Glasses','Pupil Labs');
if strcmp(gv.datatype,'Tobii Pro Glasses')
help dispTobiiInstructions;
dispTobiiInstructions;
clc;
TobiiOK = questdlg(['Did you place the video file and the data file from Tobii in the data folder of GazeCode?'],'Are the Tobii files in the right location?','Yes, continue','No & quit','Yes, continue');
if strcmp(TobiiOK,'No & quit')
disp('GazeCode quit, since you indicated not having put the Tobii files in the right location.')
return
end
end
% set camera settings of eye-tracker data
switch gv.datatype
case 'Pupil Labs'
gv.wcr = [1280 720]; % world cam resolution
gv.ecr = [640 480]; % eye cam resolution
case 'Tobii Pro Glasses'
gv.wcr = [1920 1080]; % world cam resolution
gv.ecr = [640 480]; % eye cam resolution (assumption, not known ATM)
end
%% load data folder
while gv.foldnaam == 0
gv.foldnaam = uigetdir(gv.datadir,'Select data directory to code');
end
while gv.catfoldnaam == 0
gv.catfoldnaam = uigetdir(gv.catdir,'Select directory of categories');
end
filmnaam = strsplit(gv.foldnaam,gv.fs);
gv.filmnaam = filmnaam{end};
% check if results dir already exists (in that case, load previous or start
% over), otherwise create dir.
resdir = [gv.resdir gv.fs gv.filmnaam];
if exist([resdir gv.fs gv.filmnaam '.mat']) > 0
oudofnieuw = questdlg(['There already is a results directory with a file for ',gv.filmnaam,'. Do you want to load previous results or start over? Starting over will overwrite previous results.'],'Folder already labeled?','Load previous','Start over','Load previous');
if strcmp(oudofnieuw,'Load previous')
% IMPORANT NOTE FOR TESTING! This reloads gv! Use start over when
% making changes to this file.
load([resdir gv.fs gv.filmnaam '.mat']);
skipdataload = true;
else
rmdir(resdir,'s');
mkdir(resdir);
end
elseif exist(resdir) == 0
mkdir(resdir);
else
% do nothing
end
%% init main screen, don't change this section if you're not sure what you are doing
hm = figure(1);
set(hm,'Name','GazeCode','NumberTitle','off');
hmmar = [150 100];
set(hm, 'Units', 'pixels');
ws = truescreensize();
ws = [1 1 ws ];
% set figure full screen, position is bottom left width height!;
set(hm,'Position',[ws(1) + hmmar(1), ws(2) + hmmar(2), ws(3)-2*hmmar(1), ws(4)-2*hmmar(2)]);
% this is the first time gv is set to hm!
set(hm,'windowkeypressfcn',@verwerkknop,'closerequestfcn',@sluitaf,'userdata',gv);
% get coordinates main screen
hmpos = get(hm,'Position');
hmxc = hmpos(3)/2;
hmyc = hmpos(4)/2;
hmxmax = hmpos(3);
hmymax = hmpos(4);
% disable all button etc.
set(hm,'MenuBar','none');
set(hm,'DockControls','off');
set(hm,'Resize','off');
% main menu 1
mm1 = uimenu(hm,'Label','Menu');
% sub menu of main menu 1
sm0 = uimenu(mm1,'Label','Save to text','CallBack',@savetotext);
sm1 = uimenu(mm1,'Label','About GazeCode','CallBack','uiwait(msgbox(''This is version 1.0.1'',''About FixLabel''))');
%% left panel (Child 2 of hm), don't change this section if you're not sure what you are doing
lp = uipanel(hm,'Title','Fix Playback/Lookup','Units','pixels','FontSize',16,'BackgroundColor',[0.8 0.8 0.8]);
lpmar = [50 20];
gv.lp = lp;
set(lp,'Position',[1+lpmar(1) 1+lpmar(2) (hmxmax/2)-2*lpmar(1) hmymax-2*lpmar(2)]);
lpsize = get(lp,'Position');
lpsize = lpsize(3:end);
knopsize = [100 100];
knopmar = [20 10];
fwknop = uicontrol(lp,'Style','pushbutton','string','>>','callback',@playforward,'userdata',gv.fwdbut);
set(fwknop,'position',[lpsize(1)-knopsize(1)-knopmar(1) knopmar(2) knopsize]);
% set(fwknop,'backgroundcolor',[1 0.5 0]);
set(fwknop,'fontsize',20);
bkknop = uicontrol(lp,'Style','pushbutton','string','<<','callback',@playback,'userdata',gv.bckbut);
set(bkknop,'position',[knopmar knopsize]);
% set(bkknop,'backgroundcolor',[1 0.5 0]);
set(bkknop,'fontsize',20);
%% right panel (child 1 of hm), don't change this section if you're not sure what you are doing
rp = uipanel('Title','Categories','Units','pixels','FontSize',16,'BackgroundColor',[0.8 0.8 0.8]);
rpmar = [50 20];
set(rp,'Position',[hmxc+rpmar(1) 1+rpmar(2) (hmxmax/2)-2*rpmar(1) hmymax-2*rpmar(2)]);
rpsize = get(rp,'Position');
rpsize = rpsize(3:end);
% right panel buttons
knopsize = [150 150];
knopmar = [20];
% make grid
widthgrid = knopsize(1)*3+2*knopmar;
heightgrid = knopsize(2)*3+2*knopmar;
xstartgrid = floor((rpsize(1) - widthgrid)/2);
ystartgrid = rpsize(2) - heightgrid - knopmar;
opzij = knopmar+knopsize(1);
omhoog = knopmar+knopsize(2);
gridpos = [...
xstartgrid, ystartgrid, knopsize;...
xstartgrid+opzij, ystartgrid, knopsize;...
xstartgrid+2*opzij, ystartgrid, knopsize;...
xstartgrid ystartgrid+omhoog knopsize;...
xstartgrid+opzij ystartgrid+omhoog knopsize;...
xstartgrid+2*opzij ystartgrid+omhoog knopsize;...
xstartgrid ystartgrid+2*omhoog knopsize;...
xstartgrid+opzij ystartgrid+2*omhoog knopsize;...
xstartgrid+2*opzij ystartgrid+2*omhoog knopsize;...
];
gv.knoppen = [];
for p = 1:size(gridpos,1)
% gv.knoppen(p) = uicontrol(rp,'Style','pushbutton','HorizontalAlignment','left','string','','callback',@labelfix,'userdata',gv);
gv.knoppen(p) = uicontrol(rp,'Style','pushbutton','HorizontalAlignment','left','string','','callback',@labelfix,'userdata',gv);
set(gv.knoppen(p),'position',gridpos(p,:));
set(gv.knoppen(p),'backgroundcolor',[1 1 1]);
set(gv.knoppen(p),'fontsize',20);
set(gv.knoppen(p),'userdata',p);
imgData = imread([gv.catfoldnaam gv.fs num2str(p) '.png']);
imgData = imgData./maxall(imgData);
imgData = double(imgData);
set(gv.knoppen(p),'CData',imgData);
end
set(hm,'userdata',gv);
%% position axes of right panel to upper part of right panel. Don't change this section if you're not sure what you are doing
rpax = axes('Units','normal', 'Position', [0 0 1 1], 'Parent', rp,'visible','off');
set(rpax,'Units','pixels');
rpaxpos = get(rpax,'position');
tempx = rpaxpos(1);
tempy = rpaxpos(2);
tempw = rpaxpos(3);
temph = rpaxpos(4);
tempw = tempw - mod(tempw,16);
temph = (tempw/16) * 9;
tempx = floor((rpaxpos(3) - tempw)/2);
tempy = rpaxpos(4)-temph;
set(rpax,'Position',[tempx tempy tempw temph],'visible','off');
gv.rpaxpos = get(rpax,'position');
%% position axes of left panel to upper part of left panel. Don't change this section if you're not sure what you are doing
lpax = axes('Units','normal', 'Position', [0 0 1 1], 'Parent', lp,'visible','off');
set(lpax,'Units','pixels');
lpaxpos = get(lpax,'position');
tempx = lpaxpos(1);
tempy = lpaxpos(2);
tempw = lpaxpos(3);
temph = lpaxpos(4);
tempw = tempw - mod(tempw,16);
temph = (tempw/16) * 9;
tempx = floor((lpaxpos(3) - tempw)/2);
tempy = lpaxpos(4)-temph;
set(lpax,'Position',[tempx tempy tempw temph],'visible','on');
gv.lpaxpos = get(lpax,'position');
%% read video of visualisation, here cases can be added for other mobile eye trackers
% the Pupil Labs version expects the data to be in a specific folder that
% is default when exporting visualisations in Pupil Labs with a default
% name of the file, Tobii Pro Glasses does not, so select it.
switch gv.datatype
case 'Pupil Labs'
waarisdefilmdir = [gv.foldnaam gv.fs 'exports'];
[hoeveelfilms, nhoeveelfilms] = folderfromfolder(waarisdefilmdir);
if nhoeveelfilms > 1
% to be done still, select which visualisation movie to use if multiple
% exist
end
gv.vidObj = VideoReader([gv.foldnaam gv.fs 'exports' gv.fs hoeveelfilms.name gv.fs 'world_viz.mp4']);
case 'Tobii Pro Glasses'
[videofile,videopath] = uigetfile('.mp4','Select video file');
gv.vidObj = VideoReader([videopath gv.fs videofile]);
end
gv.fr = get(gv.vidObj,'FrameRate');
frdur = 1000/gv.fr;
nf = get(gv.vidObj,'NumberOfFrames');
gv.maxframe = nf;
gv.centerx = gv.vidObj.Width/2;
gv.centery = gv.vidObj.Height/2;
set(hm,'userdata',gv);
%% fixation detection using data
% read data and determine fixations, here cases can be added for other
% mobile eye trackers, as well as changing the fixation detection algorithm
% by altering the function that now runs on line 423.
if ~skipdataload
% to be done still, select data file from results directory if you
% want to skip data loading
gv = get(hm,'userdata');
disp('Determining fixations...');
switch gv.datatype
case 'Pupil Labs'
tempfold = folderfromfolder([gv.foldnaam gv.fs 'exports']);
% if there are more than one exports, it just takes the first!
tempfold = tempfold(1).name;
% note the typo! Pupils Labs currently exports postions not
% positions!
filenaam = [gv.foldnaam gv.fs 'exports' gv.fs tempfold gv.fs 'gaze_postions.csv'];
% this file reads the exported data file from Pupil Labs and gets time
% stamp and x and y coordinates
[gv.datt, gv.datx, gv.daty] = leesgazedata(filenaam);
% recalculate absolute timestamps to time from onset (0 ms)
gv.datt = double(gv.datt);
gv.datt2 = gv.datt;
gv.datt2(1) = 0;
for p = 2:length(gv.datt)
gv.datt2(p) = gv.datt(p) - gv.datt(p-1);
gv.datt2(p) = gv.datt2(p) + gv.datt2(p-1);
end
gv.datt2 = gv.datt2*1000;
gv.datt = gv.datt2;
gv.datx(gv.datx > 1) = NaN;
gv.datx(gv.datx < 0) = NaN;
gv.daty(gv.daty > 1) = NaN;
gv.daty(gv.daty < 0) = NaN;
gv.datx = gv.datx * gv.wcr(1) - gv.wcr(1)/2;
gv.daty = gv.daty * gv.wcr(2) - gv.wcr(2)/2;
case 'Tobii Pro Glasses'
[filenaam, filepad] = uigetfile('.txt','Select data file with fixations');
[gv.datt, gv.datx, gv.daty] = leesgazedataTobii([filepad gv.fs filenaam]);
%gv.datx = gv.datx * gv.wcr(1) - gv.wcr(1)/2;
%gv.daty = gv.daty * gv.wcr(2) - gv.wcr(2)/2;
otherwise
disp('Unknown data type, crashing in 3,2,1,...');
end
% determine start and end times of each fixation in one vector (odd
% number start times of fixations even number stop times)
% The line below determines fixations start and stop times since the
% beginning of the recording. For this detection of fixations the algo-
% rithm of Hooge and Camps (2013), but this can be replaced by your own
% favourite or perhaps more suitable fixation detectioon algorithm.
% Important is that this algorithm returns a vector that has fixation
% start times at the odd and fixation end times at the even positions
% of it.
gv.fmark = fixdetect(gv.datx,gv.daty,gv.datt,gv);
fixB = gv.fmark(1:2:end);
fixE = gv.fmark(2:2:end);
fixD = fixE- fixB;
[temptijd,idxtB,idxfixB] = intersect(gv.datt,fixB);
xstart = gv.datx(idxtB);
ystart = gv.daty(idxtB);
[temptijd,idxtE,idxfixE] = intersect(gv.datt,fixE);
xend = gv.datx(idxtE);
yend = gv.daty(idxtE);
for p = 1:length(idxtB)
xmean(p,1) = mean(gv.datx(idxtB(p):idxtE(p)));
ymean(p,1) = mean(gv.daty(idxtB(p):idxtE(p)));
xsd(p,1) = std(gv.datx(idxtB(p):idxtE(p)));
ysd(p,1) = std(gv.daty(idxtB(p):idxtE(p)));
end
fixnr = [1:length(fixB)]';
fixlabel = zeros(size(fixnr));
gv.data = [fixnr, fixB, fixE, fixD, xstart, ystart, xend, yend, xmean, xsd, ymean, ysd, fixlabel];
gv.maxfix = max(fixnr);
set(hm,'userdata',gv);
disp('... done');
% determine begin and end frame beloning to fixations start and end
% times
gv.bfr = floor(fixB/frdur);
gv.efr = ceil(fixE/frdur);
% determine the frame between beginning and end frame for a fixations,
% this one will be displayed
gv.mfr = floor((gv.bfr+gv.efr)/2);
if gv.mfr(end) > gv.maxframe
gv.mfr(end) = gv.maxframe;
end
gv.fixxpos = (gv.centerx + xmean);
gv.fixypos = (gv.centery - ymean);
gv.fixxposB = gv.centerx + xstart;
gv.fixyposB = gv.centery + ystart;
gv.fixxposE = gv.centerx + xend;
gv.fixyposE = gv.centery + yend;
gv.bfr(gv.bfr<1) = 1;
gv.bfr(gv.bfr>nf) = nf;
gv.efr(gv.efr<1) = 1;
gv.efr(gv.efr>nf) = nf;
set(hm,'userdata',gv);
end
%% start to show the first frame or when reloading the frame last coded.
showmainfr(hm,gv);
end
% function to attribute a category code to the fixation, this is a function
% of the buttons in the right panel
function labelfix(src,evt)
if isempty(evt)
categorie = get(src,'userdata');
rp = get(src,'parent');
hm = get(rp,'parent');
gv = get(hm,'userdata');
else
% if zero is pressed a code is reset
if ~strcmp(evt.Character,'0') || isempty(evt)
categorie = get(src,'userdata');
rp = get(src,'parent');
hm = get(rp,'parent');
gv = get(hm,'userdata');
else
hm = src;
categorie = 0;
gv = get(hm,'userdata');
end
end
data = gv.data;
data(gv.curfix,end) = categorie;
gv.data = data;
setlabel(gv);
set(hm,'userdata',gv);
end
% function to show the current frame and fixation being labeled
function showmainfr(hm,gv)
plaat = read(gv.vidObj,gv.mfr(gv.curfix));
imagesc(plaat);
frameas = gca;
axis off;
axis equal;
% clc;
disp(['Current fixation: ', num2str(gv.curfix),'/',num2str(gv.maxfix)]);
set(gv.lp,'Title',['Current fixation: ' num2str(gv.curfix),'/',num2str(gv.maxfix) ]);
hold(frameas,'off');
setlabel(gv);
if isempty(gv.data(:,end)==0)
msgbox('All fixations of this directory seem to be labeled','Warning','warn');
end
set(hm,'userdata',gv);
end
function setlabel(gv)
if gv.data(gv.curfix,end) > 0
for p = 1:size(gv.knoppen,2)
if p == gv.data(gv.curfix,end)
set(gv.knoppen(p),'backgroundcolor',[1 0.5 0]);
else
set(gv.knoppen(p),'backgroundcolor',[1 1 1]);
end
end
else
for p = 1:size(gv.knoppen,2)
set(gv.knoppen(p),'backgroundcolor',[1 1 1]);
end
end
end
% function to move one fixation further, function of button in left panel
function playforward(src,evt)
lp = get(src,'parent');
hm = get(lp,'parent');
gv = get(hm,'userdata');
if gv.curfix < gv.maxfix
gv.curfix = gv.curfix + 1;
showmainfr(hm,gv);
else
msgbox('Last fixation reached','Warning','warn');
end
set(hm,'userdata',gv);
end
% function move one fixation back, function of button in left panel
function playback(src,evt)
lp = get(src,'parent');
hm = get(lp,'parent');
gv = get(hm,'userdata');
if gv.curfix > 1
gv.curfix = gv.curfix - 1;
showmainfr(hm,gv);
else
h = msgbox('First fixation reached','Warning','warn');
end
set(hm,'userdata',gv);
end
% function to handle keypresses as shortcuts, function of main screen
function verwerkknop(src,evt)
gv = get(src,'userdata');
tsrc = get(src,'Children');
% Simplified as per suggestion of D.C. Niehorster on 2018-03-29
switch evt.Key
case gv.fwdbut
playforward(findobj('UserData',gv.fwdbut),evt);
case gv.bckbut
playback(findobj('UserData',gv.bckbut),evt);
case gv.cat1but
labelfix(findobj('UserData',1),evt);
case gv.cat2but
labelfix(findobj('UserData',2),evt);
case gv.cat3but
labelfix(findobj('UserData',3),evt);
case gv.cat4but
labelfix(findobj('UserData',4),evt);
case gv.cat5but
labelfix(findobj('UserData',5),evt);
case gv.cat6but
labelfix(findobj('UserData',6),evt);
case gv.cat7but
labelfix(findobj('UserData',7),evt);
case gv.cat8but
labelfix(findobj('UserData',8),evt);
case gv.cat9but
labelfix(findobj('UserData',9),evt);
case gv.cat0but
% pushing command buttons also codes as 0, so check whether
% evt.Modifier is empty to discern a command key with key zero
if isempty(evt.Modifier)
labelfix(src,evt);
end
otherwise
disp('Unknown key pressed');
end
end
function savetotext(src,evt)
disp('Saving to text...');
mm1 = get(src,'parent');
hm = get(mm1,'parent');
gv = get(hm,'userdata');
data = gv.data;
filenaam = [gv.resdir gv.fs gv.filmnaam gv.fs gv.filmnaam '.xls'];
while exist(filenaam,'file')
answer = inputdlg(['File: ', filenaam ,'.xls already exists. Enter a new file name'],'Warning: file already exists',1,{[gv.filmnaam '_01.xls']});
filenaam = [gv.resdir gv.fs gv.filmnaam gv.fs answer{1}];
end
fid = fopen(filenaam,'w+');
fprintf(fid,[repmat('%s\t',1,12),'%s\n'],'fix nr','fix start (ms)','fix end (ms)','fix dur (ms)','x start','y start','x end','y end','mean x','sd x','mean y','sd y','label');
fgetl(fid);
fprintf(fid,[repmat('%d\t',1,12),'%d\n'],gv.data');
fclose(fid);
disp('... done');
end
% closing and saving function
function sluitaf(src,evt)
gv = get(src,'userdata');
knopsluit = questdlg('You''re about to close the program. Are you sure you''re done and want to quit?','Are you sure?','Yes','No','No');
if strcmp('Yes',knopsluit);
% commandwindow;
disp('Closing...');
gv = rmfield(gv,'lp');
save([gv.resdir gv.fs gv.filmnaam gv.fs gv.filmnaam '.mat'],'gv');
disp('Saving...')
set(src,'closerequestfcn','closereq');
close(src);
else
disp('Program not closed. Continuing.');
end
end
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
CheckStructReg.m
|
.m
|
FreeHyTE-Structural-HTD-master/CheckStructReg.m
| 14,988 |
utf_8
|
9ec1e343b711657ba56b461c5499ceb1
|
function varargout = CheckStructReg(varargin)
% CHECKSTRUCTREG MATLAB code for CheckStructReg.fig
% CHECKSTRUCTREG, by itself, creates a new CHECKSTRUCTREG or raises the existing
% singleton*.
%
% H = CHECKSTRUCTREG returns the handle to a new CHECKSTRUCTREG or the handle to
% the existing singleton*.
%
% CHECKSTRUCTREG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHECKSTRUCTREG.M with the given input arguments.
%
% CHECKSTRUCTREG('Property','Value',...) creates a new CHECKSTRUCTREG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before CheckStructReg_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to CheckStructReg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help CheckStructReg
% Last Modified by GUIDE v2.5 20-Jun-2016 09:11:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @CheckStructReg_OpeningFcn, ...
'gui_OutputFcn', @CheckStructReg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before CheckStructReg is made visible.
function CheckStructReg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to CheckStructReg (see VARARGIN)
% Choose default command line output for CheckStructReg
handles.output = hObject;
% Launch input processor
[~,Nodes,Edges,Loops,~,~] = InputProcReg;
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
axis off ;
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes CheckStructReg wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = CheckStructReg_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in run.
function run_Callback(hObject, eventdata, handles)
% hObject handle to run (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(CheckStructReg); % closing the GUI window
pause(0.05); % to actually close it
MainReg;
% --- Executes on button press in previous.
function previous_Callback(hObject, eventdata, handles)
% hObject handle to previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(CheckStructReg);
StructRegBC2;
% --- Executes on button press in update.
function update_Callback(hObject, eventdata, handles)
% hObject handle to update (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% clearing the display
cla(gcf) ;
% getting the ViewOption
ViewOption = get(handles.view,'Value');
% Launch input processor
[~,Nodes,Edges,Loops,BConds,~] = InputProcReg;
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
if ViewOption==1 % just the mesh
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
elseif ViewOption==2 % just the BC, normal
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
elseif ViewOption==3 % just the BC, tangential
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
elseif ViewOption==4 % mesh & BC, normal
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.005*delta,sum(EY)/2+0.005*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold','color','b');
end
else % mesh & BC, tangential
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.005*delta,sum(EY)/2+0.005*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold','color','b');
end
end
% --- Executes on selection change in view.
function view_Callback(hObject, eventdata, handles)
% hObject handle to view (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns view contents as cell array
% contents{get(hObject,'Value')} returns selected item from view
% --- Executes during object creation, after setting all properties.
function view_CreateFcn(hObject, eventdata, handles)
% hObject handle to view (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
StructTriBC1.m
|
.m
|
FreeHyTE-Structural-HTD-master/StructTriBC1.m
| 16,215 |
utf_8
|
18071396a70e5a6c5d00c2801681c3b4
|
%% STANDARD, PREDEFINED FUNCTIONS
% No changes were made to the following functions, predefined by GUIDE
function varargout = StructTriBC1(varargin)
% STRUCTTRIBC1 MATLAB code for StructTriBC1.fig
% STRUCTTRIBC1, by itself, creates a new STRUCTTRIBC1 or raises the existing
% singleton*.
%
% H = STRUCTTRIBC1 returns the handle to a new STRUCTTRIBC1 or the handle to
% the existing singleton*.
%
% STRUCTTRIBC1('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in STRUCTTRIBC1.M with the given input arguments.
%
% STRUCTTRIBC1('Property','Value',...) creates a new STRUCTTRIBC1 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before StructTriBC1_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to StructTriBC1_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help StructTriBC1
% Last Modified by GUIDE v2.5 03-Jun-2017 13:50:49
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @StructTriBC1_OpeningFcn, ...
'gui_OutputFcn', @StructTriBC1_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Outputs from this function are returned to the command line.
function varargout = StructTriBC1_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%% OPENING FUNCTION
% * Executes just before StructTriBC1 is made visible;
% * Reads the mesh data from the |mat| file of the previous GUI and
% constructs the topological matrices;
% * If the |mat| file associated to the current GUI exists (meaning that
% the previous GUI was not changed), it loads the boundary information,
% otherwise it sets all boundaries to Dirichlet.
function StructTriBC1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StructTriBC1 (see VARARGIN)
%%
% Creates the |handles| structure
% Choose default command line output for |StructTriBC1|
handles.output = hObject;
%%
% Loading the mesh information (is different for Regular and Triangular
% routines, but essentially does the same thing).
load('StructDef','p','t');
%%
% Calls an external function that creates all topological matrices. In the
% Regular routine, this is done in the opening function, rather than
% externally.
[nodes, edges_nodes, edges_loops, loops_nodes, loops_edges] = CreateEdgeLoop(p,t);
%%
% Getting the exterior edges. In the Regular routine, this information is
% obtained from the |mat| file of the previous GUI.
edgesArray = find(edges_loops(:,2)==0);
%%
% Publishing the topological information in the |handles| structure, to
% make it available to all functions associated to the current GUI.
set(handles.listbox1,'string',edgesArray);
handles.DorN = get(handles.popupmenu1,'String');
handles.data = cell(length(edgesArray),2);
handles.edgesArray = edgesArray;
handles.nodes = nodes;
handles.edges_nodes = edges_nodes;
handles.edges_loops = edges_loops;
handles.loops_nodes = loops_nodes;
handles.loops_edges = loops_edges;
%%
% If there exists a local |mat| file, it loads its key elements to fill in
% the fields with data taken from the previous run...
if exist('./StructTriBC1.mat','file') % reuse the previous data
load('StructTriBC1','data');
handles.data=data;
%%
% ... otherwise it just presets all boundaries to 'Dirichlet' type.
else
for i=1:length(edgesArray)
handles.data{i,1}=edgesArray(i);
handles.data{i,2}=handles.DorN{1}; % Dirichlet as predefined boundary type
end
end
%%
% Creates the table where the boundaries are listed, along with their types
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
%%
% Generates the code for drawing the mesh, along with the mesh information
% buttons
nel = size(loops_nodes,1); % Total Number of Elements in the Mesh
nnel = size(loops_nodes,2); % Number of nodes per Element
nnode = size(nodes,1); % Total Number of Nodes in the Mesh
nedge = size(edges_nodes,1); % Total Number of Edges in the Mesh
% For drawing purposes
limxmin = min(nodes(:,1));
limxmax = max(nodes(:,1));
limymin = min(nodes(:,2));
limymax = max(nodes(:,2));
%
% Plotting the Finite Element Mesh
% Initialization of the required matrices
X = zeros(nnel,nel) ;
Y = zeros(nnel,nel) ;
% Extract X,Y coordinates for the (iel)-th element
for iel = 1:nel
X(:,iel) = nodes(loops_nodes(iel,:),1) ;
Y(:,iel) = nodes(loops_nodes(iel,:),2) ;
end
patch(X,Y,'w');
axis([limxmin-0.01*abs(limxmin) limxmax+0.01*abs(limxmax) limymin-0.01*abs(limymin) limymax+0.01*abs(limymax)]);
axis equal;
axis off ;
% To display Node Numbers % Element Numbers
axpos = getpixelposition(handles.axes2); % position & dimension of the axes object
% Define button's weight and height
bweight = 60;
bheight = 20;
pos = [((axpos(1)+axpos(3))/2) (axpos(2)-1.5*bheight) bweight bheight]; % align the second button with the center of the axes obj limit
ShowNodes = uicontrol('style','toggle','string','Nodes',....
'position',[(pos(1)-2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
ShowEdges = uicontrol('style','toggle','string','Edges',....
'position',[pos(1) pos(2) pos(3) pos(4)],'background','white',...
'units','Normalized');
ShowElements = uicontrol('style','toggle','string','Elements',....
'position',[(pos(1)+2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
set(ShowNodes,'callback',...
{@SHOWNODES,ShowEdges,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowEdges,'callback',...
{@SHOWEDGES,ShowNodes,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowElements,'callback',....
{@SHOWELEMENTS,ShowNodes,ShowEdges,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
%%
% Updates the handles structure
guidata(hObject, handles);
%% NEXT BUTTON
% * Executes on button press in |pushbutton_next|;
% * It recovers all data provided by the user in the GUI fields and the
% topological matrices computed in the opening function;
% * It checks for relevant (i.e. mesh and boundary type) changes as
% compared to the previous |mat| file. If such changes exist, it deletes
% the |mat| file corresponding to the next GUI to force its definition from
% scratch. If no mesh changes were detected, the next GUI will load its
% previous version;
% * If the user asked for the model to be saved, it saves the information
% regarding this GUI in the specified file and folder.
function pushbutton_next_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Recovering the data created or set by the user in the current GUI
data=handles.data;
DorN=handles.DorN;
edgesArray = handles.edgesArray;
nodes = handles.nodes;
edges_nodes = handles.edges_nodes;
edges_loops = handles.edges_loops;
loops_nodes = handles.loops_nodes;
loops_edges = handles.loops_edges;
%%
% Check if critical changes were made in the current GUI session.
if exist('./StructTriBC1.mat','file')
save('ToDetectChanges','data'); % temporary file to detect critical changes
% Fields whose change triggers the change of the mesh
CriticalFields = {'data'};
% Checks the old StructRegBC1 and the new ToDetectChanges for changes in
% the critical fields. ChangesQ = 1 if there are changes, 0 otherwise
ChangesQ = any(~isfield(comp_struct(load('StructTriBC1.mat'),...
load('ToDetectChanges.mat')),CriticalFields));
% deleting the auxiliary file
delete('ToDetectChanges.mat');
%%
% If the |mat| file associated to the current GUI session does not exist,
% it is likely because the previous GUI was modified. In this case the
% next GUI needs to be reinitialized.
else
ChangesQ = 1;
end
%%
% Saving the workspace to the local |mat| file. If requested by the
% user, the GUI information is also _appended_ to the file specified by the
% user.
load('StructDef','DirName','FileName');
% if requested by the user, saves to file
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'data','DorN','nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges','edgesArray');
end
% saves the local data file
save('StructTriBC1',...
'data','DorN','nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges','edgesArray');
% saves the data required by VisualizeTri to the local data file
save('Visualize',...
'nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
%%
% Preparing to exit.
close(handles.figure1);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
%%
% If there are relevant changes, it physically deletes the |mat| files
% associated to the next GUI.
if ChangesQ
delete('StructTriBC2.mat');
end
StructTriBC2;
%% RESET BUTTON
% * Executes on button press in |pushbutton_reset|.
% * It resets all tables and defines all boundaries as Dirichlet.
function pushbutton_reset_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Setting all edges to Dirichlet type...
edgesArray = handles.edgesArray;
handles.DorN = get(handles.popupmenu1,'String');
handles.data = cell(length(edgesArray),2);
for i=1:length(edgesArray)
handles.data{i,1}=edgesArray(i);
handles.data{i,2}=handles.DorN{1}; % Dirichlet as predefined boundary type
end
%%
% ... and redrawing the table.
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
%% PREVIOUS BUTTON
% * Executes on button press in |pushbutton_previous|;
% * Just closes the current GUI and launches the previous one. All changes
% made in the current GUI are lost.
function pushbutton_previous_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(StructTriBC1);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
StructDef(2);
%% ASSIGN BUTTON
% * Executes on button press in |assign|;
% * Fills in the boundary type table for the boundaries selected in
% |listbox1| with 'Dirichlet' or 'Neumann', as defined in |popupmenu1|.
function assign_Callback(hObject, eventdata, handles)
% hObject handle to assign (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Gets the selected items in |listbox1|
itemlist = get(handles.listbox1,'value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
%%
% Sets the |data| for the selected items to the type selected in
% |popupmenu1|.
if get(handles.popupmenu1,'value')==1 % if Dirichlet is selected
for ii = 1:nitems
crtitem = itemlist(ii);
handles.data{crtitem,2}=handles.DorN{1};
end
else % if Neumann is selected
for ii = 1:nitems
crtitem = itemlist(ii);
handles.data{crtitem,2}=handles.DorN{2};
end
end
%%
% Updates the handles structure
guidata(hObject,handles);
%%
% Redraws the table
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
% --- Executes on button press in enlarge.
function enlarge_Callback(hObject, eventdata, handles)
% hObject handle to enlarge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Recovering the data created or set by the user in the current GUI
nodes = handles.nodes;
edges_nodes = handles.edges_nodes;
edges_loops = handles.edges_loops;
loops_nodes = handles.loops_nodes;
loops_edges = handles.loops_edges;
% saves the data required by Visualize to the local data file
save('Visualize',...
'nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
VisualizeTri;
%% GUI ENTITIES GENERATION CODE
% * Automatically generated code
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
StructTriBC2.m
|
.m
|
FreeHyTE-Structural-HTD-master/StructTriBC2.m
| 25,242 |
utf_8
|
3ce94f3d416f7e0c7ec937ca8175b84d
|
%% STANDARD, PREDEFINED FUNCTIONS
% No changes were made to the following functions, predefined by GUIDE
function varargout = StructTriBC2(varargin)
% STRUCTTRIBC2 MATLAB code for StructTriBC2.fig
% STRUCTTRIBC2, by itself, creates a new STRUCTTRIBC2 or raises the existing
% singleton*.
%
% H = STRUCTTRIBC2 returns the handle to a new STRUCTTRIBC2 or the handle to
% the existing singleton*.
%
% STRUCTTRIBC2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in STRUCTTRIBC2.M with the given input arguments.
%
% STRUCTTRIBC2('Property','Value',...) creates a new STRUCTTRIBC2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before StructTriBC2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to StructTriBC2_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to next (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help StructTriBC2
% Last Modified by GUIDE v2.5 15-Jul-2016 10:27:01
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @StructTriBC2_OpeningFcn, ...
'gui_OutputFcn', @StructTriBC2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Outputs from this function are returned to the command line.
function varargout = StructTriBC2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%% OPENING FUNCTION
% * Executes just before |StructTriBC2| is made visible;
% * Reads the mesh data from the |mat| file of the previous GUI and
% constructs the lists of Dirichlet and Neumann boundaries;
% * If the |mat| file of the current GUI exists (meaning that the
% previous GUI was not changed), it loads the boundary information,
% otherwise it sets all boundaries to Dirichlet.
function StructTriBC2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StructTriBC2 (see VARARGIN)
%%
% Creates the |handles| structure
% Choose default command line output for |StructTriBC2|
handles.output = hObject;
%%
% Loads the exterior edges and their types from the previous GUI
load('StructTriBC1','edgesArray','data','DorN'); % data contains pairs of edges and their types
%%
% Creates two arrays listing the exterior Dirichlet and Neumann edges
% (|edgesDirichlet| and |edgesNeumann|)
for i=1:length(edgesArray)
if strcmp(data{i,2},DorN{1}) % if the edge type is Dirichlet
handles.edgesDirichlet(i,1)=edgesArray(i); % list with the Dirichlet edges
else
handles.edgesNeumann(i,1)=edgesArray(i); % list with the Neumann edges
end
end
%%
% *Dirichlet boundary conditions*
%%
% Generates the |dataDir| matrix to store the id of the exterior Dirichlet
% edges and their enforced boundary conditions in the normal and tangential
% directions. The |dataDir| matrix is created from from scratch or imported
% from the |StructRegBC2| file, if such file exists (meaning that the
% previous GUI was left unchanged).
% It is recalled that if a displacement boundary condition is enforced in a
% single direction and left free in the other, the boundary should be
% defined as Dirichlet and the kinematic boundary condition in the free
% direction should be defined as NaN.
if isfield(handles,'edgesDirichlet')==1
handles.edgesDirichlet(handles.edgesDirichlet==0)=[];
%%
% Writes all |edgesDirichlet| into the |listboxDir|
set(handles.listboxDir,'string',handles.edgesDirichlet);
%%
% Creates the |dataDir| matrix.
handles.dataDir=cell(length(handles.edgesDirichlet),3);
%%
% If there exists a local |mat| file, it loads it to fill in
% the fields with data taken from the previous next...
if exist('./StructTriBC2.mat','file') % reuse the previous data
load('StructTriBC2','dataDir');
handles.dataDir=dataDir;
%%
% ... otherwise it just sets all Dirichlet boundary conditions to NaN
else
for i=1:length(handles.edgesDirichlet)
handles.dataDir{i,1}=handles.edgesDirichlet(i);
handles.dataDir{i,2}='NaN';
handles.dataDir{i,3}='NaN';
end
end
%%
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
end
%%
% *Neumann boundary conditions*
%%
% Generates the |dataNeu| matrix to store the id of the exterior Neumann
% edges and their enforced boundary conditions in the normal and tangential
% directions. The |dataNeu| matrix is created from from scratch or imported
% from the |StructRegBC2| file, if such file exists (meaning that the
% previous GUI was left unchanged).
if isfield(handles,'edgesNeumann')==1
handles.edgesNeumann(handles.edgesNeumann==0)=[];
%%
% Writes all |edgesNeumann| into the |listboxNeu|
set(handles.listboxNeu,'string',handles.edgesNeumann);
%%
% Creates the |dataNeu| matrix.
handles.dataNeu=cell(length(handles.edgesNeumann),3);
%%
% If there exists a local |mat| file, it loads it to fill in
% the fields with data taken from the previous next...
if exist('./StructTriBC2.mat','file') % reuse the previous data
load('StructTriBC2','dataNeu');
handles.dataNeu=dataNeu;
%%
% ... otherwise it just sets all Neumann boundary conditions to NaN
else
for i=1:length(handles.edgesNeumann)
handles.dataNeu{i,1}=handles.edgesNeumann(i);
handles.dataNeu{i,2}='NaN';
handles.dataNeu{i,3}='NaN';
end
end
%%
% Creates the table where the Neumann boundary conditions are listed,
% along with their types
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
end
%%
% Generates the code for drawing the mesh, along with the mesh information
% buttons
%load the mesh data
load('StructTriBC1','nodes','edges_nodes','edges_loops','loops_nodes',...
'loops_edges');
nel = size(loops_nodes,1); % Total Number of Elements in the Mesh
nnel = size(loops_nodes,2); % Number of nodes per Element
nnode = size(nodes,1); % Total Number of Nodes in the Mesh
nedge = size(edges_nodes,1); % Total Number of Edges in the Mesh
% For drawing purposes
limxmin = min(nodes(:,1));
limxmax = max(nodes(:,1));
limymin = min(nodes(:,2));
limymax = max(nodes(:,2));
%
% Plotting the Finite Element Mesh
% Initialization of the required matrices
X = zeros(nnel,nel) ;
Y = zeros(nnel,nel) ;
% Extract X,Y coordinates for the (iel)-th element
for iel = 1:nel
X(:,iel) = nodes(loops_nodes(iel,:),1) ;
Y(:,iel) = nodes(loops_nodes(iel,:),2) ;
end
patch(X,Y,'w')
axis([limxmin-0.01*abs(limxmin) limxmax+0.01*abs(limxmax) limymin-0.01*abs(limymin) limymax+0.01*abs(limymax)]);
axis equal;
axis off ;
% To display Node Numbers % Element Numbers
axpos = getpixelposition(handles.axes3); % position & dimension of the axes object
% Define button's weight and height
bweight = 60;
bheight = 20;
pos = [((axpos(1)+axpos(3))/2) (axpos(2)-1.5*bheight) bweight bheight]; % align the second button with the center of the axes obj limit
ShowNodes = uicontrol('style','toggle','string','Nodes',....
'position',[(pos(1)-2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
ShowEdges = uicontrol('style','toggle','string','Edges',....
'position',[pos(1) pos(2) pos(3) pos(4)],'background','white',...
'units','Normalized');
ShowElements = uicontrol('style','toggle','string','Elements',....
'position',[(pos(1)+2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
set(ShowNodes,'callback',...
{@SHOWNODES,ShowEdges,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowEdges,'callback',...
{@SHOWEDGES,ShowNodes,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowElements,'callback',....
{@SHOWELEMENTS,ShowNodes,ShowEdges,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
%%
% Updates the handles structure
guidata(hObject, handles);
%% NEXT FUNCTION
% * Executes on button press in |next|;
% * Reads the boundary condition data, stores it in the local |mat| file
% and starts the checking GUI;
% * If the user asked for the model to be saved, it saves the information
% regarding this GUI in the specified file and folder.
function next_Callback(hObject, eventdata, handles)
% hObject handle to next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Recovering the user-defined data
if isfield(handles,'edgesDirichlet')
edgesDirichlet=handles.edgesDirichlet;
dataDir=handles.dataDir;
% Converting strings in data arrays to matrices
D = cellfun(@str2num,dataDir(:,2:end),'UniformOutput',0);
% Looking for NaN in D & N
NaND = cellfun(@any,cellfun(@isnan,D,'UniformOutput',0));
end
if isfield(handles,'edgesNeumann')
edgesNeumann=handles.edgesNeumann;
dataNeu=handles.dataNeu;
% Converting strings in data arrays to matrices
N = cellfun(@str2num,dataNeu(:,2:end),'UniformOutput',0);
% Looking for NaN in D & N
NaNN = cellfun(@any,cellfun(@isnan,N,'UniformOutput',0));
end
%%
% Checking the data
if any(all(NaND,2)) % if all Dirichlet conditions on an edge are NaN
errordlg('All Dirichlet boundary conditions are set to NaN at least for one boundary.','Invalid input','modal');
return;
end
if any(any(NaNN,2)) % if any Neumann conditions are NaN
errordlg('At least one Neumann boundary condition is set to NaN.','Invalid input','modal');
return;
end
%%
% Saving the local data to save files
% If StructTriBC2.mat does not exist, it creates it
if ~exist('./StructTriBC2.mat','file')
dummy = 0;
save('StructTriBC2','dummy');
end
%%
% If requested by the user, appends the local data to the save file
load('StructDef','DirName','FileName');
if isfield(handles,'edgesDirichlet')
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'edgesDirichlet','dataDir');
end
save('StructTriBC2','-append','edgesDirichlet','dataDir');
end
if isfield(handles,'edgesNeumann')
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'edgesNeumann','dataNeu');
end
save('StructTriBC2','-append','edgesNeumann','dataNeu');
end
%%
% Closes everything and launches the ckecking GUI
close(handles.figure1); % closing the GUI window
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
CheckStructTri;
%% ASSIGN FORCE FUNCTION
% * Executes on button press in |assignForce|;
% * Fills in the enforced load table for the boundaries selected in
% |listboxNeu| with the string defined in |editForce|, in the direction
% defined in the |popupmenu_NTNeu|.
function assignForce_Callback(hObject, eventdata, handles)
% hObject handle to assignForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Gets the selected boundaries in |listboxNeu| and the direction of the
% load in |popupmenu_NTNeu|
itemlist = get(handles.listboxNeu,'Value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
ForceDirection = get(handles.popupmenu_NTNeu,'Value');
%%
% Writes the force definition in the column of |dataNeu| corresponding to
% the direction the force is applied into.
for ii = 1:nitems
crtitem = itemlist(ii);
handles.dataNeu{crtitem,ForceDirection+1}=get(handles.editForce,'string');
end
%%
% Updates the handles structure
guidata(hObject,handles);
%%
% Redraws the table where the Neumann boundary conditions are listed
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
%% ASSIGN DISPLACEMENT FUNCTION
% * Executes on button press in |assignDisp|;
% * Fills in the enforced load table for the boundaries selected in
% |listboxDir| with the string defined in |editDisp|, in the direction
% defined in the |popupmenu_NTDir|.
function assignDisp_Callback(hObject, eventdata, handles)
% hObject handle to assignDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Gets the selected boundaries in |listboxDir| and the direction of the
% load in |popupmenu_NTDir|
itemlist = get(handles.listboxDir,'Value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
DispDirection = get(handles.popupmenu_NTDir,'Value');
%%
% Writes the displacemment definition in the column of |dataDir| associated
% to the direction the displacement is applied into.
for ii = 1:nitems
crtitem = itemlist(ii);
handles.dataDir{crtitem,DispDirection+1}=get(handles.editDisp,'string');
end
%%
% Updates the handles structure
guidata(hObject,handles);
%%
% Redraws the table where the Dirichlet boundary conditions are listed
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
%% RESET NEUMANN/DIRICHLET BOUNDARY CONDITION FUNCTIONS
%%
% *Reset Neumann*
%
% * Executes on button press in |resetNeumann|;
% * Substitutes all previous definitions in |dataNeu| by |NaN|;
% * Redraws the force boundary condition table.
function resetNeumann_Callback(hObject, eventdata, handles)
% hObject handle to resetNeumann (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Substitutes all previous definitions in |dataNeu| by |NaN|
for i=1:length(handles.edgesNeumann)
handles.dataNeu{i,2}='NaN';
handles.dataNeu{i,3}='NaN';
end
%%
% Updates the handles structure
guidata(hObject,handles);
%%
% Redraws the table where the Neumann boundary conditions are listed
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
%%
% *Reset Dirichlet*
%
% * Executes on button press in |resetDirichlet|;
% * Substitutes all previous definitions in |dataDir| by |NaN|;
% * Redraws the displacement boundary condition table.
function resetDirichlet_Callback(hObject, eventdata, handles)
% hObject handle to resetDirichlet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Substitutes all previous definitions in |dataDir| by |NaN|
for i=1:length(handles.edgesDirichlet)
handles.dataDir{i,2}='NaN';
handles.dataDir{i,3}='NaN';
end
%%
% Updates the handles structure
guidata(hObject,handles);
%%
% Redraws the table where the Dirichlet boundary conditions are listed
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
%% PREVIOUS FUNCTION
% * Executes on button press in |previous|;
% * Just closes the current GUI and launches the previous one. All changes
% made in the current GUI are lost.
function previous_Callback(hObject, eventdata, handles)
% hObject handle to previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(StructTriBC2);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
StructTriBC1;
% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
VisualizeTri;
%% GUI ENTITIES GENERATION CODE
% * Automatically generated code for the buttons and menus;
% * Some (not-so-sound) checks are performed on the data inserted by the
% user in |editDisp| and |editNeu| just to make sure they are
% mathematically legible.
% --- Executes on selection change in listboxNeu.
function listboxNeu_Callback(hObject, eventdata, handles)
% hObject handle to listboxNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listboxNeu contents as cell array
% contents{get(hObject,'Value')} returns selected item from listboxNeu
% --- Executes during object creation, after setting all properties.
function listboxNeu_CreateFcn(hObject, eventdata, handles)
% hObject handle to listboxNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editForce_Callback(hObject, eventdata, handles)
% hObject handle to editForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editForce as text
% str2double(get(hObject,'String')) returns contents of editForce as a double
[Flux, status] = str2num(get(hObject,'string'));
if any(isnan(Flux)) || ~status % if the input is something else than
% a vector of reals
set(hObject,'String','');
errordlg('Flux field must have real value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function editForce_CreateFcn(hObject, eventdata, handles)
% hObject handle to editForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in listboxDir.
function listboxDir_Callback(hObject, eventdata, handles)
% hObject handle to listboxDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listboxDir contents as cell array
% contents{get(hObject,'Value')} returns selected item from listboxDir
% --- Executes during object creation, after setting all properties.
function listboxDir_CreateFcn(hObject, eventdata, handles)
% hObject handle to listboxDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editDisp_Callback(hObject, eventdata, handles)
% hObject handle to editDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editDisp as text
% str2double(get(hObject,'String')) returns contents of editDisp as a double
[U, status] = str2num(get(hObject,'string'));
if ~status % if the input is something else than a vector of reals (or a NaN)
set(hObject,'string','');
errordlg('Sate field must have real value','Invalid input','modal');
uicontrol(hObject);
return;
end
if length(U)~=1 && any(isnan(U)) % if more than one term in input and one of them is NaN
set(hObject,'string','');
errordlg('A NaN Dirichlet boundary condition cannot be defined along with any other term','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function editDisp_CreateFcn(hObject, eventdata, handles)
% hObject handle to editDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_NTDir.
function popupmenu_NTDir_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_NTDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_NTDir contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_NTDir
% --- Executes during object creation, after setting all properties.
function popupmenu_NTDir_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_NTDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_NTNeu.
function popupmenu_NTNeu_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_NTNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_NTNeu contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_NTNeu
% --- Executes during object creation, after setting all properties.
function popupmenu_NTNeu_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_NTNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
VisualizeTri.m
|
.m
|
FreeHyTE-Structural-HTD-master/VisualizeTri.m
| 4,483 |
utf_8
|
affd85f9ab67bc4eeb5f266cbb69374c
|
function varargout = VisualizeTri(varargin)
% VISUALIZETRI MATLAB code for VisualizeTri.fig
% VISUALIZETRI, by itself, creates a new VISUALIZETRI or raises the existing
% singleton*.
%
% H = VISUALIZETRI returns the handle to a new VISUALIZETRI or the handle to
% the existing singleton*.
%
% VISUALIZETRI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VISUALIZETRI.M with the given input arguments.
%
% VISUALIZETRI('Property','Value',...) creates a new VISUALIZETRI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before VisualizeTri_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to VisualizeTri_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help VisualizeTri
% Last Modified by GUIDE v2.5 15-Jul-2016 09:17:00
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @VisualizeTri_OpeningFcn, ...
'gui_OutputFcn', @VisualizeTri_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before VisualizeTri is made visible.
function VisualizeTri_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to VisualizeTri (see VARARGIN)
% Choose default command line output for VisualizeTri
handles.output = hObject;
% Create data structures
load('Visualize','nodes','edges_nodes','edges_loops','loops_nodes',...
'loops_edges');
% Definitions of the data structures
Nodes = nodes;
Edges=struct('nini',edges_nodes(:,1),'nfin',edges_nodes(:,2),...
'parametric',createLine(Nodes(edges_nodes(:,1),:),...
Nodes(edges_nodes(:,2),:)),...
'lleft',edges_loops(:,1),'lright',edges_loops(:,2),...
'type',char(zeros(length(edges_nodes(:,1)),1)),'order',...
zeros(length(edges_nodes(:,1)),1));
Loops=struct('nodes',loops_nodes,'edges',loops_edges,...
'center',zeros(length(loops_nodes(:,1)),2),...
'area',zeros(length(loops_nodes(:,1)),1));
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
axis off ;
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes VisualizeTri wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = VisualizeTri_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
StructRegBC2.m
|
.m
|
FreeHyTE-Structural-HTD-master/StructRegBC2.m
| 20,555 |
utf_8
|
a9852dc440c14f3d430b4968d279bead
|
function varargout = StructRegBC2(varargin)
% STRUCTREGBC2 MATLAB code for StructRegBC2.fig
% STRUCTREGBC2, by itself, creates a new STRUCTREGBC2 or raises the existing
% singleton*.
%
% H = STRUCTREGBC2 returns the handle to a new STRUCTREGBC2 or the handle to
% the existing singleton*.
%
% STRUCTREGBC2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in STRUCTREGBC2.M with the given input arguments.
%
% STRUCTREGBC2('Property','Value',...) creates a new STRUCTREGBC2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before StructRegBC2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to StructRegBC2_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to next (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help StructRegBC2
% Last Modified by GUIDE v2.5 17-Jul-2016 19:59:15
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @StructRegBC2_OpeningFcn, ...
'gui_OutputFcn', @StructRegBC2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Outputs from this function are returned to the command line.
function varargout = StructRegBC2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes just before StructRegBC2 is made visible.
function StructRegBC2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StructRegBC2 (see VARARGIN)
% Choose default command line output for StructRegBC2
handles.output = hObject;
load('StructDef','edgesArray'); % edgesArray contains all exterior edges
load('StructRegBC1','data','DorN'); % data contains pairs of edges and their types
for i=1:length(edgesArray)
if strcmp(data{i,2},DorN{1}) % if the edge type is Dirichlet
handles.edgesDirichlet(i,1)=edgesArray(i); % list with the Dirichlet edges
else
handles.edgesNeumann(i,1)=edgesArray(i); % list with the Neumann edges
end
end
% Creating dataDir from scratch or reading it from StructRegBC2 file
if isfield(handles,'edgesDirichlet')==1
handles.edgesDirichlet(handles.edgesDirichlet==0)=[];
set(handles.listboxDir,'string',handles.edgesDirichlet);
handles.dataDir=cell(length(handles.edgesDirichlet),3);
if exist('./StructRegBC2.mat','file') % reuse the previous data
load('StructRegBC2','dataDir');
handles.dataDir=dataDir;
else
for i=1:length(handles.edgesDirichlet)
handles.dataDir{i,1}=handles.edgesDirichlet(i);
handles.dataDir{i,2}='NaN';
handles.dataDir{i,3}='NaN';
end
end
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
end
% Creating dataNeu from scratch or reading it from StructRegBC2 file
if isfield(handles,'edgesNeumann')==1
handles.edgesNeumann(handles.edgesNeumann==0)=[];
set(handles.listboxNeu,'string',handles.edgesNeumann);
handles.dataNeu=cell(length(handles.edgesNeumann),3);
if exist('./StructRegBC2.mat','file') % reuse the previous data
load('StructRegBC2','dataNeu');
handles.dataNeu=dataNeu;
else
for i=1:length(handles.edgesNeumann)
handles.dataNeu{i,1}=handles.edgesNeumann(i);
handles.dataNeu{i,2}='NaN';
handles.dataNeu{i,3}='NaN';
end
end
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
end
% ****** DRAW THE MESH ******
%load the array of edges
load('StructDef','L','B','Nx','Ny');
%load the mesh data
load('StructRegBC1','nodes','edges_nodes','edges_loops','loops_nodes',...
'loops_edges');
nel = Nx*Ny ; % Total Number of Elements in the Mesh
nnel = 4 ; % Number of nodes per Element
% Number of points on the Length and Width
npx = Nx+1 ;
npy = Ny+1 ;
nnode = npx*npy ; % Total Number of Nodes in the Mesh
% Number of edges on the Length and Width
nedgex = Nx*npy; % Number of Horizontal Edges
nedgey = Ny*npx; % Number of Vertical Edges
nedge = nedgex+nedgey; % Total Number of Edges in the Mesh
% For drawing purposes
limxmin = min(nodes(:,1));
limxmax = max(nodes(:,1));
limymin = min(nodes(:,2));
limymax = max(nodes(:,2));
%
% Plotting the Finite Element Mesh
% Initialization of the required matrices
X = zeros(nnel,nel) ;
Y = zeros(nnel,nel) ;
% Extract X,Y coordinates for the (iel)-th element
for iel = 1:nel
X(:,iel) = nodes(loops_nodes(iel,:),1) ;
Y(:,iel) = nodes(loops_nodes(iel,:),2) ;
end
patch(X,Y,'w');
axis([limxmin-0.01*abs(limxmin) limxmax+0.01*abs(limxmax) limymin-0.01*abs(limymin) limymax+0.01*abs(limymax)]);
axis equal;
axis off ;
% To display Node Numbers % Element Numbers
axpos = getpixelposition(handles.axes3); % position & dimension of the axes object
% Define button's weight and height
bweight = 60;
bheight = 20;
pos = [((axpos(1)+axpos(3))/2) (axpos(2)-1.5*bheight) bweight bheight]; % align the second button with the center of the axes obj limit
ShowNodes = uicontrol('style','toggle','string','Nodes',....
'position',[(pos(1)-2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
ShowEdges = uicontrol('style','toggle','string','Edges',....
'position',[pos(1) pos(2) pos(3) pos(4)],'background','white',...
'units','Normalized');
ShowElements = uicontrol('style','toggle','string','Elements',....
'position',[(pos(1)+2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
set(ShowNodes,'callback',...
{@SHOWNODES,ShowEdges,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowEdges,'callback',...
{@SHOWEDGES,ShowNodes,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowElements,'callback',....
{@SHOWELEMENTS,ShowNodes,ShowEdges,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
%-----------------------------------------------------------------
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in next.
function next_Callback(hObject, eventdata, handles)
% hObject handle to next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
NaND = 0; NaNN = 0;
if isfield(handles,'edgesDirichlet')
edgesDirichlet=handles.edgesDirichlet;
dataDir=handles.dataDir;
% Converting strings in data arrays to matrices
D = cellfun(@str2num,dataDir(:,2:end),'UniformOutput',0);
% Looking for NaN in D & N
NaND = cellfun(@any,cellfun(@isnan,D,'UniformOutput',0));
end
if isfield(handles,'edgesNeumann')
edgesNeumann=handles.edgesNeumann;
dataNeu=handles.dataNeu;
% Converting strings in data arrays to matrices
N = cellfun(@str2num,dataNeu(:,2:end),'UniformOutput',0);
% Looking for NaN in D & N
NaNN = cellfun(@any,cellfun(@isnan,N,'UniformOutput',0));
end
%%
% Checking the data
if any(all(NaND,2)) % if all Dirichlet conditions on an edge are NaN
errordlg('All Dirichlet boundary conditions are set to NaN at least for one boundary.','Invalid input','modal');
return;
end
if any(any(NaNN,2)) % if any Neumann conditions are NaN
errordlg('At least one Neumann boundary condition is set to NaN.','Invalid input','modal');
return;
end
%%
% saving the workspace
if ~exist('./StructRegBC2.mat','file')
dummy = 0;
save('StructRegBC2','dummy'); % if save file does not exist, it creates it
end
load('StructDef','DirName','FileName');
% if requested by the user, saves to file
if isfield(handles,'edgesDirichlet')
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'edgesDirichlet','dataDir');
end
save('StructRegBC2','-append','edgesDirichlet','dataDir');
end
if isfield(handles,'edgesNeumann')
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'edgesNeumann','dataNeu');
end
save('StructRegBC2','-append','edgesNeumann','dataNeu');
end
close(handles.figure1); % closing the GUI window
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
CheckStructReg;
% --- Executes on button press in assignForce.
function assignForce_Callback(hObject, eventdata, handles)
% hObject handle to assignForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
itemlist = get(handles.listboxNeu,'Value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
ForceDirection = get(handles.popupmenu_NTNeu,'Value');
for ii = 1:nitems
crtitem = itemlist(ii);
handles.dataNeu{crtitem,ForceDirection+1}=get(handles.editForce,'string');
end
guidata(hObject,handles);
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
% --- Executes on button press in assignDisp.
function assignDisp_Callback(hObject, eventdata, handles)
% hObject handle to assignDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
itemlist = get(handles.listboxDir,'Value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
DispDirection = get(handles.popupmenu_NTDir,'Value');
for ii = 1:nitems
crtitem = itemlist(ii);
handles.dataDir{crtitem,DispDirection+1}=get(handles.editDisp,'string');
end
guidata(hObject,handles);
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
% --- Executes on button press in resetNeumann.
function resetNeumann_Callback(hObject, eventdata, handles)
% hObject handle to resetNeumann (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=1:length(handles.edgesNeumann)
handles.dataNeu{i,2}='NaN';
handles.dataNeu{i,3}='NaN';
end
guidata(hObject,handles);
column2={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.845,0.10,0.13,0.44],...
'Data',handles.dataNeu,...
'ColumnName',column2,'RowName',[]);
% --- Executes on button press in resetDirichlet.
function resetDirichlet_Callback(hObject, eventdata, handles)
% hObject handle to resetDirichlet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=1:length(handles.edgesDirichlet)
handles.dataDir{i,2}='NaN';
handles.dataDir{i,3}='NaN';
end
guidata(hObject,handles);
column1={'Boundary ID','Normal','Tangential'};
uitable('units','Normalized','Position',[0.475,0.10,0.13,0.44],...
'Data',handles.dataDir,...
'ColumnName',column1,'RowName',[]);
% --- Executes on button press in previous.
function previous_Callback(hObject, eventdata, handles)
% hObject handle to previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(StructRegBC2);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
StructRegBC1;
% --- Executes on selection change in listboxNeu.
function listboxNeu_Callback(hObject, eventdata, handles)
% hObject handle to listboxNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listboxNeu contents as cell array
% contents{get(hObject,'Value')} returns selected item from listboxNeu
% --- Executes during object creation, after setting all properties.
function listboxNeu_CreateFcn(hObject, eventdata, handles)
% hObject handle to listboxNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editForce_Callback(hObject, eventdata, handles)
% hObject handle to editForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editForce as text
% str2double(get(hObject,'String')) returns contents of editForce as a double
[Flux, status] = str2num(get(hObject,'string'));
if any(isnan(Flux)) || ~status % if the input is something else than
% a vector of reals
set(hObject,'String','');
errordlg('Flux field must have real value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function editForce_CreateFcn(hObject, eventdata, handles)
% hObject handle to editForce (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in listboxDir.
function listboxDir_Callback(hObject, eventdata, handles)
% hObject handle to listboxDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listboxDir contents as cell array
% contents{get(hObject,'Value')} returns selected item from listboxDir
% --- Executes during object creation, after setting all properties.
function listboxDir_CreateFcn(hObject, eventdata, handles)
% hObject handle to listboxDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editDisp_Callback(hObject, eventdata, handles)
% hObject handle to editDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editDisp as text
% str2double(get(hObject,'String')) returns contents of editDisp as a double
[U, status] = str2num(get(hObject,'string'));
if ~status % if the input is something else than a vector of reals (or a NaN)
set(hObject,'String','');
errordlg('Sate field must have real value','Invalid input','modal');
uicontrol(hObject);
return;
end
if length(U)~=1 && any(isnan(U)) % if more than one term in input and one of them is NaN
set(hObject,'string','');
errordlg('A NaN Dirichlet boundary condition cannot be defined along with any other term','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function editDisp_CreateFcn(hObject, eventdata, handles)
% hObject handle to editDisp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_NTDir.
function popupmenu_NTDir_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_NTDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_NTDir contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_NTDir
% --- Executes during object creation, after setting all properties.
function popupmenu_NTDir_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_NTDir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_NTNeu.
function popupmenu_NTNeu_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_NTNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_NTNeu contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_NTNeu
% --- Executes during object creation, after setting all properties.
function popupmenu_NTNeu_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_NTNeu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in enlarge.
function enlarge_Callback(hObject, eventdata, handles)
% hObject handle to enlarge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
VisualizeReg;
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
StructRegBC1.m
|
.m
|
FreeHyTE-Structural-HTD-master/StructRegBC1.m
| 15,032 |
utf_8
|
2af0284af20ac072dd37e1d21fb117e7
|
function varargout = StructRegBC1(varargin)
% STRUCTREGBC1 MATLAB code for StructRegBC1.fig
% STRUCTREGBC1, by itself, creates a new STRUCTREGBC1 or raises the existing
% singleton*.
%
% H = STRUCTREGBC1 returns the handle to a new STRUCTREGBC1 or the handle to
% the existing singleton*.
%
% STRUCTREGBC1('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in STRUCTREGBC1.M with the given input arguments.
%
% STRUCTREGBC1('Property','Value',...) creates a new STRUCTREGBC1 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before StructRegBC1_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to StructRegBC1_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help StructRegBC1
% Last Modified by GUIDE v2.5 15-Jul-2016 10:27:07
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @StructRegBC1_OpeningFcn, ...
'gui_OutputFcn', @StructRegBC1_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Outputs from this function are returned to the command line.
function varargout = StructRegBC1_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes just before StructRegBC1 is made visible.
function StructRegBC1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StructRegBC1 (see VARARGIN)
% Choose default command line output for StructRegBC1
handles.output = hObject;
%load the array of edges
load('StructDef','edgesArray','L','B','Nx','Ny');
set(handles.listbox1,'string',edgesArray);
handles.DorN = get(handles.popupmenu1,'String');
handles.data = cell(length(edgesArray),2);
if exist('./StructRegBC1.mat','file') % reuse the previous data
load('StructRegBC1','data');
handles.data=data;
else
for i=1:length(edgesArray)
handles.data{i,1}=edgesArray(i);
handles.data{i,2}=handles.DorN{1}; % Dirichlet as predefined boundary type
end
end
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
%----Generate Mesh Code-----------------------------------------------
nel = Nx*Ny ; % Total Number of Elements in the Mesh
nnel = 4 ; % Number of nodes per Element
% Number of points on the Length and Width
npx = Nx+1 ;
npy = Ny+1 ;
nnode = npx*npy ; % Total Number of Nodes in the Mesh
% Number of edges on the Length and Width
nedgex = Nx*npy; % Number of Horizontal Edges
nedgey = Ny*npx; % Number of Vertical Edges
nedge = nedgex+nedgey; % Total Number of Edges in the Mesh
% Discretizing the Length and Width of the plate
nx = linspace(0,L,npx) ;
ny = linspace(0,B,npy) ;
[xx,yy] = meshgrid(nx,ny) ;
% To get the Nodal Connectivity Matrix
nodes = [xx(:) yy(:)] ;
NodeMap = 1:nnode ;
loops_nodes = zeros(nel,nnel) ;
% If elements along the X-axes and Y-axes are equal
if npx==npy
NodeMap = reshape(NodeMap,npx,npy);
loops_nodes(:,1) = reshape(NodeMap(1:npx-1,1:npy-1),nel,1);
loops_nodes(:,2) = reshape(NodeMap(2:npx,1:npy-1),nel,1);
loops_nodes(:,3) = reshape(NodeMap(2:npx,2:npy),nel,1);
loops_nodes(:,4) = reshape(NodeMap(1:npx-1,2:npy),nel,1);
% If the elements along the axes are different
else%if npx>npy
NodeMap = reshape(NodeMap,npy,npx);
loops_nodes(:,1) = reshape(NodeMap(1:npy-1,1:npx-1),nel,1);
loops_nodes(:,2) = reshape(NodeMap(2:npy,1:npx-1),nel,1);
loops_nodes(:,3) = reshape(NodeMap(2:npy,2:npx),nel,1);
loops_nodes(:,4) = reshape(NodeMap(1:npy-1,2:npx),nel,1);
end
% Obtaining the edge matrix
% Finding the nodes for each edge
edgesx=[reshape(NodeMap(1:npy-1,:),nedgey,1),...
reshape(NodeMap(2:npy,:),nedgey,1)];
edgesx(1:Ny,:)=fliplr(edgesx(1:Ny,:));
edgesy=[reshape(NodeMap(:,2:npx),nedgex,1),...
reshape(NodeMap(:,1:npx-1),nedgex,1)];
edgesy(1:npy:end,:)=fliplr(edgesy(1:npy:end,:));
edges_nodes = [edgesx ; edgesy];
%Finding the neighbouring elements for each edge
edges_loops = zeros(nedge,2);
for i=1:nedge
[row1, column1] = find(loops_nodes==edges_nodes(i,1));
[row2, column2] = find(loops_nodes==edges_nodes(i,2));
edges_loops(i,:)=intersect(row1,row2)';
if edges_loops(i,1)==edges_loops(i,2) % a single neighbour
edges_loops(i,2)=0; % right neighbour is set to zero
elseif edges_loops(i,1) > edges_loops(i,2) % left neighbour larger than right
edges_loops(i,:)=fliplr(edges_loops(i,:)); % flip them (left always
end % smallest in regular meshes)
end
%Finding the edges of each finite element
loops_edges = zeros(nel,4);
for i=1:nel
[row1, column1] = find(edges_loops==i);
loops_edges(i,:)=row1';
end
% storing all structures
handles.edgesArray = edgesArray;
handles.nodes = nodes;
handles.edges_nodes = edges_nodes;
handles.edges_loops = edges_loops;
handles.loops_nodes = loops_nodes;
handles.loops_edges = loops_edges;
% For drawing purposes
limxmin = min(nodes(:,1));
limxmax = max(nodes(:,1));
limymin = min(nodes(:,2));
limymax = max(nodes(:,2));
%
% Plotting the Finite Element Mesh
% Initialization of the required matrices
X = zeros(nnel,nel) ;
Y = zeros(nnel,nel) ;
% Extract X,Y coordinates for the (iel)-th element
for iel = 1:nel
X(:,iel) = nodes(loops_nodes(iel,:),1) ;
Y(:,iel) = nodes(loops_nodes(iel,:),2) ;
end
patch(X,Y,'w')
axis([limxmin-0.01*abs(limxmin) limxmax+0.01*abs(limxmax) limymin-0.01*abs(limymin) limymax+0.01*abs(limymax)]);
axis equal;
axis off ;
% To display Node Numbers % Element Numbers
axpos = getpixelposition(handles.axes2); % position & dimension of the axes object
% Define button's weight and height
bweight = 60;
bheight = 20;
pos = [((axpos(1)+axpos(3))/2) (axpos(2)-1.5*bheight) bweight bheight]; % align the second button with the center of the axes obj limit
ShowNodes = uicontrol('style','toggle','string','Nodes',....
'position',[(pos(1)-2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
ShowEdges = uicontrol('style','toggle','string','Edges',....
'position',[pos(1) pos(2) pos(3) pos(4)],'background','white',...
'units','Normalized');
ShowElements = uicontrol('style','toggle','string','Elements',....
'position',[(pos(1)+2*bweight) pos(2) pos(3) pos(4)],'background',...
'white','units','Normalized');
set(ShowNodes,'callback',...
{@SHOWNODES,ShowEdges,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowEdges,'callback',...
{@SHOWEDGES,ShowNodes,ShowElements,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
set(ShowElements,'callback',....
{@SHOWELEMENTS,ShowNodes,ShowEdges,nodes,edges_nodes,loops_nodes,X,Y,nnode,nedge,nel});
%-----------------------------------------------------------------
%setFigDockGroup(fh,'handles.axes1')
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in pushbutton_next.
function pushbutton_next_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data=handles.data;
DorN=handles.DorN;
edgesArray = handles.edgesArray;
nodes = handles.nodes;
edges_nodes = handles.edges_nodes;
edges_loops = handles.edges_loops;
loops_nodes = handles.loops_nodes;
loops_edges = handles.loops_edges;
% check if critical changes were made in the current GUI session
if exist('./StructRegBC1.mat','file')
save('ToDetectChanges','data'); % temporary file to detect critical changes
% Fields whose change triggers the change of the mesh
CriticalFields = {'data'};
% Checks the old StructRegBC1 and the new ToDetectChanges for changes in
% the critical fields. ChangesQ = 1 if there are changes, 0 otherwise
ChangesQ = any(~isfield(comp_struct(load('StructRegBC1.mat'),...
load('ToDetectChanges.mat')),CriticalFields));
% deleting the auxiliary file
delete('ToDetectChanges.mat');
else
ChangesQ = 1;
end
% saving the workspace
load('StructDef','DirName','FileName');
% if requested by the user, saves to file
if ~isempty(DirName)
save(fullfile(DirName,FileName),'-append',...
'data','DorN','nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
end
% saves the local data file
save('StructRegBC1','data','DorN','nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
% saves the data required by VisualizeReg to the local data file
save('Visualize',...
'nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
close(handles.figure1);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
if ChangesQ % if changes were detected
delete('StructRegBC2.mat');
end
StructRegBC2;
% --- Executes on button press in pushbutton_reset.
function pushbutton_reset_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load('StructDef','edgesArray');
handles.DorN = get(handles.popupmenu1,'String');
handles.data = cell(length(edgesArray),2);
for i=1:length(edgesArray)
handles.data{i,1}=edgesArray(i);
handles.data{i,2}=handles.DorN{1}; % Dirichlet as predefined boundary type
end
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
% --- Executes on button press in pushbutton_previous.
function pushbutton_previous_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(StructRegBC1);
% Trying to close Visualize if it was opened
try
close('Visualize');
catch
end
StructDef(2);
% --- Executes on button press in assign.
function assign_Callback(hObject, eventdata, handles)
% hObject handle to assign (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
itemlist = get(handles.listbox1,'value'); % list of selected items in the listbox
nitems = length(itemlist); % number of selected items in the listbox
if get(handles.popupmenu1,'value')==1 % if Dirichlet is selected
for ii = 1:nitems
crtitem = itemlist(ii);
handles.data{crtitem,2}=handles.DorN{1};
end
else % if Neumann is selected
for ii = 1:nitems
crtitem = itemlist(ii);
handles.data{crtitem,2}=handles.DorN{2};
end
end
guidata(hObject,handles);
column = {'Boundary ID','Boundary Type'};
uitable('units','Normalized','Position',[0.76, 0.17, 0.13, 0.35],'Data',...
handles.data,'ColumnName',column,'RowName',[]);
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in enlarge.
function enlarge_Callback(hObject, eventdata, handles)
% hObject handle to enlarge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Recovering the data created or set by the user in the current GUI
nodes = handles.nodes;
edges_nodes = handles.edges_nodes;
edges_loops = handles.edges_loops;
loops_nodes = handles.loops_nodes;
loops_edges = handles.loops_edges;
% saves the data required by VisualizeReg to the local data file
save('Visualize',...
'nodes','edges_nodes','edges_loops',...
'loops_nodes','loops_edges');
VisualizeReg;
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
StructDef.m
|
.m
|
FreeHyTE-Structural-HTD-master/StructDef.m
| 44,142 |
utf_8
|
6ce2378f399d3a8deac90865ac3b6d92
|
%% PREDEFINED FUNCTIONS
% No changes were made to the following functions, predefined by GUIDE
function varargout = StructDef(varargin)
% STRUCTDEF MATLAB code for StructDef.fig
% STRUCTDEF, by itself, creates a new STRUCTDEF or raises the existing
% singleton*.
%
% H = STRUCTDEF returns the handle to a new STRUCTDEF or the handle to
% the existing singleton*.
%
% STRUCTDEF('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in STRUCTDEF.M with the given input arguments.
%
% STRUCTDEF('Property','Value',...) creates a new STRUCTDEF or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before StructDef_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to StructDef_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help StructDef
% Last Modified by GUIDE v2.5 11-May-2016 10:58:08
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @StructDef_OpeningFcn, ...
'gui_OutputFcn', @StructDef_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% UIWAIT makes StructDef wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = StructDef_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%% OPENING FUNCTION
% * Executes just before StructDef is made visible;
% * Reads the previous data in the local |mat| file and fills in the
% fields.
function StructDef_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to StructDef (see VARARGIN)
%%
% If no varargin was defined, it is set to zero and saved to handles
if isempty(varargin)
handles.varargin = 0;
else
handles.varargin = varargin{1};
end
%%
% % Splash screen sequence
% if handles.varargin == 0
% timer = tic;
% ShowSplashForSecs = 1;
%
% s = SplashScreen( 'Splashscreen', 'Splash.png', ...
% 'ProgressBar', 'on', ...
% 'ProgressPosition', 5, ...
% 'ProgressRatio', 0.4 );
% s.addText( 520, 80, 'Structural HTD', 'FontSize', 35, 'Color', [0 0 0.6] );
% s.addText( 520, 120, 'v1.0', 'FontSize', 25, 'Color', [0.2 0.2 0.5] );
% s.addText( 365, 270, 'Loading...', 'FontSize', 20, 'Color', 'white' );
%
% ElapsedTime = toc(timer);
% if ElapsedTime < ShowSplashForSecs
% pause(ShowSplashForSecs - ElapsedTime);
% end
% delete(s);
% end
%%
% Setting warnings to off. These warnings are caused by missing files and
% variables before the local |mat| files are written for the first time and
% by the possibility that the problem is purely Neumann or Dirichlet. The
% warnings are re-activated after the successful execution, at the end of
% the |main.m| function.
warning('off','MATLAB:DELETE:FileNotFound');
warning('off','MATLAB:load:variableNotFound');
%%
% Creates the |handles| structure
% Choose default command line output for |StructDef|
handles.output = hObject;
%%
% Getting the current working folder (in R2012 may be different from the
% folder you started the app from!)
handles.WorkingFolder = pwd;
%%
% If there exists a local |mat| file, it loads its key elements to fill in
% the fields with data taken from the previous run.
if exist('./StructDef.mat','file')
load('StructDef','L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState');
%%
% In rare situations, no values are stored for L, B, Nx, Ny. If this is
% the case, it reads NaN and thus ChangesQ always results 1. To avoid
% this, when NaN is red, it is substituted by zero.
if isnan(L)
L=0; B=0; Nx=0; Ny=0;
end
%%
% Filling in the fields with the data from the previous iteration
set(handles.edit_DimX,'String',sprintf('%d',L));
set(handles.edit_DimY,'String',sprintf('%d',B));
set(handles.edit_NLoopX,'String',sprintf('%d',Nx));
set(handles.edit_NLoopY,'String',sprintf('%d',Ny));
set(handles.edit_OrderEdge,'String',sprintf('%d',EdgesOrder));
set(handles.edit_OrderLoop,'String',sprintf('%d',LoopsOrder));
set(handles.edit_NGP,'String',sprintf('%d',NumberGaussPoints));
set(handles.edit_Young,'String',sprintf('%g',Young));
set(handles.edit_Poisson,'String',sprintf('%g',Poisson));
set(handles.popupmenu_mesh,'Value',MeshOption);
set(handles.popupmenu_plane,'Value',PlaneState);
%%
% If |MeshOption = 2|, that is, the mesh generation is automatic, it
% makes no sense to edit the fields associated to the regular mesh
% generator. They become inactive.
if MeshOption == 1
set(handles.edit_DimX, 'enable', 'on');
set(handles.edit_DimY, 'enable', 'on');
set(handles.edit_NLoopX, 'enable', 'on');
set(handles.edit_NLoopY, 'enable', 'on');
else
set(handles.edit_DimX, 'enable', 'off');
set(handles.edit_DimY, 'enable', 'off');
set(handles.edit_NLoopX, 'enable', 'off');
set(handles.edit_NLoopY, 'enable', 'off');
end
end
%%
% Returns control to the user.
% Update handles structure
guidata(hObject, handles);
%% NEXT BUTTON
% * Executes on button press in |pushbutton_next|;
% * It recovers all data provided by the user in the GUI fields;
% * If the mesh is regular, it computes the |edgesArray| list (consisting of
% the exterior edges of the srtucture);
% * If the mesh is formed by triangular elements, it launches the |pdetool|
% to generate the mesh;
% * In either case, after the mesh generation is complete, it checks for
% relevant (i.e. mesh) changes as compared to the previous |mat| file. If
% such changes exist, it deletes the |mat| file corresponding to the next
% GUIs to force their definition from scratch. If no mesh changes were
% detected, the next GUI will load its previous version;
% * If the user asked for the model to be saved, it saves the information
% regarding this GUI in the specified file and folder.
function pushbutton_next_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Reading the information provided by the user in the GUI fields.
EdgesOrder = str2double(get(handles.edit_OrderEdge,'String'));
LoopsOrder = str2double(get(handles.edit_OrderLoop,'String'));
NumberGaussPoints = str2double(get(handles.edit_NGP,'String'));
MeshOption = get(handles.popupmenu_mesh,'Value');
Young = str2double(get(handles.edit_Young,'String'));
Poisson = str2double(get(handles.edit_Poisson,'String'));
PlaneState = get(handles.popupmenu_plane,'Value');
%%
% If the user asked for the model to be saved, it stores the path and the
% file name.
if isfield(handles,'DirName')
DirName = handles.DirName;
FileName = handles.FileName;
else
DirName = '';
FileName = '';
end
%%
% *Procedure for the regular rectangular mesh*
if MeshOption == 1
%%
% Reading mesh information
L = str2double(get(handles.edit_DimX,'String'));
B = str2double(get(handles.edit_DimY,'String'));
Nx = str2double(get(handles.edit_NLoopX,'String'));
Ny = str2double(get(handles.edit_NLoopY,'String'));
%%
% Computing the |edgesArray| list
L1 = linspace(1,Ny,Ny);
L2 = linspace((Nx*Ny)+1,((Nx*Ny)+1)+(Ny-1),Ny);
L3 = linspace(((Nx*Ny)+1)+Ny,((Nx*Ny)+1)+Ny+((Ny+1)*(Nx-1)),Nx);
L4 = linspace(((Nx*Ny)+1)+2*Ny,((Nx*Ny)+1)+Ny+((Ny+1)*(Nx-1))+Ny,Nx);
edgesArray = sort(cat(1,L1',L2',L3',L4'));
%%
% |p| and |t| variables are allocated dummy values to avoid errors
% related to the comparison between |mat| files corresponding to
% regular (rectangular) and triangular meshes.
p = 0; t = 0;
%%
% Check if critical changes were made in the current GUI session. Note
% that critical changes only refer to the mesh, not necessarily to the
% geometry of the structure.
if exist('./StructDef.mat','file')
save('ToDetectChanges','MeshOption','Nx','Ny','p','t'); % temporary file to detect critical changes
% Fields whose change triggers the change of the mesh
CriticalFields = {'MeshOption','Nx','Ny','p','t'};
% Checks the old |StructDef.m| and the new |ToDetectChanges| file
% for changes in the critical fields. ChangesQ = 1 if there are
% changes, 0 otherwise.
ChangesQ = any(~isfield(comp_struct(load('StructDef.mat'),...
load('ToDetectChanges.mat')),CriticalFields));
% deleting the auxiliary file
delete('ToDetectChanges.mat');
else
% If there is no |StructDef| file in the first place, it sets
% ChangesQ to 1.
ChangesQ = 1;
end
%%
% Saving the workspace to the local |mat| file. If requested by the
% user, the GUI information is also saved to the file specified by the
% user.
save('StructDef','L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','DirName','FileName','ChangesQ');
% If the folder where it looks for pre-load files is different from the
% current folder, it creates a copy of StructDef in the former
if ~strcmp(pwd,handles.WorkingFolder)
save(fullfile(handles.WorkingFolder,'StructDef'),'L','B','Nx','Ny',...
'EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','DirName','FileName','ChangesQ');
end
if ~isempty(DirName)
save(fullfile(DirName,FileName),...
'L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','ChangesQ');
end
%%
% Preparing to exit.
close(handles.figure1);
%%
% If there are relevant changes, it physically deletes the |mat| files
% associated to the following GUIs.
if ChangesQ
delete('StructRegBC1.mat','StructRegBC2.mat');
end
StructRegBC1;
%%
% *Procedure for the automatic triangular mesh*
else
%%
% Reading mesh information. This data is useless for the automatic mesh
% generation. It is only stored to fill in the corresponding fields in
% a future run.
L = str2double(get(handles.edit_DimX,'String'));
B = str2double(get(handles.edit_DimY,'String'));
Nx = str2double(get(handles.edit_NLoopX,'String'));
Ny = str2double(get(handles.edit_NLoopY,'String'));
%%
% |edgesArray| variable is allocated a dummy value to avoid errors
% related to the comparison between |mat| files corresponding to
% regular (rectangular) and triangular meshes.
edgesArray = 0;
%%
% Launching |pdetool| to define the mesh
pdewindow = pdeinit;
%%
% Stopping the execution until the |pdetool| window is closed
waitfor(pdewindow);
%%
% This is a basic check to confirm that the user saved the mesh
% information. A new mesh need not be created if the corresponding
% information already exist in |StructDef.mat|, so the program checks
% if a new mesh was defined or if |StructDef.mat| exists. Of course,
% the check fails if |StructDef.mat| exists, but does not contain
% relevant mesh information (the program exists with an error).
BaseVars = evalin('base','whos'); % collects variable info from base
% if the mesh variables are not found in base and an old definition
% does not exist in StructDef.mat
if (~ismember('p',[BaseVars(:).name]) || ~ismember('t',[BaseVars(:).name])) && ...
(~exist('./StructDef.mat','file'))
errordlg('No mesh information was exported or variable names were changed. Please press "Next" again and export the mesh info as p, e and t.','Invalid input','modal');
uicontrol(hObject);
return;
end
%%
% if the mesh variables are found in base, it loads them...
if ismember('p',[BaseVars(:).name]) && ismember('t',[BaseVars(:).name])
p = evalin('base','p');
t = evalin('base','t');
%%
% ... otherwise, it loads them from the StructDef.mat
else
load('StructDef','p','t');
end
%%
% Check if critical changes were made in the current GUI session. Note
% that critical changes only refer to the mesh, not necessarily to the
% geometry of the structure.
if exist('./StructDef.mat','file')
save('ToDetectChanges','MeshOption','Nx','Ny','p','t'); % temporary file to detect critical changes
% Fields whose change triggers the change of the mesh
CriticalFields = {'MeshOption','Nx','Ny','p','t'};
% Checks the old StructDef and the new ToDetectChanges for changes in
% the critical fields. ChangesQ = 1 if there are changes, 0 otherwise
ChangesQ = any(~isfield(comp_struct(load('StructDef.mat'),...
load('ToDetectChanges.mat')),CriticalFields));
% deleting the auxiliary file
delete('ToDetectChanges.mat');
else
% If there is no |StructDef| file in the first place, it sets
% ChangesQ to 1.
ChangesQ = 1;
end
%%
% Saving the workspace to the local |mat| file. If requested by the
% user, the GUI information is also saved to the file specified by the
% user.
save('StructDef','L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','DirName','FileName','ChangesQ');
% If the folder where it looks for pre-load files is different from the
% current folder, it creates a copy of StructDef in the former
if ~strcmp(pwd,handles.WorkingFolder)
save(fullfile(handles.WorkingFolder,'StructDef'),'L','B','Nx','Ny',...
'EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','DirName','FileName','ChangesQ');
end
% if requested by the user, saves to file
if ~isempty(DirName)
save(fullfile(DirName,FileName),...
'L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','ChangesQ');
end
%%
% Preparing to exit.
close(handles.figure1);
%%
% If there are relevant changes, it physically deletes the |mat| files
% associated to the following GUIs.
if ChangesQ
delete('StructTriBC1.mat','StructTriBC2.mat');
end
StructTriBC1;
end
%% RESET BUTTON
% * Executes on button press in |pushbutton_reset|;
% * It deletes all entries of the edit fields and resets the pop-up menus;
% * It also deletes the save information so that the save button action is
% reversed.
function pushbutton_reset_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Removing all field information
set(handles.edit_DimX,'String','');
set(handles.edit_DimY,'String','');
set(handles.edit_NLoopX,'String','');
set(handles.edit_NLoopY,'String','');
set(handles.edit_OrderEdge,'String','');
set(handles.edit_OrderLoop,'String','');
set(handles.edit_NGP,'String','');
set(handles.edit_Young,'String','');
set(handles.edit_Poisson,'String','');
%%
% Reseting |edit_Path|, the pop-up menus, and the properties of the mesh
% definition fields
set(handles.edit_Path,'String',...
'THE MODEL WILL NOT BE SAVED! Please press Save if you wish to save the model.',...
'BackgroundColor',[1.0 0.694 0.392]);
set(handles.popupmenu_plane,'Value',1);
set(handles.popupmenu_mesh,'Value',1);
set(handles.edit_DimX, 'enable', 'on');
set(handles.edit_DimY, 'enable', 'on');
set(handles.edit_NLoopX, 'enable', 'on');
set(handles.edit_NLoopY, 'enable', 'on');
handles.FileName = '';
handles.DirName = '';
%%
% Updating the |handles| structure
guidata(hObject, handles);
%% SAVE BUTTON
% * Executes on button press in |Save|;
% * Reads the path and filename provided by the user to save the model;
% * Generates the |FileName| and |DirName| members in the |handles|
% structure to store this information and to make it available to other
% functions.
function Save_Callback(hObject, eventdata, handles)
% hObject handle to Save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Reads the |handles| structure
handles=guidata(hObject);
%%
% Gets the path and filename to save the model
[FileName,DirName] = uiputfile('*.mat','Save as');
if FileName
%%
% Registers the path to the save file in the |edit_Path| box
set(handles.edit_Path,'string',fullfile(DirName,FileName),'BackgroundColor',[0 1 0]);
%%
% Generates the |FileName| and |DirName| members in the |handles|
% structure to store this information and to make it available to other
% functions.
handles.FileName = FileName;
handles.DirName = DirName;
%%
% If user cancelled the saving process and no save file was given
else
handles.FileName = '';
handles.DirName = '';
end
%%
% Updating the |handles| structure
guidata(hObject, handles);
%% LOAD BUTTON
% * Executes on button press in |Load|;
% * Loads all relevant variables in the file appointed by the user into the
% workspace. If the definition of the model was not completed in the
% previous session, some of the variables cannot be loaded (the
% corresponding warning is suppressed);
% * Stores the required variables into the StructDef |mat| file. This data
% must always be available;
% * Verifies if the data generated by the second and third GUIs are
% available. If they are, stores them into the local |mat| files, otherwise
% _deletes_ the |mat| files, to force their reinitialization;
% * Deletes the |FileName| and |DirName| variables to avoid overwriting of the
% loaded file;
% * Refreshes the interface, filling in the fields with the newly loaded
% values.
function Load_Callback(hObject, eventdata, handles)
% hObject handle to Load (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Reads the |handles| structure
handles=guidata(hObject);
%%
% Loads the |mat| file indicated by the user
[FileName,DirName] = uigetfile('*.mat','File to load');
%%
% Deletes the |FileName| and |DirName| variables to avoid overwriting;
handles.FileName = '';
handles.DirName = '';
%%
% Loading all relevant variables into the current workspace
load(fullfile(DirName,FileName),'L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState','p','t',...
'ChangesQ','edgesArray','data','dataDir','dataNeu','edgesDirichlet',...
'edgesNeumann');
%%
% Saving the local |StructDef.mat| file
save('StructDef','L','B','Nx','Ny','EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState','p','t',...
'edgesArray','ChangesQ');
% If the folder where it looks for pre-load files is different from the
% current folder, it creates a copy of StructDef in the former
if ~strcmp(pwd,handles.WorkingFolder)
save(fullfile(handles.WorkingFolder,'StructDef'),'L','B','Nx','Ny',...
'EdgesOrder','LoopsOrder',...
'NumberGaussPoints','MeshOption','Young','Poisson','PlaneState',...
'p','t','edgesArray','DirName','FileName','ChangesQ');
end
%%
% If 'p' exists (is not zero), updates 'p' and 't' in the base workspace
if any(any(p~=0))
assignin('base','p',p);
assignin('base','t',t);
end
%%
% Depending on the kind of mesh that is selected ...
if MeshOption == 1 % regular rectangular mesh
%%
% ... checks if the variable created by the second GUI exists and if it
% doesn't, it deletes the local |mat| file to force reinitialization...
if ~exist('data','var')
delete('StructRegBC1.mat');
%%
% ... or it stores (and overwrites) the |mat| file if the variable
% exists.
else
save('StructRegBC1','data');
end
%%
% ... checks if a variable created by the third GUI exists and if it
% doesn't, it deletes the local |mat| file to force reinitialization...
if ~exist('dataDir','var') && ~exist('dataNeu','var')
delete('StructRegBC2.mat');
%%
% ... or it stores (and overwrites) the |mat| file if the variable
% exists.
else
delete('StructRegBC2.mat');
dummy = 0;
save('StructRegBC2','dummy');
if exist('dataDir','var')
save('StructRegBC2','-append','edgesDirichlet','dataDir');
end
if exist('dataNeu','var')
save('StructRegBC2','-append','edgesNeumann','dataNeu');
end
end
%%
% Same operation for the irregular mesh file.
else
if ~exist('data','var')
delete('StructTriBC1.mat');
else
save('StructTriBC1','data');
end
if ~exist('dataDir','var') && ~exist('dataNeu','var')
delete('StructTriBC2.mat');
else
delete('StructTriBC2.mat');
dummy = 0;
save('StructTriBC2','dummy');
if exist('dataDir','var')
save('StructTriBC2','-append','edgesDirichlet','dataDir');
end
if exist('dataNeu','var')
save('StructTriBC2','-append','edgesNeumann','dataNeu');
end
end
end
%%
% Refreshes the interface, writing the loaded values into its fields...
set(handles.edit_DimX,'String',sprintf('%d',L));
set(handles.edit_DimY,'String',sprintf('%d',B));
set(handles.edit_NLoopX,'String',sprintf('%d',Nx));
set(handles.edit_NLoopY,'String',sprintf('%d',Ny));
set(handles.edit_OrderEdge,'String',sprintf('%d',EdgesOrder));
set(handles.edit_OrderLoop,'String',sprintf('%d',LoopsOrder));
set(handles.edit_NGP,'String',sprintf('%d',NumberGaussPoints));
set(handles.edit_Young,'String',sprintf('%g',Young));
set(handles.edit_Poisson,'String',sprintf('%g',Poisson));
set(handles.popupmenu_mesh,'Value',MeshOption);
set(handles.popupmenu_plane,'Value',PlaneState);
set(handles.edit_Path,'string',...
'THE MODEL WILL NOT BE SAVED! Please press Save if you wish to save the model.',...
'BackgroundColor',[1.0 0.694 0.392]);
%%
% ... and activates or inactivates the regular mesh fields according to the
% type of mesh in the loaded model.
if MeshOption == 1
set(handles.edit_DimX, 'enable', 'on');
set(handles.edit_DimY, 'enable', 'on');
set(handles.edit_NLoopX, 'enable', 'on');
set(handles.edit_NLoopY, 'enable', 'on');
else
set(handles.edit_DimX, 'enable', 'off');
set(handles.edit_DimY, 'enable', 'off');
set(handles.edit_NLoopX, 'enable', 'off');
set(handles.edit_NLoopY, 'enable', 'off');
end
%%
% Updates the |handles| structure
guidata(hObject, handles);
%% CLEAR BUTTON
% * Executes on button press in |Clear|;
% * Deletes the path and name of the save file and reinitializes the
% |edit_Path| field.
function Clear_Callback(hObject, eventdata, handles)
% hObject handle to Clear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%
% Reads the |handles| structure
handles=guidata(hObject);
%%
% Deletes the |FileName| and |DirName| variables
handles.FileName = '';
handles.DirName = '';
set(handles.edit_Path,'string',...
'THE MODEL WILL NOT BE SAVED! Please press Save if you wish to save the model.',...
'BackgroundColor',[1.0 0.694 0.392]);
%%
% Updates the |handles| structure
guidata(hObject, handles);
%% POP-UP MENUS
% *Mesh pop-up menu*
% * Executes on selection change in |popupmenu_mesh|.
% * Activates/deactivates the regular mesh definition fields according to
% the type of mesh that the user chooses.
function popupmenu_mesh_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_mesh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_mesh contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_mesh
if get(handles.popupmenu_mesh,'Value') == 1
set(handles.edit_DimX, 'enable', 'on');
set(handles.edit_DimY, 'enable', 'on');
set(handles.edit_NLoopX, 'enable', 'on');
set(handles.edit_NLoopY, 'enable', 'on');
else
set(handles.edit_DimX, 'enable', 'off');
set(handles.edit_DimY, 'enable', 'off');
set(handles.edit_NLoopX, 'enable', 'off');
set(handles.edit_NLoopY, 'enable', 'off');
end
% --- Executes during object creation, after setting all properties.
function popupmenu_mesh_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_mesh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%%
% *Plane pop-up menu*
% * Executes on selection change in popupmenu_plane;
% * Values 1 and 2 correspond to plane stress and plane strain,
% respectively.
function popupmenu_plane_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_plane (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_plane contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_plane
% --- Executes during object creation, after setting all properties.
function popupmenu_plane_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_plane (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%% EDIT FIELDS
% Field box editing functions. Most Callbacks check for the validity of the
% data.
function edit_DimX_Callback(hObject, eventdata, handles)
% hObject handle to edit_DimX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_DimX as text
% str2double(get(hObject,'String')) returns contents of edit_DimX as a double
L = str2double(get(hObject,'String'));
if isnan(L) || ~isreal(L) || isequal(L,0) || L < 0
set(hObject,'String','');
errordlg('You must enter a real positive value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_DimX_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_DimX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_DimY_Callback(hObject, eventdata, handles)
% hObject handle to edit_DimY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_DimY as text
% str2double(get(hObject,'String')) returns contents of edit_DimY as a double
B = str2double(get(hObject,'String'));
if isnan(B) || ~isreal(B) || isequal(B,0) || B < 0
set(hObject,'String','');
errordlg('You must enter a real positive value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_DimY_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_DimY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_NLoopX_Callback(hObject, eventdata, handles)
% hObject handle to edit_NLoopX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_NLoopX as text
% str2double(get(hObject,'String')) returns contents of edit_NLoopX as a double
Nx = str2double(get(hObject,'String'));
if isnan(Nx) || ~isreal(Nx) || logical(abs(round(Nx)-Nx)<eps)==0 || isequal(Nx,0) || Nx < 0
set(hObject,'String','');
errordlg('You must enter a positive integer value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_NLoopX_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_NLoopX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_NLoopY_Callback(hObject, eventdata, handles)
% hObject handle to edit_NLoopY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_NLoopY as text
% str2double(get(hObject,'String')) returns contents of edit_NLoopY as a double
Ny = str2double(get(hObject,'String'));
if isnan(Ny) || ~isreal(Ny) || logical(abs(round(Ny)-Ny)<eps)==0 || isequal(Ny,0) || Ny < 0
set(hObject,'String','');
errordlg('You must enter a positive integer value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_NLoopY_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_NLoopY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_OrderEdge_Callback(hObject, eventdata, handles)
% hObject handle to edit_OrderEdge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_OrderEdge as text
% str2double(get(hObject,'String')) returns contents of edit_OrderEdge as a double
EdgesOrder = str2double(get(handles.edit_OrderEdge,'String'));
if isnan(EdgesOrder) || ~isreal(EdgesOrder) ||...
logical(abs(round(EdgesOrder)-EdgesOrder)<eps)==0 || EdgesOrder < 0
set(hObject,'String','');
errordlg('You must enter either 0 or a natural number','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_OrderEdge_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_OrderEdge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_OrderLoop_Callback(hObject, eventdata, handles)
% hObject handle to edit_OrderLoop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_OrderLoop as text
% str2double(get(hObject,'String')) returns contents of edit_OrderLoop as a double
LoopsOrderC = str2double(get(handles.edit_OrderLoop,'String'));
if isnan(LoopsOrderC) || ~isreal(LoopsOrderC) || ...
logical(abs(round(LoopsOrderC)-LoopsOrderC)<eps)==0 || LoopsOrderC < 0
set(hObject,'String','');
errordlg('You must enter either 0 or a natural number','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_OrderLoop_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_OrderLoop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_NGP_Callback(hObject, eventdata, handles)
% hObject handle to edit_NGP (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_NGP as text
% str2double(get(hObject,'String')) returns contents of edit_NGP as a double
NumberGaussPoints = str2double(get(handles.edit_NGP,'String'));
if isnan(NumberGaussPoints) || ~isreal(NumberGaussPoints) || ...
logical(abs(round(NumberGaussPoints)-NumberGaussPoints)<eps)==0 ||...
isequal(NumberGaussPoints,0) || NumberGaussPoints < 0
set(hObject,'String','');
errordlg('You must enter a positive integer value','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_NGP_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_NGP (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_Poisson_Callback(hObject, eventdata, handles)
% hObject handle to edit_Poisson (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_Poisson as text
% str2double(get(hObject,'String')) returns contents of edit_Poisson as a double
Poisson = str2double(get(handles.edit_Poisson,'String'));
if isnan(Poisson) || ~isreal(Poisson) || Poisson <= 0 || Poisson >= 0.5
set(hObject,'String','');
errordlg('You must enter a positive real number smaller than 0.5','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_Poisson_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_Poisson (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_Young_Callback(hObject, eventdata, handles)
% hObject handle to edit_Young (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_Young as text
% str2double(get(hObject,'String')) returns contents of edit_Young as a double
Young = str2double(get(handles.edit_Young,'String'));
if isnan(Young) || ~isreal(Young) || Young <= 0
set(hObject,'String','');
errordlg('You must enter a positive real number','Invalid input','modal');
uicontrol(hObject);
return;
end
% --- Executes during object creation, after setting all properties.
function edit_Young_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_Young (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_Path_Callback(hObject, eventdata, handles)
% hObject handle to edit_Path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_Path as text
% str2double(get(hObject,'String')) returns contents of edit_Path as a double
% --- Executes during object creation, after setting all properties.
function edit_Path_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_Path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%% TEXT FIELDS
% Text fields' editing functions. The respective |ButtonDownFcn| defines
% the help of that field, accessed through right clicking.
% --- Executes during object creation, after setting all properties.
function text_DimX_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_DimX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_DimY_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_DimY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_NLoopX_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_NLoopX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_NLoopY_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_NLoopY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_OrderEdge_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_OrderEdge (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_OrderLoop_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_OrderLoop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_NGP_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_NGP (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function text_SaveLoad_CreateFcn(hObject, eventdata, handles)
% hObject handle to text_SaveLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
VisualizeReg.m
|
.m
|
FreeHyTE-Structural-HTD-master/VisualizeReg.m
| 4,483 |
utf_8
|
ba24a15c04807eb97012e3cb337df1ca
|
function varargout = VisualizeReg(varargin)
% VISUALIZEREG MATLAB code for VisualizeReg.fig
% VISUALIZEREG, by itself, creates a new VISUALIZEREG or raises the existing
% singleton*.
%
% H = VISUALIZEREG returns the handle to a new VISUALIZEREG or the handle to
% the existing singleton*.
%
% VISUALIZEREG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VISUALIZEREG.M with the given input arguments.
%
% VISUALIZEREG('Property','Value',...) creates a new VISUALIZEREG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before VisualizeReg_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to VisualizeReg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help VisualizeReg
% Last Modified by GUIDE v2.5 15-Jul-2016 10:18:01
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @VisualizeReg_OpeningFcn, ...
'gui_OutputFcn', @VisualizeReg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before VisualizeReg is made visible.
function VisualizeReg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to VisualizeReg (see VARARGIN)
% Choose default command line output for VisualizeReg
handles.output = hObject;
% Create data structures
load('Visualize','nodes','edges_nodes','edges_loops','loops_nodes',...
'loops_edges');
% Definitions of the data structures
Nodes = nodes;
Edges=struct('nini',edges_nodes(:,1),'nfin',edges_nodes(:,2),...
'parametric',createLine(Nodes(edges_nodes(:,1),:),...
Nodes(edges_nodes(:,2),:)),...
'lleft',edges_loops(:,1),'lright',edges_loops(:,2),...
'type',char(zeros(length(edges_nodes(:,1)),1)),'order',...
zeros(length(edges_nodes(:,1)),1));
Loops=struct('nodes',loops_nodes,'edges',loops_edges,...
'center',zeros(length(loops_nodes(:,1)),2),...
'area',zeros(length(loops_nodes(:,1)),1));
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
axis off ;
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes VisualizeReg wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = VisualizeReg_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
CheckStructTri.m
|
.m
|
FreeHyTE-Structural-HTD-master/CheckStructTri.m
| 10,745 |
utf_8
|
f372bc2a5776918ec9f99fd997a70faf
|
function varargout = CheckStructTri(varargin)
% CHECKSTRUCTTRI MATLAB code for CheckStructTri.fig
% CHECKSTRUCTTRI, by itself, creates a new CHECKSTRUCTTRI or raises the existing
% singleton*.
%
% H = CHECKSTRUCTTRI returns the handle to a new CHECKSTRUCTTRI or the handle to
% the existing singleton*.
%
% CHECKSTRUCTTRI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHECKSTRUCTTRI.M with the given input arguments.
%
% CHECKSTRUCTTRI('Property','Value',...) creates a new CHECKSTRUCTTRI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before CheckStructTri_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to CheckStructTri_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help CheckStructTri
% Last Modified by GUIDE v2.5 13-Jul-2016 22:00:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @CheckStructTri_OpeningFcn, ...
'gui_OutputFcn', @CheckStructTri_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before CheckStructTri is made visible.
function CheckStructTri_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to CheckStructTri (see VARARGIN)
% Choose default command line output for CheckStructTri
handles.output = hObject;
% Launch input processor
[~,Nodes,Edges,Loops,~,~] = InputProcTri;
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
axis off ;
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes CheckStructTri wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = CheckStructTri_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in run.
function run_Callback(hObject, eventdata, handles)
% hObject handle to run (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(CheckStructTri); % closing the GUI window
pause(0.05); % to actually close it
MainTri;
% --- Executes on button press in previous.
function previous_Callback(hObject, eventdata, handles)
% hObject handle to previous (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(CheckStructTri);
StructTriBC2;
% --- Executes on button press in update.
function update_Callback(hObject, eventdata, handles)
% hObject handle to update (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% clearing the display
cla(gcf) ;
% getting the ViewOption
ViewOption = get(handles.view,'Value');
% Launch input processor
[~,Nodes,Edges,Loops,BConds,~] = InputProcTri;
% prepare to plot
xmesh = [Nodes(Edges.nini(:),1) Nodes(Edges.nfin(:),1)];
ymesh = [Nodes(Edges.nini(:),2) Nodes(Edges.nfin(:),2)];
% get delta to scale the insertion points of the text
delta = sqrt(max(max(xmesh))^2+max(max(ymesh))^2);
if ViewOption==1 % just the mesh
for ii=1:length(Edges.type)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
end
daspect([1 1 1]);
% Plotting the edges
for i = 1:length(Edges.type)
EX = [Nodes(Edges.nini(i),1); Nodes(Edges.nfin(i),1)];
EY = [Nodes(Edges.nini(i),2); Nodes(Edges.nfin(i),2)];
pos = [sum(EX)/2+0.0*delta,sum(EY)/2+0.0*delta] ;
text(pos(1),pos(2),int2str(i),'fontsize',8, ...
'BackgroundColor','w','fontweight','bold','color','r');
end
% Plotting the elements
for i = 1:length(Loops.area)
C = polygonCentroid(Nodes(Loops.nodes(i,:),:));
pos = C ;
text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold',...
'BackgroundColor','w','color','b');
end
elseif ViewOption==2 % just the BC, normal
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,1}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,1}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
else % just the BC, tangential
for ii=1:length(Edges.type)
if strcmp(Edges.type(ii),'D') && ~Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','k');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Dirichlet{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
text(posend(1),posend(2),num2str(BConds.Dirichlet{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','k');
elseif strcmp(Edges.type(ii),'D') && Edges.lright(ii)
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',1,'color','b');
else
line(xmesh(ii,:),ymesh(ii,:),'LineWidth',3,'color','r');
diffx = xmesh(ii,2)-xmesh(ii,1);
diffy = ymesh(ii,2)-ymesh(ii,1);
posini = Nodes(Edges.nini(ii),:)+ [0.08*diffx 0.08*diffy];
posend = Nodes(Edges.nfin(ii),:)- [0.08*diffx 0.08*diffy];
text(posini(1),posini(2),num2str(BConds.Neumann{ii,2}(1)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
text(posend(1),posend(2),num2str(BConds.Neumann{ii,2}(end)),...
'HorizontalAlignment','center',...
'BackgroundColor','w','fontsize',7,'color','r');
end
end
end
% --- Executes on selection change in view.
function view_Callback(hObject, eventdata, handles)
% hObject handle to view (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns view contents as cell array
% contents{get(hObject,'Value')} returns selected item from view
% --- Executes during object creation, after setting all properties.
function view_CreateFcn(hObject, eventdata, handles)
% hObject handle to view (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
idmoldovan/FreeHyTE-Structural-HTD-master
|
SplashScreen.m
|
.m
|
FreeHyTE-Structural-HTD-master/SplashScreen.m
| 19,426 |
utf_8
|
49549fadd81d545c2d453aec533fd126
|
classdef SplashScreen < hgsetget
%SplashScreen create a splashscreen
%
% s = SplashScreen(title,imagefile) creates a splashscreen using
% the specified image. The title is the name of the window as shown
% in the task-bar. Use "delete(s)" to remove it. Note that images
% must be in PNG, GIF or JPEG format. Use the addText method to add
% text to your splashscreen
%
% Examples:
% s = SplashScreen( 'Splashscreen', 'example_splash.png', ...
% 'ProgressBar', 'on', ...
% 'ProgressPosition', 5, ...
% 'ProgressRatio', 0.4 )
% s.addText( 30, 50, 'My Cool App', 'FontSize', 30, 'Color', [0 0 0.6] )
% s.addText( 30, 80, 'v1.0', 'FontSize', 20, 'Color', [0.2 0.2 0.5] )
% s.addText( 300, 270, 'Loading...', 'FontSize', 20, 'Color', 'white' )
% delete( s )
%
% See also: SplashScreen/addText
% Copyright 2008-2011 The MathWorks, Inc.
% Revision: 1.1
%% Public properties
properties
Visible = 'on' % Is the splash-screen visible on-screen [on|off]
Border = 'on' % Is the edge pixel darkened to form a border [on|off]
ProgressBar = 'off' % Is the progress bar visible [on|off]
ProgressPosition = 10% Height (in pixels) above the bottom of the window for the progress bar
ProgressRatio = 0 % The ratio shown on the progress bar (in range 0 to 1)
Tag = '' % User tag for this object
end % Public properties
%% Read-only properties
properties ( GetAccess = public, SetAccess = private )
Width = 0 % Width of the window
Height = 0 % Height of the window
end % Read-only properties
%% Private properties
properties ( Access = private )
Icon = []
BufferedImage = []
OriginalImage = []
Label = []
Frame = []
end % Read-only properties
%% Public methods
methods
function obj = SplashScreen( title, imagename, varargin )
% Construct a new splash-screen object
if nargin<2
error('SplashScreen:BadSyntax', 'Syntax error. You must supply both a window title and imagename.' );
end
% First try to load the image as an icon
fullname = iMakeFullName( imagename );
if exist(fullname,'file')~=2
% Try on the path
fullname = which( imagename );
if isempty( fullname )
error('SplashScreen:BadFile', 'Image ''%s'' could not be found.', imagename );
end
end
% Create the interface
obj.createInterfaceComponents( title, fullname );
obj.updateAll();
% Set any user-specified properties
for ii=1:2:nargin-2
param = varargin{ii};
value = varargin{ii+1};
obj.(param) = value;
end
% If the user hasn't overridden the default, finish by putting
% it onscreen
if strcmpi(obj.Visible,'on')
obj.Frame.setVisible(true);
end
end % SplashScreen
function addText( obj, x, y, text, varargin )
%addText Add some text to the background image
%
% S.addText(X,Y,STR,...) adds some text to the splashscreen S
% showing the string STR. The text is located at pixel
% coordinates [X,Y]. Additional options can be set using
% parameter value pairs and include:
% 'Color' the font color (e.g. 'r' or [r g b])
% 'FontSize' the text size (in points)
% 'FontName' the name of the font to sue (default 'Arial')
% 'FontAngle' 'normal' or 'italic'
% 'FontWeight' 'normal' or 'bold'
% 'Shadow' 'on' or 'off' (default 'on')
%
% Examples:
% s = SplashScreen( 'Splashscreen', 'example_splash.png' );
% s.addText( 30, 50, 'My Cool App', 'FontSize', 30, 'Color', [0 0 0.6] )
%
% See also: SplashScreen
% We write into the original image so that the text is
% permanent
gfx = obj.OriginalImage.getGraphics();
% Set the font size etc
[font,color,shadow] = parseFontArguments( varargin{:} );
gfx.setFont( font );
% Switch on anti-aliasing
gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON );
% Draw the text semi-transparent as a shadow
if shadow
gfx.setPaint( java.awt.Color.black );
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.3 );
gfx.setComposite( ac );
gfx.drawString( text, x+1, y+2 );
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.5 );
gfx.setComposite( ac );
gfx.drawString( text, x, y+1 );
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.7 );
gfx.setComposite( ac );
gfx.drawString( text, x+1, y+1 );
end
% Now the text itself
gfx.setPaint( color );
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 1.0 );
gfx.setComposite( ac );
gfx.drawString( text, x, y );
% Now update everything else
obj.updateAll();
end % addText
function delete(obj)
%delete destroy this object and close all graphical components
if ~isempty(obj.Frame)
dispose(obj.Frame);
end
end % delete
end % Public methods
%% Data-access methods
methods
function val = get.Width(obj)
if isempty(obj.Icon)
val = 0;
else
val = obj.Icon.getIconWidth();
end
end % get.Width
function val = get.Height(obj)
if isempty(obj.Icon)
val = 0;
else
val = obj.Icon.getIconHeight();
end
end % get.Height
function set.Visible(obj,val)
if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) )
error( 'SplashScreen:BadValue', 'Property ''ProgressBar'' must be ''on'' or ''off''' );
end
obj.Visible = lower( val );
obj.Frame.setVisible( strcmpi(val,'ON') ); %#ok<MCSUP>
end % set.Visible
function set.Border(obj,val)
if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) )
error( 'SplashScreen:BadValue', 'Property ''Border'' must be ''on'' or ''off''' );
end
obj.Border = val;
obj.updateAll();
end % set.Border
function set.ProgressBar(obj,val)
if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) )
error( 'SplashScreen:BadValue', 'Property ''ProgressBar'' must be ''on'' or ''off''' );
end
obj.ProgressBar = val;
obj.updateProgressBar();
end % set.ProgressBar
function set.ProgressRatio(obj,val)
if ~isnumeric( val ) || ~isscalar( val ) || val<0 || val > 1
error( 'SplashScreen:BadValue', 'Property ''ProgressRatio'' must be a scalar between 0 and 1' );
end
obj.ProgressRatio = val;
obj.updateProgressBar();
end % set.ProgressRatio
function set.ProgressPosition(obj,val)
if ~isnumeric( val ) || ~isscalar( val ) || val<1 || val > obj.Height %#ok<MCSUP>
error( 'SplashScreen:BadValue', 'Property ''ProgressPosition'' must be a vertical position inside the window' );
end
obj.ProgressPosition = val;
obj.updateAll();
end % set.ProgressPosition
function set.Tag(obj,val)
if ~ischar( val )
error( 'SplashScreen:BadValue', 'Property ''Tag'' must be a character array' );
end
obj.Tag = val;
end % set.Tag
end % Data-access methods
%% Private methods
methods ( Access = private )
function createInterfaceComponents( obj, title, imageFile )
import javax.swing.*;
% Load the image
jImFile = java.io.File( imageFile );
try
obj.OriginalImage = javax.imageio.ImageIO.read( jImFile );
catch err
error('SplashScreen:BadFile', 'Image ''%s'' could not be loaded.', imageFile );
end
% Read it again into the copy we'll draw on
obj.BufferedImage = javax.imageio.ImageIO.read( jImFile );
% Create the icon
obj.Icon = ImageIcon( obj.BufferedImage );
% Create the frame and fill it with the image
obj.Frame = JFrame( title );
obj.Frame.setUndecorated( true );
obj.Label = JLabel( obj.Icon );
p = obj.Frame.getContentPane();
p.add( obj.Label );
% Resize and reposition the window
obj.Frame.setSize( obj.Icon.getIconWidth(), obj.Icon.getIconHeight() );
pos = get(0,'MonitorPositions');
x0 = pos(1,1) + (pos(1,3)-obj.Icon.getIconWidth())/2;
y0 = pos(1,2) + (pos(1,4)-obj.Icon.getIconHeight())/2;
obj.Frame.setLocation( x0, y0 );
end % createInterfaceComponents
function updateAll( obj )
% Update the entire image
% Copy in the original
w = obj.Frame.getWidth();
h = obj.Frame.getHeight();
gfx = obj.BufferedImage.getGraphics();
gfx.drawImage( obj.OriginalImage, 0, 0, w, h, 0, 0, w, h, [] );
% Maybe draw a border
if strcmpi( obj.Border, 'on' )
% Switch on anti-aliasing
gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON );
% Draw a semi-transparent rectangle for the background
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.8 );
gfx.setComposite( ac );
gfx.setPaint( java.awt.Color.black );
gfx.drawRect( 0, 0, w-1, h-1 );
end
obj.updateProgressBar();
end % updateAll
function updateProgressBar( obj )
% Update the progressbar and other bits
% First paint over the progressbar area with the original image
gfx = obj.BufferedImage.getGraphics();
border = 10;
size = 6;
w = obj.Frame.getWidth();
h = obj.Frame.getHeight();
py = obj.ProgressPosition;
x1 = 1;
y1 = h-py-size-1;
x2 = w-2;
y2 = h-py;
gfx.drawImage( obj.OriginalImage, x1, y1, x2, y2, x1, y1, x2, y2, [] );
if strcmpi( obj.ProgressBar, 'on' )
% Draw the progress bar over the image
% Switch on anti-aliasing
gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON );
% Draw a semi-transparent rectangle for the background
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.25 );
gfx.setComposite( ac );
gfx.setPaint( java.awt.Color.black );
gfx.fillRoundRect( border, h-py-size, w-2*border, size, size, size );
% Now draw the foreground bit
progWidth = (w-2*border-2) * obj.ProgressRatio;
ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.5 );
gfx.setComposite( ac );
gfx.setPaint( java.awt.Color.white );
gfx.fillRoundRect( border+1, h-py-size+1, progWidth, size-2, size, size );
end
% Update the on-screen image
obj.Frame.repaint();
end % updateProgressBar
end % Private methods
end % classdef
%-------------------------------------------------------------------------%
function filename = iMakeFullName( filename )
% Absolute paths start with one of:
% 'X:' (Windows)
% '\\' (UNC)
% '/' (Unix/Linux/Mac)
if ~strcmp(filename(2),':') ...
&& ~strcmp(filename(1:2),'\\') ...
&& ~strcmpi(filename(1),'/')
% Relative path, so add current working directory
filename = fullfile( pwd(), filename );
end
end % iMakeFullName
function [font,color,shadow] = parseFontArguments( varargin )
% Create a java font object based on some optional inputs
fontName = 'Arial';
fontSize = 12;
fontWeight = java.awt.Font.PLAIN;
fontAngle = 0;
color = java.awt.Color.red;
shadow = true;
if nargin
params = varargin(1:2:end);
values = varargin(2:2:end);
if numel( params ) ~= numel( values )
error( 'UIExtras:SplashScreen:BadSyntax', 'Optional arguments must be supplied as parameter-value pairs.' );
end
for ii=1:numel( params )
switch upper( params{ii} )
case 'FONTSIZE'
fontSize = values{ii};
case 'FONTNAME'
fontName = values{ii};
case 'FONTWEIGHT'
switch upper( values{ii} )
case 'NORMAL'
fontWeight = java.awt.Font.PLAIN;
case 'BOLD'
fontWeight = java.awt.Font.PLAIN;
otherwise
error( 'UIExtras:SplashScreen:BadParameterValue', 'Unsupported FontWeight: %s.', values{ii} );
end
case 'FONTANGLE'
switch upper( values{ii} )
case 'NORMAL'
fontAngle = 0;
case 'ITALIC'
fontAngle = java.awt.Font.ITALIC;
otherwise
error( 'UIExtras:SplashScreen:BadParameterValue', 'Unsupported FontAngle: %s.', values{ii} );
end
case 'COLOR'
rgb = iInterpretColor( values{ii} );
color = java.awt.Color( rgb(1), rgb(2), rgb(3) );
case 'SHADOW'
if ~ischar( values{ii} ) || ~ismember( upper( values{ii} ), {'ON','OFF'} )
error( 'UIExtras:SplashScreen:BadParameter', 'Option ''Shadow'' must be ''on'' or ''off''.' );
end
shadow = strcmpi( values{ii}, 'on' );
otherwise
error( 'UIExtras:SplashScreen:BadParameter', 'Unsupported optional parameter: %s.', params{ii} );
end
end
end
font = java.awt.Font( fontName, fontWeight+fontAngle, fontSize );
end % parseFontArguments
function col = iInterpretColor(str)
%interpretColor Interpret a color as an RGB triple
%
% rgb = uiextras.interpretColor(col) interprets the input color COL and
% returns the equivalent RGB triple. COL can be one of:
% * RGB triple of floating point numbers in the range 0 to 1
% * RGB triple of UINT8 numbers in the range 0 to 255
% * single character: 'r','g','b','m','y','c','k','w'
% * string: one of 'red','green','blue','magenta','yellow','cyan','black'
% 'white'
% * HTML-style string (e.g. '#FF23E0')
%
% Examples:
% >> uiextras.interpretColor( 'r' )
% ans =
% 1 0 0
% >> uiextras.interpretColor( 'cyan' )
% ans =
% 0 1 1
% >> uiextras.interpretColor( '#FF23E0' )
% ans =
% 1.0000 0.1373 0.8784
%
% See also: ColorSpec
% Copyright 2005-2010 The MathWorks Ltd.
% $Revision: 327 $
% $Date: 2010-08-26 09:53:11 +0100 (Thu, 26 Aug 2010) $
if ischar( str )
str = strtrim(str);
str = dequote(str);
if str(1)=='#'
% HTML-style string
if numel(str)==4
col = [hex2dec( str(2) ), hex2dec( str(3) ), hex2dec( str(4) )]/15;
elseif numel(str)==7
col = [hex2dec( str(2:3) ), hex2dec( str(4:5) ), hex2dec( str(6:7) )]/255;
else
error( 'UIExtras:interpretColor:BadColor', 'Invalid HTML color %s', str );
end
elseif all( ismember( str, '1234567890.,; []' ) )
% Try the '[0 0 1]' thing first
col = str2num( str ); %#ok<ST2NM>
if numel(col) == 3
% Conversion worked, so just check for silly values
col(col<0) = 0;
col(col>1) = 1;
end
else
% that didn't work, so try the name
switch upper(str)
case {'R','RED'}
col = [1 0 0];
case {'G','GREEN'}
col = [0 1 0];
case {'B','BLUE'}
col = [0 0 1];
case {'C','CYAN'}
col = [0 1 1];
case {'Y','YELLOW'}
col = [1 1 0];
case {'M','MAGENTA'}
col = [1 0 1];
case {'K','BLACK'}
col = [0 0 0];
case {'W','WHITE'}
col = [1 1 1];
case {'N','NONE'}
col = [nan nan nan];
otherwise
% Failed
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
end
elseif isfloat(str) || isdouble(str)
% Floating point, so should be a triple in range 0 to 1
if numel(str)==3
col = double( str );
col(col<0) = 0;
col(col>1) = 1;
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
elseif isa(str,'uint8')
% UINT8, so range is implicit
if numel(str)==3
col = double( str )/255;
col(col<0) = 0;
col(col>1) = 1;
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
end % iInterpretColor
function str = dequote(str)
str(str=='''') = [];
str(str=='"') = [];
str(str=='[') = [];
str(str==']') = [];
end % dequote
|
github
|
abagde93/ECE253-master
|
chroma_keying.m
|
.m
|
ECE253-master/ECE253_HW1/main/chroma_keying.m
| 1,591 |
utf_8
|
e7026e5d39354368b8b173526f4cabc4
|
%Problem 4: Chroma Keying
function [] = chroma_keying(input_image, mask_params, background_image)
%First read in input and background images
input_img = imread(input_image);
img_background = imread(background_image);
%Process input image. Get histograms for individual RGB channels
%This way we can set thresholds for the mask
input_img_R = input_img(:,:,1);
input_img_G = input_img(:,:,2);
input_img_B = input_img(:,:,3);
%Binary image showing foreground mask
mask = (input_img(:,:,1) < mask_params(1)) & (input_img(:,:,2) > mask_params(2)) & (input_img(:,:,3) < mask_params(3));
mask = imcomplement(mask);
binary_mask = uint8(mask);
%Use mask on original image, get RGB image on black background
original_foreground(:,:,1) = input_img(:,:,1).*binary_mask;
original_foreground(:,:,2) = input_img(:,:,2).*binary_mask;
original_foreground(:,:,3) = input_img(:,:,3).*binary_mask;
%Now place RGB image on another background
new_background(:,:,1) = original_foreground(:,:,1) + img_background(:,:,1).*(1-binary_mask);
new_background(:,:,2) = original_foreground(:,:,2) + img_background(:,:,2).*(1-binary_mask);
new_background(:,:,3) = original_foreground(:,:,3) + img_background(:,:,3).*(1-binary_mask);
subplot(2,3,1)
imhist(input_img_R)
title('red histogram')
subplot(2,3,2)
imhist(input_img_G)
title('green histogram')
subplot(2,3,3)
imhist(input_img_B)
title('blue histogram')
subplot(2,3,4)
imshow(mask)
title('Binary Mask(i)')
subplot(2,3,5)
imshow(original_foreground)
title('Foreground(ii)')
subplot(2,3,6)
imshow(new_background)
title('Foreground on New Background(iii)')
|
github
|
abagde93/ECE253-master
|
compute_norm_rgb_histogram.m
|
.m
|
ECE253-master/ECE253_HW1/main/compute_norm_rgb_histogram.m
| 1,870 |
utf_8
|
3229b67d2beb9479737cc65025d1a230
|
%Problem 3: Histograms
function rgb_hist = compute_norm_rgb_histogram(input_image)
%First we have to read in the image
%We pass the function the image --> compute_norm_rgb_histogram(image_name)
%imshow(input_image)
%Now seperate image into individual RGB components
red = input_image(:,:,1);
green = input_image(:,:,2);
blue = input_image(:,:,3);
%convert to arrays to work with easier
red_array = reshape(red,1,[]);
green_array = reshape(green,1,[]);
blue_array = reshape(blue,1,[]);
%Now compute invidual histograms(5-bit, 32 bins)
red_hist = zeros(1,32);
green_hist = zeros(1,32);
blue_hist = zeros(1,32);
for bin = 1:32
for x=1:length(red_array) %All arrays are the same size
t_min = (255/32)*(bin-1);
t_max = (255/32)*(bin);
if (red_array(x) <= t_max && red_array(x) >= t_min)
red_hist(1,bin) = red_hist(1,bin) + 1;
end
if (green_array(x) <= t_max && green_array(x) >= t_min)
green_hist(1,bin) = green_hist(1,bin) + 1;
end
if (blue_array(x) <= t_max && blue_array(x) >= t_min)
blue_hist(1,bin) = blue_hist(1,bin) + 1;
end
end
end
%Concatenate histograms together and normalize
rgb_vector = cat(2,red_hist,green_hist,blue_hist);
rgb_hist = rgb_vector./sum(rgb_vector);
subplot(3,3,1)
imhist(red)
title('red imhist(testing)')
subplot(3,3,2)
imhist(green)
title('green imhist(testing)')
subplot(3,3,3)
imhist(blue)
title('blue imhist(testing)')
subplot(3,3,4)
x=(1:32)*8;
bar(x,red_hist)
xlim([0 255])
title('red')
subplot(3,3,5)
x=(1:32)*8;
bar(x,green_hist)
xlim([0 255])
title('green')
subplot(3,3,6)
x=(1:32)*8;
bar(x,blue_hist)
xlim([0 255])
title('blue')
subplot(3,3,8)
x=(1:96)*7.968;
bar(x,rgb_hist)
xlim([0 765])
title('RGB hist(FINAL ANSWER)')
xlabel('96 bins(32 each for R,G,B respectively)')
ylabel('normalized histogram')
|
github
|
abagde93/ECE253-master
|
chroma_keying.m
|
.m
|
ECE253-master/ECE253_HW1/Problem4/chroma_keying.m
| 1,591 |
utf_8
|
e7026e5d39354368b8b173526f4cabc4
|
%Problem 4: Chroma Keying
function [] = chroma_keying(input_image, mask_params, background_image)
%First read in input and background images
input_img = imread(input_image);
img_background = imread(background_image);
%Process input image. Get histograms for individual RGB channels
%This way we can set thresholds for the mask
input_img_R = input_img(:,:,1);
input_img_G = input_img(:,:,2);
input_img_B = input_img(:,:,3);
%Binary image showing foreground mask
mask = (input_img(:,:,1) < mask_params(1)) & (input_img(:,:,2) > mask_params(2)) & (input_img(:,:,3) < mask_params(3));
mask = imcomplement(mask);
binary_mask = uint8(mask);
%Use mask on original image, get RGB image on black background
original_foreground(:,:,1) = input_img(:,:,1).*binary_mask;
original_foreground(:,:,2) = input_img(:,:,2).*binary_mask;
original_foreground(:,:,3) = input_img(:,:,3).*binary_mask;
%Now place RGB image on another background
new_background(:,:,1) = original_foreground(:,:,1) + img_background(:,:,1).*(1-binary_mask);
new_background(:,:,2) = original_foreground(:,:,2) + img_background(:,:,2).*(1-binary_mask);
new_background(:,:,3) = original_foreground(:,:,3) + img_background(:,:,3).*(1-binary_mask);
subplot(2,3,1)
imhist(input_img_R)
title('red histogram')
subplot(2,3,2)
imhist(input_img_G)
title('green histogram')
subplot(2,3,3)
imhist(input_img_B)
title('blue histogram')
subplot(2,3,4)
imshow(mask)
title('Binary Mask(i)')
subplot(2,3,5)
imshow(original_foreground)
title('Foreground(ii)')
subplot(2,3,6)
imshow(new_background)
title('Foreground on New Background(iii)')
|
github
|
abagde93/ECE253-master
|
compute_norm_rgb_histogram.m
|
.m
|
ECE253-master/ECE253_HW1/Problem3/compute_norm_rgb_histogram.m
| 1,870 |
utf_8
|
3229b67d2beb9479737cc65025d1a230
|
%Problem 3: Histograms
function rgb_hist = compute_norm_rgb_histogram(input_image)
%First we have to read in the image
%We pass the function the image --> compute_norm_rgb_histogram(image_name)
%imshow(input_image)
%Now seperate image into individual RGB components
red = input_image(:,:,1);
green = input_image(:,:,2);
blue = input_image(:,:,3);
%convert to arrays to work with easier
red_array = reshape(red,1,[]);
green_array = reshape(green,1,[]);
blue_array = reshape(blue,1,[]);
%Now compute invidual histograms(5-bit, 32 bins)
red_hist = zeros(1,32);
green_hist = zeros(1,32);
blue_hist = zeros(1,32);
for bin = 1:32
for x=1:length(red_array) %All arrays are the same size
t_min = (255/32)*(bin-1);
t_max = (255/32)*(bin);
if (red_array(x) <= t_max && red_array(x) >= t_min)
red_hist(1,bin) = red_hist(1,bin) + 1;
end
if (green_array(x) <= t_max && green_array(x) >= t_min)
green_hist(1,bin) = green_hist(1,bin) + 1;
end
if (blue_array(x) <= t_max && blue_array(x) >= t_min)
blue_hist(1,bin) = blue_hist(1,bin) + 1;
end
end
end
%Concatenate histograms together and normalize
rgb_vector = cat(2,red_hist,green_hist,blue_hist);
rgb_hist = rgb_vector./sum(rgb_vector);
subplot(3,3,1)
imhist(red)
title('red imhist(testing)')
subplot(3,3,2)
imhist(green)
title('green imhist(testing)')
subplot(3,3,3)
imhist(blue)
title('blue imhist(testing)')
subplot(3,3,4)
x=(1:32)*8;
bar(x,red_hist)
xlim([0 255])
title('red')
subplot(3,3,5)
x=(1:32)*8;
bar(x,green_hist)
xlim([0 255])
title('green')
subplot(3,3,6)
x=(1:32)*8;
bar(x,blue_hist)
xlim([0 255])
title('blue')
subplot(3,3,8)
x=(1:96)*7.968;
bar(x,rgb_hist)
xlim([0 765])
title('RGB hist(FINAL ANSWER)')
xlabel('96 bins(32 each for R,G,B respectively)')
ylabel('normalized histogram')
|
github
|
abagde93/ECE253-master
|
AHE.m
|
.m
|
ECE253-master/ECE253_HW2/Problem1/AHE.m
| 1,359 |
utf_8
|
606ab0162f38e5b54dfb15ce5fa9c543
|
%Problem 1: Adaptive Histogram Equalization
function enhanced_image = AHE(input_image,win_size)
%Pad input image based on window size, so conextual region for edge pixels
%remains valid. Window size in always MxM, where M is odd.
%Window will always be contered on pixel of interest. This means that the
%padding on each size has to be exactly (M-1)/2
pad = (win_size -1)/2;
padded_image = padarray(input_image,[pad pad],'symmetric');
[rows,cols] = size(input_image);
%Allocate enhanced_image matrix
enhanced_image = zeros(rows,cols);
for x=1:rows
for y=1:cols
rank = 0;
%current pixel in terms of the padded matrix(offset)
current_pixel = padded_image(x+pad,y+pad);
for i = -pad:1:pad
for j = -pad:1:pad
if padded_image(x+pad+i,y+pad+j) > current_pixel
rank = rank+1;
end
end
end
output_pixel = rank*255/(win_size*win_size);
enhanced_image(x,y) = output_pixel;
end
end
test_image = histeq(input_image);
subplot(1,3,1)
imshow(input_image)
title('original image')
subplot(1,3,2)
imshow(enhanced_image, [])
title('enhanced image - AHE')
subplot(1,3,3)
imshow(test_image)
title('MATLAB HE')
|
github
|
abagde93/ECE253-master
|
QUANT_MSE.m
|
.m
|
ECE253-master/ECE253_HW2/main/QUANT_MSE.m
| 1,852 |
utf_8
|
4e5588d86ca8130cc5dea9700714ea4a
|
%Problem 3 - Lloyd-Max Quantizer
function MSE = QUANT_MSE(im)
%%Part1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Defined seperate function myQuantize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Part2 and Part3%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Reshape image in order to perform Lloyd-Max quantizing
[M,N] = size(im);
training_set = reshape(im,N*M,1);
%Preallocate MSE arrays
MSE_myQ_orig = [];
MSE_LM_orig = [];
for s = 1:1:7
%Performing uniform quantization using myQuantize function
im_quantized = myQuantize(im, s);
%Find MSE between myQuantize'd and original image
MSE = sum((sum(((im_quantized - im).^2))))/numel(im);
MSE_myQ_orig = [MSE_myQ_orig, MSE];
%Performing Lloyd Max quantization
len = 2.^s;
training_set = double(training_set);
[partition, codebook] = lloyds(training_set, len);
[im_lloyd ,index] = quantiz(training_set,partition,codebook);
im_lloyd = (im_lloyd/len)*255;
im_lloyd = reshape(im_lloyd,[M,N]);
im_lloyd = uint8(im_lloyd);
%Find MSE between LM-Quantize'd and original image
MSE = sum((sum(((im_lloyd - im).^2))))/numel(im);
MSE_LM_orig = [MSE_LM_orig, MSE];
%Show images at s-bit quantization levels
subplot(2,7,s)
imshow(im_quantized)
title(sprintf('myQuantize %d bit', s))
subplot(2,7,s+7)
imshow(im_lloyd)
title(sprintf('Lloyd-Max %d bit', s))
end
%Plot MSE vs bits
figure
subplot(1,2,1)
plot(MSE_myQ_orig)
title('MSE - myQuantize')
xlabel('#-bit image')
ylabel('MSE')
subplot(1,2,2)
plot(MSE_LM_orig)
title('MSE - LM-Quantize')
xlabel('#-bit image')
ylabel('MSE')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
abagde93/ECE253-master
|
AHE.m
|
.m
|
ECE253-master/ECE253_HW2/main/AHE.m
| 1,359 |
utf_8
|
606ab0162f38e5b54dfb15ce5fa9c543
|
%Problem 1: Adaptive Histogram Equalization
function enhanced_image = AHE(input_image,win_size)
%Pad input image based on window size, so conextual region for edge pixels
%remains valid. Window size in always MxM, where M is odd.
%Window will always be contered on pixel of interest. This means that the
%padding on each size has to be exactly (M-1)/2
pad = (win_size -1)/2;
padded_image = padarray(input_image,[pad pad],'symmetric');
[rows,cols] = size(input_image);
%Allocate enhanced_image matrix
enhanced_image = zeros(rows,cols);
for x=1:rows
for y=1:cols
rank = 0;
%current pixel in terms of the padded matrix(offset)
current_pixel = padded_image(x+pad,y+pad);
for i = -pad:1:pad
for j = -pad:1:pad
if padded_image(x+pad+i,y+pad+j) > current_pixel
rank = rank+1;
end
end
end
output_pixel = rank*255/(win_size*win_size);
enhanced_image(x,y) = output_pixel;
end
end
test_image = histeq(input_image);
subplot(1,3,1)
imshow(input_image)
title('original image')
subplot(1,3,2)
imshow(enhanced_image, [])
title('enhanced image - AHE')
subplot(1,3,3)
imshow(test_image)
title('MATLAB HE')
|
github
|
abagde93/ECE253-master
|
QUANT_MSE.m
|
.m
|
ECE253-master/ECE253_HW2/Problem3/QUANT_MSE.m
| 1,852 |
utf_8
|
4e5588d86ca8130cc5dea9700714ea4a
|
%Problem 3 - Lloyd-Max Quantizer
function MSE = QUANT_MSE(im)
%%Part1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Defined seperate function myQuantize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Part2 and Part3%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Reshape image in order to perform Lloyd-Max quantizing
[M,N] = size(im);
training_set = reshape(im,N*M,1);
%Preallocate MSE arrays
MSE_myQ_orig = [];
MSE_LM_orig = [];
for s = 1:1:7
%Performing uniform quantization using myQuantize function
im_quantized = myQuantize(im, s);
%Find MSE between myQuantize'd and original image
MSE = sum((sum(((im_quantized - im).^2))))/numel(im);
MSE_myQ_orig = [MSE_myQ_orig, MSE];
%Performing Lloyd Max quantization
len = 2.^s;
training_set = double(training_set);
[partition, codebook] = lloyds(training_set, len);
[im_lloyd ,index] = quantiz(training_set,partition,codebook);
im_lloyd = (im_lloyd/len)*255;
im_lloyd = reshape(im_lloyd,[M,N]);
im_lloyd = uint8(im_lloyd);
%Find MSE between LM-Quantize'd and original image
MSE = sum((sum(((im_lloyd - im).^2))))/numel(im);
MSE_LM_orig = [MSE_LM_orig, MSE];
%Show images at s-bit quantization levels
subplot(2,7,s)
imshow(im_quantized)
title(sprintf('myQuantize %d bit', s))
subplot(2,7,s+7)
imshow(im_lloyd)
title(sprintf('Lloyd-Max %d bit', s))
end
%Plot MSE vs bits
figure
subplot(1,2,1)
plot(MSE_myQ_orig)
title('MSE - myQuantize')
xlabel('#-bit image')
ylabel('MSE')
subplot(1,2,2)
plot(MSE_LM_orig)
title('MSE - LM-Quantize')
xlabel('#-bit image')
ylabel('MSE')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
lodemo/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
|
lodemo/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
|
beridel/fast_matched_filter-master
|
fast_matched_filter.m
|
.m
|
fast_matched_filter-master/fast_matched_filter/fast_matched_filter.m
| 5,239 |
utf_8
|
c3c59b14256bbcf7816ddf1f7c56dd06
|
% :copyright:
% William B. Frank and Eric Beauce
% :license:
% GNU General Public License, Version 3
% (https://www.gnu.org/licenses/gpl-3.0.en.html)
function [cc_sum] = fast_matched_filter(templates, ...
moveouts, ...
weights, ...
data, ...
step, ...
arch)
% input:
% templates ---------- 4D matrix [time x components x stations x templates]
% moveouts ----------- 3D matrix [components x stations x templates]
% or 2D matrix [stations x templates]
% (in that case, the same moveout is attributed to each component)
% weights ------------ 3D matrix [components x stations x templates]
% or 2D matrix [stations x templates]
% (in that case, the same weight is attributed to each component)
% data --------------- 3D matrix [time x components x stations]
% step --------------- interval between correlations (in samples)
% arch --------------- 'cpu' or 'precise'
% By default 'cpu' should be used. 'precise' is a more
% precise and slower CPU implementation for template
% matching. 'precise' should be used when large
% amplitudes in the data bias the calculation of the
% correlation coefficients, for example when the
% template event does not detect itself with a
% correlation coefficient of 1.
%
% NB: Mean and trend MUST be removed from template and data traces before
% using this function
%
% output:
% 2D matrix [times (at step defined interval) x templates]
n_samples_template = size(templates, 1);
n_components = size(templates, 2);
n_stations = size(templates, 3);
n_templates = size(templates, 4);
n_samples_data = size(data, 1);
n_corr = floor((n_samples_data - n_samples_template) / step + 1);
sum_square_templates = squeeze(sum(templates .^ 2, 1));
% extend the moveouts and weights matrices from 2D to 3D matrices, if necessary
b = ones(n_components, 1);
if numel(moveouts) ~= n_components * n_stations * n_templates
moveouts = reshape(kron(moveouts, b), [n_components, n_stations, n_templates]);
end
if numel(weights) ~= n_components * n_stations * n_templates
weights = reshape(kron(weights, b), [n_components, n_stations, n_templates]);
end
% input arguments (brackets indicate a non-scalar variable):
% templates (float) [time x components x stations x templates]
% sum of square of templates (float) [components x stations x templates]
% moveouts (int) [components x stations x templates]
% data (float) [time x components x stations]
% weights (float) [components x stations x templates]
% step, or the samples between each sliding window (int)
% N samples per template trace (int)
% N samples per data trace (int)
% N templates (int)
% N stations (int)
% N components (int)
% N samples in correlation sums (int)
% output arguments:
% cc_sum (float)
templates = single(templates(:));
sum_square_templates = single(sum_square_templates(:));
moveouts = int32(moveouts(:));
data = single(data(:));
weights = single(weights(:));
step = int32(step);
n_samples_template = int32(n_samples_template);
n_samples_data = int32(n_samples_data);
n_templates = int32(n_templates);
n_stations = int32(n_stations);
n_components = int32(n_components);
n_corr = int32(n_corr);
if strcmp(arch, 'cpu')
% fprintf('Use the regular cpu implementation.\n');
cc_sum = matched_filter(templates, ...
sum_square_templates, ...
moveouts, ...
data, ...
weights, ...
step, ...
n_samples_template, ...
n_samples_data, ...
n_templates, ...
n_stations, ...
n_components, ...
n_corr);
elseif strcmp(arch, 'precise')
% fprintf('Use the more precise, slower cpu implementation.\n');
cc_sum = matched_filter_precise(templates, ...
sum_square_templates, ...
moveouts, ...
data, ...
weights, ...
step, ...
n_samples_template, ...
n_samples_data, ...
n_templates, ...
n_stations, ...
n_components, ...
n_corr);
else
error('arch should be cpu or precise\n');
end
cc_sum = reshape(cc_sum, [], n_templates);
n_zeros = sum(cc_sum(1:(n_corr-max(moveouts)),1) == 0.);
if n_zeros > 10
text = sprintf('%d correlation computations were skipped. Can be caused by zeros in data, or too low amplitudes (try to increase the gain).\n', n_zeros);
fprintf(text);
end
end
|
github
|
MRC-CBU/riksneurotools-master
|
rsfMRI_GLM.m
|
.m
|
riksneurotools-master/Conn/rsfMRI_GLM.m
| 25,725 |
utf_8
|
2654812ab9bb94b923565c58d1b0db46
|
function [Zmat, Bmat, pZmat, pBmat, aY, X0r] = rsfMRI_GLM(S);
% [Zmat, Bmat, pZmat, pBmat, aY, X0r] = rsfMRI_GLM(S);
%
% Function (using SPM8 functions) for estimating linear regressions
% between fMRI timeseries in each pair of Nr ROIs, adjusting for bandpass
% filter, confounding timeseries (eg CSF) and (SVD of) various expansions of
% movement parameters, and properly modelling dfs based on comprehensive
% model of error autocorrelation.
%
% [email protected], Jan 2013
%
% Many thanks to Linda Geerligs for pointing out improvements!
%
% S.Y = [Ns x Nr] data matrix, where Ns = number of scans (ie resting-state fMRI timeseries) and Nr = number of ROIs
% S.M = [Ns x 6] matrix of 6 movement parameters from realignment (x,y,z,pitch,roll,yaw)
% S.C = [Ns x Nc] matrix of confounding timeseries, Nc = number of confounds (eg extracted from WM, CSF or Global masks)
% S.G = [0/1] - whether to include global over ROIs (ie given current data) (default = 0)
% S.TR = time between volumes (TR), in seconds
%
% (S.HPC (default = 100) = highpass cut-off (in seconds)
% (S.LPC (default = 10) = lowpass cut-off (in seconds)
% (S.CY (default = {}) = precomputed covariance over pooled voxels (optional)
% (S.pflag (default=0) is whether to calculate partial regressions too (takes longer))
% (S.svd_thr (default=.99) is threshold for SVD of confounds)
% (S.SpikeMovAbsThr (default='', ie none) = absolute threshold for outliers based on RMS of Difference of Translations
% (S.SpikeMovRelThr (default='', ie none) = relative threshold (in SDs) for outliers based on RMS of Difference of Translations or Rotations
% (S.SpikeDatRelThr (default='', ie none) = relative threshold (in SDs) for mean of Y over voxels (outliers, though arbitrary?)
% (S.SpikeLag (default=1) = how many TRs after a spike are modelled out as separate regressors
% (S.StandardiseY (default = 0) = whether to Z-score each ROI's timeseries to get standardised Betas)
% (S.PreWhiten (default = 1) = whether to estimate autocorrelation of error and prewhiten (slower, but better Z-values (less important for Betas?))
% (S.GlobMove = user-specified calculation of global movement)
%
% Zmat = [Nr x Nr] matrix of Z-statistics for linear regression from seed (row) to target (column) ROI
% Bmat = [Nr x Nr] matrix of betas for linear regression from seed (row) to target (column) ROI
% pZmat = [Nr x Nr] matrix of Z-statistics for partial linear regression from seed (row) to target (column) ROI
% pZmat = [Nr x Nr] matrix of betas for partial linear regression from seed (row) to target (column) ROI
% aY = data adjusted for confounds
% X0r = confounds (filter, confound ROIs, movement expansion)
%
% Note:
% some Inf Z-values can be returned in Zmat (when p-value so low than inv_Ncdf is infinite)
% (these could be replaced by the maximum Z-value in matrix?)
%
% Potential improvements:
% regularised regression (particularly for pZmat), eg L1 with LASSO - or L2 implementable with spm_reml_sc?
try Y = S.Y; catch error('Need Nscans x Nrois data matrix'); end
try C = S.C; catch error('Need Nscans x Nc matrix of Nc confound timeseries (Nc can be zero)'); end
try TR = S.TR; catch error('Need TR (in secondss)'); end
try HPC = S.HPC; catch
HPC = 1/0.01;
warning('Assuming highpass cut-off of %d',HPC);
end
try LPC = S.LPC; catch
LPC = 1/0.2;
warning('Assuming lowpass cut-off of %d',LPC);
end
try CY = S.CY; catch
CY = [];
end
try GlobalFlag = S.G; catch
GlobalFlag = 0;
end
try SpikeMovAbsThr = S.SpikeMovAbsThr; catch
SpikeMovAbsThr = '';
% SpikeMovAbsThr = 0.5; % mm from Power et al
% SpikeMovAbsThr = 0.25; % mm from Satterthwaite et al 2013
end
try SpikeMovRelThr = S.SpikeMovRelThr; catch
% SpikeMovRelThr = '';
SpikeMovRelThr = 5; % 5 SDs of mean?
end
try SpikeDatRelThr = S.SpikeDatRelThr; catch
SpikeDatRelThr = '';
% SpikeDatRelThr = 5; % 5 SDs of mean?
end
try SpikeLag = S.SpikeLag; catch
SpikeLag = 1;
% SpikeLag = 5; % 5 TRs after spike?
end
try StandardiseY = S.StandardiseY; catch
StandardiseY = 0;
end
try PreWhiten = S.PreWhiten; catch
PreWhiten = 1;
end
try VolterraLag = S.VolterraLag; catch
VolterraLag = 5; % artifacts can last up to 5 TRs = 10s, according to Power et al (2013)
end
try pflag = S.pflag; catch pflag = 0; end
try svd_thr = S.svd_thr; catch svd_thr = .99; end
Ns = size(Y,1);
Nr = size(Y,2);
%% If want to try Matlab's LASSO (takes ages though)
% lassoflag = 0;
% if lassoflag
% matlabpool open
% opts = statset('UseParallel','always');
% end
%% Create a DCT bandpass filter (so filtering part of model, countering Hallquist et al 2013 Neuroimage)
K = spm_dctmtx(Ns,Ns);
nHP = fix(2*(Ns*TR)/HPC + 1);
nLP = fix(2*(Ns*TR)/LPC + 1);
K = K(:,[2:nHP nLP:Ns]); % Remove initial constant
Nk = size(K,2);
fprintf('Bandpass filter using %d dfs (%d left)\n',Nk,Ns-Nk)
%% Create comprehensive model of residual autocorrelation (to counter Eklund et al, 2012, Neuroimage)
if PreWhiten
T = (0:(Ns - 1))*TR; % time
d = 2.^(floor(log2(TR/4)):log2(64)); % time constants (seconds)
Q = {}; % dictionary of components
for i = 1:length(d)
for j = 0:1
Q{end + 1} = toeplitz((T.^j).*exp(-T/d(i)));
end
end
end
%% Detect outliers in movement and/or data
%M = detrend(M,0);
%M(:,4:6)= M(:,4:6)*180/pi;
if ~isfield(S,'GlobMove')
try M = S.M; catch error('Need Nscans x 6 movement parameter matrix'); end
if size(M,2) == 6
dM = [zeros(1,6); diff(M,1,1)]; % First-order derivatives
% Combine translations and rotations based on ArtRepair approximation for voxels 65mm from origin?
%cdM = sqrt(sum(dM(:,1:3).^2,2) + 1.28*sum(dM(:,4:6).^2,2));
dM(:,4:6) = dM(:,4:6)*50; % Approximate way of converting rotations to translations, assuming sphere radius 50mm (and rotations in radians) from Linda Geerligs
cdM = sum(abs(dM),2);
else
error('If not user-specified global movement passed, then must pass 3 translations and 3 rotations')
end
else
cdM = S.GlobMove;
try M = S.M; catch M=[]; end
end
if ~isempty(SpikeMovAbsThr) % Absolute movement threshold
% rms = sqrt(mean(dM(:,1:3).^2,2)); % if want translations only
% aspk = find(rms > SpikeMovAbsThr);
aspk = find(cdM > SpikeMovAbsThr);
fprintf('%d spikes in absolute movement differences (based on threshold of %4.2f)\n',length(aspk),SpikeMovAbsThr)
else
aspk = [];
end
if ~isempty(SpikeMovRelThr) % Relative (SD) threshold for translation and rotation
% rms = sqrt(mean(dM(:,1:3).^2,2));
% rspk = find(rms > (mean(rms) + SpikeMovRelThr*std(rms)));
% rms = sqrt(mean(dM(:,4:6).^2,2));
% rspk = [rspk; find(rms > (mean(rms) + SpikeMovRelThr*std(rms)))];
rspk = find(cdM > (mean(cdM) + SpikeMovRelThr*std(cdM)));
fprintf('%d spikes in relative movement differences (based on threshold of %4.2f SDs)\n',length(rspk),SpikeMovRelThr)
else
rspk = [];
end
if ~isempty(SpikeDatRelThr) % Relative (SD) threshold across all ROIs (dangerous? Arbitrary?)
dY = [zeros(1,Nr); diff(Y,1,1)];
rms = sqrt(mean(dY.^2,2));
dspk = find(rms > (mean(rms) + SpikeDatRelThr*std(rms)));
fprintf('%d spikes in mean data across ROIs (based on threshold of %4.2f SDs)\n',length(dspk),SpikeDatRelThr)
else
dspk = [];
end
%% Create delta-function regressors for each spike
spk = unique([aspk; rspk; dspk]); lspk = spk;
for q = 2:SpikeLag
lspk = [lspk; spk + (q-1)];
end
spk = unique(lspk);
if ~isempty(spk)
RSP = zeros(Ns,length(spk));
n = 0;
for p = 1:length(spk)
if spk(p) <= Ns
n=n+1;
RSP(spk(p),n) = 1;
end
end
fprintf('%d unique spikes in total\n',length(spk))
RSP = spm_en(RSP,0);
else
RSP = [];
end
%% Create expansions of movement parameters
% Standard differential + second-order expansion (a la Satterthwaite et al, 2012)
% sM = []; for m=1:6; for n=m:6; sM = [sM M(:,m).*M(:,n)]; end; end % Second-order expansion
% sdM = []; for m=1:6; for n=m:6; sdM = [sdM dM(:,m).*dM(:,n)]; end; end % Second-order expansion of derivatives
% aM = [M dM sM sdM];
% Above commented bits are subspace of more general Volterra expansion
%U=[]; for c=1:6; U(c).u = M(:,c); U(c).name{1}=sprintf('m%d',c); end; [aM,aMname] = spm_Volterra(U,[1 0 0; 1 -1 0; 0 1 -1]',2);
%U=[]; for c=1:6; U(c).u = M(:,c); U(c).name{1}=sprintf('m%d',c); end; [aM,aMname] = spm_Volterra(U,[1 0; 1 -1; 0 1]',2); %Only N and N+1 needed according to Satterthwaite et al 2013
bf = eye(VolterraLag); % artifacts can last up to 5 TRs = 10s, according to Power et al (2013)
% bf = [1 0 0 0 0; 1 1 0 0 0; 1 1 1 0 0; 1 1 1 1 0; 1 1 1 1 1]; % only leads to a few less modes below, and small compared to filter anyway!
bf = [bf; diff(bf)];
U=[]; for c=1:size(M,2); U(c).u = M(:,c); U(c).name{1}='c'; end; aM = spm_Volterra(U,bf',2);
aM = spm_en(aM,0);
%% Add Global? (Note: may be passed by User in S.C anyway)
% (recommended by Rik and Power et al, 2013, though will entail negative
% correlations, which can be problem for some graph-theoretic measures)
if GlobalFlag
C = [C mean(Y,2)];
end
C = spm_en(C,0);
%% Combine all confounds (assumes more data than confounds, ie Ns > Nc) and perform dimension reduction (cf PCA of correlation matrix)
%X0 = [C RSP K(:,2:end) aM]; % exclude constant term from K
XM = spm_en(ones(Ns,1)); % constant term
X1 = [XM K RSP]; % Regressors that don't want to SVD
X0 = [aM C]; % Regressors that will SVD below
%X1 = [XM K C RSP]; % Regressors that don't want to SVD
%X0 = [aM]; % Regressors that will SVD below
X0r = X0;
if ~isempty(X0)
R1 = eye(Ns) - X1*pinv(X1);
X0 = R1*X0; % Project out of SVD-regressors what explained by non-SVD regressors!
X0 = spm_en(X0,0);
% Possible of course that some dimensions tiny part of SVD of X (so excluded) by happen to correlate highly with y...
% ...could explore some L1 (eg LASSO) or L2 regularisation of over-parameterised model instead,
% but LASSO takes ages (still working on possible L2 approach with spm_reml)
if svd_thr < 1
[U,S] = spm_svd(X0,0);
S = diag(S).^2; S = full(cumsum(S)/sum(S));
Np = find(S > svd_thr); Np = Np(1);
X0r = full(U(:,1:Np));
fprintf('%d SVD modes left (from %d original terms) - %4.2f%% variance of correlation explained\n',Np,size(X0,2),100*S(Np))
end
end
X0r = [K RSP X0r XM]; % Reinsert mean
Nc = size(X0r,2);
if Nc >= Ns; error('Not enough dfs (scans) to estimate');
else fprintf('%d confounds for %d scans (%d left)\n',Nc,Ns,Ns-Nc); end
%% Create adjusted data, in case user wants for other metrics, eg, MI, and standardised data, if requested
R = eye(Ns) - X0r*pinv(X0r);
aY = R*Y;
if StandardiseY
Y = zscore(Y);
else
Y = Y/std(Y(:)); % Some normalisation necessary to avoid numerical underflow, eg in cov(Y') below
end
%% Pool data covariance over ROIs (assuming enough of them!), unless specified
if isempty(CY) & PreWhiten
CY = cov(Y'); % Correct to only do this after any standardisation?
end
%%%%%%%%%%%%%%%%%%%%%%%%%% Main Loop
%% Do GLMs for all target ROIs for a given source ROI
Ar = [1:Nr];
Zmat = zeros(Nr); % Matrix of Z statistics for each pairwise regression
Bmat = zeros(Nr);
if pflag
pZmat = zeros(Nr); % Matrix of Z statistics for each pairwise partial regression
pBmat = zeros(Nr); % Matrix of Z statistics for each pairwise partial regression
else
pZmat = [];
pBmat = [];
end
%[V h] = rik_reml(CY,X0r,Q,1,0,4); % if could assume that error did not depend on seed timeseries
%W = spm_inv(spm_sqrtm(V));
lNpc = 0; % Just for printing pflag output below
for n = 1:Nr
Ir = setdiff(Ar,n);
Yr = Y(:,Ir); % Yr contains all other timeseries, so ANCOVA below run on Nr-2 timeseries in one go
Xr = Y(:,n);
% Xr = spm_en(Xr); % Normalise regressors so Betas can be compared directly across (seed) ROIs (not necessary if Standardised Y already)?
X = [Xr X0r];
% if lassoflag == 1 % takes too long (particularly for cross-validation to determine lambda)
% for pn = 1:length(Ir)
% Ir = setdiff(Ar,pn);
%
% Yr = Y(:,Ir); % Yr contains all other timeseries, so ANCOVA below run on Nr-2 timeseries in one go
% Xr = Y(:,pn);
% Xr = spm_en(Xr,0); % Normalise regressors so Betas can be compared directly across (seed) ROIs (not necessary is Standardised Y already)?
%
% fprintf('l');
% [lB,lfit] = lasso(X0r,Yr(:,pn),'CV',10,'Options',opts);
% keepX = find(lB(:,lfit.Index1SE));
% X = [Xr X0r(:,keepX)];
% Nc = length(keepX);
%
% [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up
% W = spm_inv(spm_sqrtm(V));
%
% %% Estimate T-value for regression of first column (seed timeseries)
% [T(pn),dfall,Ball] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Nc)]');
% df(pn) = dfall(2);
% B(pn) = Ball(1);
% end
% fprintf('\n');
% else
%% Estimate autocorrelation of error (pooling across ROIs) and prewhitening matrix
if PreWhiten
[V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up
W = spm_inv(spm_sqrtm(V));
else
W = speye(Ns);
end
%% Estimate T-value for regression of first column (seed timeseries)
[T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr,[1 zeros(1,Nc)]');
try
Zmat(n,Ir) = norminv(spm_Tcdf(T,df(2))); % Needs Matlab Stats toolbox, but has larger range of Z (so not so many "Inf"s)
catch
Zmat(n,Ir) = spm_invNcdf(spm_Tcdf(T,df(2)));
end
Bmat(n,Ir) = B(1,:);
%% Estimate T-value for PARTIAL regression of first column (seed timeseries) - takes ages!
if pflag
for pn = 1:length(Ir)
pIr = setdiff(Ar,[n Ir(pn)]);
pY = spm_en(Y(:,pIr),0); % Is necessary for SVD below
% SVD
if svd_thr < 1
[U,S] = spm_svd([pY X0],0);
S = diag(S).^2; S = full(cumsum(S)/sum(S));
Np = find(S > svd_thr); Np = Np(1);
XY0 = full(U(:,1:Np));
Npc = Np;
else
XY0 = [pY X0];
end
XY0 = [XY0 ones(Ns,1)]; % Reinsert mean
Npc = size(XY0,2);
% if lassoflag == 1
% fprintf('l')
% [lB,lfit] = lasso(XY0,Yr(:,pn),'CV',10,'Options',opts);
% keepX = find(lB(:,lfit.Index1SE));
% X = [Xr XY0(:,keepX)];
% Nc = length(keepX);
%
% [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up
% W = spm_inv(spm_sqrtm(V));
%
% %% Estimate T-value for regression of first column (seed timeseries)
% [T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Nc)]');
% else
if Npc >= (Ns-1) % -1 because going to add Xr below
warning('Not enough dfs (scans) to estimate - just adjusting data and ignoring loss of dfs');
R = eye(Ns) - pY*pinv(pY); % Residual-forming matrix
[T,df,B] = spm_ancova(W*X,speye(Ns,Ns),R*W*Yr(:,pn),[1 zeros(1,Npc)]'); % Ok to assume error and hence W unaffected by addition of pY in X?
else
if lNpc ~= Npc % Just to reduce time taken to print to screen
fprintf(' partial for seed region %d and target region %d: %d confounds for %d scans (%d left)\n',n,pn,Npc,Ns,Ns-Npc);
end
lNpc = Npc;
X = [Xr XY0];
%% Commented out below because ok to assume error and hence W unaffected by addition of pY in X?
% [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up
% W = spm_inv(spm_sqrtm(V));
%% Estimate T-value for regression of first column (seed timeseries)
[T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Npc)]');
end
try
pZmat(n,Ir(pn)) = norminv(spm_Tcdf(T,df(2)));
catch
pZmat(n,Ir(pn)) = spm_invNcdf(spm_Tcdf(T,df(2)));
end
pBmat(n,Ir(pn)) = B(1);
end
end
fprintf('.')
end
fprintf('\n')
return
%figure,imagesc(Zmat); colorbar
%figure,imagesc(pZmat); colorbar
function [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,D,t,hE,hP)
% ReML estimation of [improper] covariance components from y*y'
% FORMAT [C,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,D,t,hE,hP);
%
% YY - (m x m) sample covariance matrix Y*Y' {Y = (m x N) data matrix}
% X - (m x p) design matrix
% Q - {1 x q} covariance components
%
% N - number of samples (default 1)
% D - Flag for positive-definite scheme (default 0)
% t - regularisation (default 4)
% hE - hyperprior (default 0)
% hP - hyperprecision (default 1e-16)
%
% C - (m x m) estimated errors = h(1)*Q{1} + h(2)*Q{2} + ...
% h - (q x 1) ReML hyperparameters h
% Ph - (q x q) conditional precision of h
%
% F - [-ve] free energy F = log evidence = p(Y|X,Q) = ReML objective
%
% Fa - accuracy
% Fc - complexity (F = Fa - Fc)
%
% Performs a Fisher-Scoring ascent on F to find ReML variance parameter
% estimates.
%
% see also: spm_reml_sc for the equivalent scheme using log-normal
% hyperpriors
%__________________________________________________________________________
%
% SPM ReML routines:
%
% spm_reml: no positivity constraints on covariance parameters
% spm_reml_sc: positivity constraints on covariance parameters
% spm_sp_reml: for sparse patterns (c.f., ARD)
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Karl Friston
% $Id: spm_reml.m 5223 2013-02-01 11:56:05Z ged $
% Modified by Rik to remove screen output and turn off warnings
% check defaults
%--------------------------------------------------------------------------
try, N; catch, N = 1; end % assume a single sample if not specified
try, K; catch, K = 32; end % default number of iterations
try, D; catch, D = 0; end % default checking
try, t; catch, t = 4; end % default regularisation
try, hE; catch, hE = 0; end % default hyperprior
try, hP; catch, hP = 1e-16; end % default hyperprecision
% catch NaNs
%--------------------------------------------------------------------------
W = Q;
q = find(all(isfinite(YY)));
YY = YY(q,q);
for i = 1:length(Q)
Q{i} = Q{i}(q,q);
end
% dimensions
%--------------------------------------------------------------------------
n = length(Q{1});
m = length(Q);
% ortho-normalise X
%--------------------------------------------------------------------------
if isempty(X)
X = sparse(n,0);
else
X = spm_svd(X(q,:),0);
end
% initialise h and specify hyperpriors
%==========================================================================
h = zeros(m,1);
for i = 1:m
h(i,1) = any(diag(Q{i}));
end
hE = sparse(m,1) + hE;
hP = speye(m,m)*hP;
dF = Inf;
D = 8*(D > 0);
warning off
% ReML (EM/VB)
%--------------------------------------------------------------------------
for k = 1:K
% compute current estimate of covariance
%----------------------------------------------------------------------
C = sparse(n,n);
for i = 1:m
C = C + Q{i}*h(i);
end
% positive [semi]-definite check
%----------------------------------------------------------------------
for i = 1:D
if min(real(eig(full(C)))) < 0
% increase regularisation and re-evaluate C
%--------------------------------------------------------------
t = t - 1;
h = h - dh;
dh = spm_dx(dFdhh,dFdh,{t});
h = h + dh;
C = sparse(n,n);
for i = 1:m
C = C + Q{i}*h(i);
end
else
break
end
end
% E-step: conditional covariance cov(B|y) {Cq}
%======================================================================
iC = spm_inv(C);
iCX = iC*X;
if ~isempty(X)
Cq = spm_inv(X'*iCX);
else
Cq = sparse(0);
end
% M-step: ReML estimate of hyperparameters
%======================================================================
% Gradient dF/dh (first derivatives)
%----------------------------------------------------------------------
P = iC - iCX*Cq*iCX';
U = speye(n) - P*YY/N;
for i = 1:m
% dF/dh = -trace(dF/diC*iC*Q{i}*iC)
%------------------------------------------------------------------
PQ{i} = P*Q{i};
dFdh(i,1) = -spm_trace(PQ{i},U)*N/2;
end
% Expected curvature E{dF/dhh} (second derivatives)
%----------------------------------------------------------------------
for i = 1:m
for j = i:m
% dF/dhh = -trace{P*Q{i}*P*Q{j}}
%--------------------------------------------------------------
dFdhh(i,j) = -spm_trace(PQ{i},PQ{j})*N/2;
dFdhh(j,i) = dFdhh(i,j);
end
end
% add hyperpriors
%----------------------------------------------------------------------
e = h - hE;
dFdh = dFdh - hP*e;
dFdhh = dFdhh - hP;
% Fisher scoring: update dh = -inv(ddF/dhh)*dF/dh
%----------------------------------------------------------------------
dh = spm_dx(dFdhh,dFdh,{t});
h = h + dh;
% predicted change in F - increase regularisation if increasing
%----------------------------------------------------------------------
pF = dFdh'*dh;
if pF > dF
t = t - 1;
else
t = t + 1/4;
end
% revert to SPD checking, if near phase-transition
%----------------------------------------------------------------------
if ~isfinite(pF) || abs(pF) > 1e6
[V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,t - 2);
return
else
dF = pF;
end
% Convergence (1% change in log-evidence)
%======================================================================
% fprintf('%s %-23d: %10s%e [%+3.2f]\n',' ReML Iteration',k,'...',full(pF),t);
% final estimate of covariance (with missing data points)
%----------------------------------------------------------------------
if dF < 1e-1, break, end
end
% re-build predicted covariance
%==========================================================================
V = 0;
for i = 1:m
V = V + W{i}*h(i);
end
% check V is positive semi-definite (if not already checked)
%==========================================================================
if ~D
if min(eig(V)) < 0
[V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,2,hE(1),hP(1));
return
end
end
% log evidence = ln p(y|X,Q) = ReML objective = F = trace(R'*iC*R*YY)/2 ...
%--------------------------------------------------------------------------
Ph = -dFdhh;
if nargout > 3
% tr(hP*inv(Ph)) - nh + tr(pP*inv(Pp)) - np (pP = 0)
%----------------------------------------------------------------------
Ft = trace(hP*inv(Ph)) - length(Ph) - length(Cq);
% complexity - KL(Ph,hP)
%----------------------------------------------------------------------
Fc = Ft/2 + e'*hP*e/2 + spm_logdet(Ph*inv(hP))/2 - N*spm_logdet(Cq)/2;
% Accuracy - ln p(Y|h)
%----------------------------------------------------------------------
Fa = Ft/2 - trace(C*P*YY*P)/2 - N*n*log(2*pi)/2 - N*spm_logdet(C)/2;
% Free-energy
%----------------------------------------------------------------------
F = Fa - Fc;
end
warning on
function [C] = spm_trace(A,B)
% fast trace for large matrices: C = spm_trace(A,B) = trace(A*B)
% FORMAT [C] = spm_trace(A,B)
%
% C = spm_trace(A,B) = trace(A*B) = sum(sum(A'.*B));
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_trace.m 4805 2012-07-26 13:16:18Z karl $
% fast trace for large matrices: C = spm_trace(A,B) = trace(A*B)
%--------------------------------------------------------------------------
C = sum(sum(A'.*B));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.