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 | urbste/MLPnP_matlab_toolbox-master | extractA.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/extractA.m | 2,185 | utf_8 | 13ae6c28060717fe4500e5c7fffd82c0 | % Apart = extractA(At,Ajc,blk0,blk1,blkstart[,blkstart2])
% EXTRACTA Fast alternative to
% Apart = At(blkstart(1):blkstart(2)-1,:).
% Instead of blkstart(2), it takes "blkstart2" (if supplied) or
% size(At,1)+1 (if neither blkstart(2) nor blkstart2) are available.
%
% Extract submatrix of
% A with subscripts "blkstart(1):blkstart(2)-1" and has its nonzeros per column
% bounded bij Ajc1:Ajc2. If Ajc1 = [] (Ajc2=[]) then start at column start
% (end at column end) of A.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also partitA
function Apart = extractA(At,Ajc,blk0,blk1,blkstart,blkstart2)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | veccomplex.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/veccomplex.m | 3,006 | utf_8 | f9c6ce5e9906c2b3f5d39a6ed53616c6 | % z = veccomplex(x,cpx,K)
% ********** INTERNAL FUNCTION OF SEDUMI **********
function z = veccomplex(x,cpx,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
z = zeros(length(x) - cpx.dim,1);
dimflqr = K.f+K.l+sum(K.q)+sum(K.r);
rsel = 1:dimflqr;
nfx = length(cpx.f)+length(cpx.x);
imsel = 1:nfx;
imsel = imsel' + [zeros(length(cpx.f),1); vec(cpx.x)];
rsel(imsel) = 0;
rsel = find(rsel);
z(1:dimflqr-nfx) = x(rsel);
z(cpx.f) = z(cpx.f) + sqrt(-1) * x(imsel(1:length(cpx.f)));
z(cpx.x) = z(cpx.x) + sqrt(-1) * x(imsel(length(cpx.f)+1:end));
% ----------------------------------------
% PSD:
% ----------------------------------------
hfirstk = 1+dimflqr + sum(K.s(1:K.rsdpN).^2); % start of Hermitian blocks
zfirstk = 1+dimflqr - nfx; % start of psd blocks in z
firstk = 1+dimflqr; % start if psd blocks in x
k = 1; sk = 1;
for knz = 1:length(cpx.s)
newk = cpx.s(knz);
if newk > k
len = sum(K.s(sk:sk+newk-k-1).^2);
z(zfirstk:zfirstk+len-1) = x(firstk:firstk+len-1); % copy real PSD blocks
zfirstk = zfirstk + len;
firstk = firstk + len;
sk = sk + newk - k; % handled newk-k real blocks
end
nksqr = K.s(K.rsdpN + knz)^2; % insert a Hermitian block
z(zfirstk:zfirstk+nksqr-1) = x(hfirstk:hfirstk+nksqr-1) ...
+ i * x(hfirstk+nksqr: hfirstk+2*nksqr-1);
zfirstk = zfirstk + nksqr;
hfirstk = hfirstk + 2*nksqr;
k = newk + 1; % handled up to block newk.
end
if sk <= K.rsdpN % copy remaining real blocks
len = sum(K.s(sk:K.rsdpN).^2);
z(zfirstk:zfirstk+len-1) = x(firstk:firstk+len-1);
end |
github | urbste/MLPnP_matlab_toolbox-master | vec.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/vec.m | 1,567 | utf_8 | f3fc35a93c8a5b99b592835a0b810dd5 | % Y = VEC(x) Given an m x n matrix x, this produces the vector Y of length
% m*n that contains the columns of the matrix x, stacked below each other.
%
% See also mat.
function x = vec(X)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
[m n] = size(X);
x = reshape(X,m*n,1); |
github | urbste/MLPnP_matlab_toolbox-master | sdinit.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/sdinit.m | 4,508 | utf_8 | 267a7f165ea8a2d377b14f1b99a7aba1 | % [d, v,vfrm,y,y0, R] = sdinit(At,b,c,dense,K,pars)
% SDINIT Initialize with identity solution, for self-dual model.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [d, v,vfrm,y,y0, R] = sdinit(At,b,c,dense,K,pars)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% --------------------------------------------------
% Initialize m = #eqns, n = order(K).
% --------------------------------------------------
m = length(b);
n = K.l + 2 * length(K.q) + K.rLen + K.hLen;
% ------------------------------------------------------------
% Include some inf-norms to determine scaling/magnitude of data.
% ------------------------------------------------------------
R.maxb = norm(b,inf);
R.maxc = norm(c,inf);
% ----------------------------------------
% Choose trivial soln on central path:
% y = 0; v = mu * identity with mu := pars.mu * sqrt(norm(b)*norm(c)).
% ----------------------------------------
y = zeros(m,1);
mu = pars.mu * sqrt((1+R.maxb)*(1+R.maxc));
id = qreshape(eyeK(K),0,K);
v = mu * id;
y0 = n * mu; % b0 * y0 = norm(v)^2.
R.b0 = mu;
% ------------------------------------------------------------
% Determine primal/dual scaling "d0", so that x = d0*v, z=v/d0.
% sd-var different: x0 = 1, z0 = mu^2.
% ------------------------------------------------------------
d0 = sqrt((1+R.maxb) / (1+R.maxc));
x0 = pars.mu; z0 = mu^2 / x0;
cx = d0 * (c'*v);
R.sd = (z0 + cx)/ y0;
% ----------------------------------------
% Since x=d0^2*z, we have d = d0 * identity
% ----------------------------------------
d.l = d0^2 * ones(K.l,1); % LP
d.l(1) = x0/z0; % =1/mu^2.
d.det = d0^2 * ones(length(K.q),1); % LORENTZ
d.q1 = (sqrt(2) * d0) * ones(length(K.q),1); % trace part of d0 * identity
d.q2 = zeros(K.mainblks(3)-K.mainblks(2),1);
d.auxdet = sqrt(2*d.det);
d.auxtr = sqrt(2)*(d.q1 + d.auxdet);
d.u = sqrt(d0) * id(K.lq+1:end); % sqrt(d0) * identity (PSD)
d.perm = [];
% ----------------------------------------
% Create Jordan frame of v = mu * identity
% vfrm.q denotes Lorentz frame (norm 1/sqrt(2) blocks).
% vfrm.s = I in Householder product form,
% ----------------------------------------
vfrm.lab = mu*ones(n,1); % identity
vfrm.q = d.q2;
vfrm.s = qrK(d.u,K);
% ----------------------------------------
% Residuals R.b, R.c, R.sd, and size-parameter R.b0.
% A x - x0 b - y0 R.b = 0
% -A'y + x0 c + y0 R.c - z = 0
% b'y - c'x + y0 R.sd - z0 = 0
% Rb'y -Rc'x - x0 Rsd = -b0
% ----------------------------------------
R.b = d0 * Amul(At,dense,v,0); % x = d0 *v
R.b = (R.b - x0*b) / y0;
R.c = vecsym(v/d0-x0*c,K) / y0; % z = v/d0
R.c(1) = 0.0; % for artificial (x0,z0)
% ------------------------------------------------------------
% Some inf-norms to determine scaling/magnitude of Residuals.
% Note that if R.sd < 0 then this residual may be absorbed into z0.
% ------------------------------------------------------------
R.maxRb = max(1e-6, norm(R.b,inf));
R.maxRc = max(1e-6, norm(R.c,inf));
R.norm = max([R.maxRb, R.maxRc, R.sd]);
R.w = 2 * pars.w .* [R.maxRb;R.maxRc] ./ [1+R.maxb;1+R.maxc]; |
github | urbste/MLPnP_matlab_toolbox-master | psdscale.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/psdscale.m | 6,141 | utf_8 | d6b8616345e5086c5e26c53ea7a16b13 | % y = psdscale(ud,x,K [,transp])
% PSDSCALE Computes length lenud (=sum(K.s.^2)) vector y.
% !transp (default) then y[k] = vec(Ldk' * Xk * Ldk)
% transp == 1 then y[k] = vec(Udk' * Xk * Udk)
% Uses pivot ordering ud.perm if available and nonempty.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also scaleK, factorK.
function y = psdscale(ud,x,K,varargin)
% This file is part of SeDuMi 1.3 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%The function is quite dirty as the type and dimension of the inputs may
%change, that is why we have so many subcases.
if ~isempty(varargin)
transp=varargin{1};
else
transp=0;
end
Ks=K.s;
if ~isempty(Ks)
N=sum(Ks.^2);
y(N,1)=0;
else
y=[];
return
end
startindices=K.sblkstart-K.mainblks(end)+1;
%Sometimes x containts only the PSD part, sometimes the whole thing
xstartindices=startindices+(length(x)-N);
permindices=cumsum([1,Ks]);
if ~transp
if isstruct(ud)
if isempty(ud.perm)
for i=1:K.rsdpN
Ksi=Ks(i);
temp=tril(reshape(ud.u(startindices(i):startindices(i+1)-1),Ksi,Ksi));
y(startindices(i):startindices(i+1)-1)=...
temp'...
*reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi)...
*temp;
end
else
for i=1:K.rsdpN
Ksi=Ks(i);
temp=tril(reshape(ud.u(startindices(i):startindices(i+1)-1),Ksi,Ksi));
X=reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi);
%We only permute if we have to
if isequal(ud.perm(permindices(i):permindices(i+1)-1),(1:Ksi)')
if nnz(X)/(Ksi*Ksi)<0.1
y(startindices(i):startindices(i+1)-1)=...
temp'...
*sparse(X)...
*temp;
else
y(startindices(i):startindices(i+1)-1)=...
temp'...
*X...
*temp;
end
else
y(startindices(i):startindices(i+1)-1)=...
temp'...
*X(ud.perm(permindices(i):permindices(i+1)-1),ud.perm(permindices(i):permindices(i+1)-1))...
*temp;
end
end
end
else
for i=1:K.rsdpN
Ksi=Ks(i);
temp=tril(reshape(ud(startindices(i):startindices(i+1)-1),Ksi,Ksi));
X=reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi);
if spars(X)<0.1
y(startindices(i):startindices(i+1)-1)=...
temp'...
*sparse(X)...
*temp;
else
y(startindices(i):startindices(i+1)-1)=...
temp'...
*X...
*temp;
end
end
end
else %transp
if isstruct(ud)
if isempty(ud.perm)
for i=1:K.rsdpN
Ksi=Ks(i);
temp=triu(reshape(ud.u(startindices(i):startindices(i+1)-1),Ksi,Ksi));
y(startindices(i):startindices(i+1)-1)=...
temp'...
*reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi)...
*temp;
end
else
for i=1:K.rsdpN
Ksi=Ks(i);
temp=triu(reshape(ud.u(startindices(i):startindices(i+1)-1),Ksi,Ksi));
X=reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi);
if isequal(ud.perm(permindices(i):permindices(i+1)-1),(1:Ksi)')
if nnz(X)/(Ksi*Ksi)<0.1
y(startindices(i):startindices(i+1)-1)=temp'...
*sparse(X)...
*temp;
else
y(startindices(i):startindices(i+1)-1)=temp'...
*X...
*temp;
end
else
tempy=zeros(Ksi,Ksi);
tempy(ud.perm(permindices(i):permindices(i+1)-1),ud.perm(permindices(i):permindices(i+1)-1))=temp'...
*X...
*temp;
y(startindices(i):startindices(i+1)-1)=tempy;
end
end
end
else
for i=1:K.rsdpN
Ksi=Ks(i);
temp=triu(reshape(ud(startindices(i):startindices(i+1)-1),Ksi,Ksi));
y(startindices(i):startindices(i+1)-1)=...
temp'...
*reshape(x(xstartindices(i):xstartindices(i+1)-1),Ksi,Ksi)...
*temp;
end
end
end |
github | urbste/MLPnP_matlab_toolbox-master | checkpars.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/checkpars.m | 5,983 | utf_8 | cab850e9f461f590a5dafa49bbaba500 | % pars = checkpars(pars,lponly)
% CHECKPARS Fills in defaults for missing fields in "pars" structure.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function pars = checkpars(pars,lponly)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
% --------------------------------------------------
% Algorithm selection parameters
% --------------------------------------------------
if ~isfield(pars,'alg') | sum([0 1 2] == pars.alg) == 0
pars.alg = 2;
end
if ~isfield(pars,'beta') % 0.1 <= beta <= 0.9 (theoretically in (0,1))
pars.beta = 0.5;
elseif pars.beta > 0.9
pars.beta = 0.9;
elseif pars.beta < 0.1
pars.beta = 0.1;
end
if ~isfield(pars,'theta') % 0.01 <= theta <= 1.0 (theoretically in (0,1])
if pars.alg == 0
pars.theta = 1;
else
pars.theta = 0.25;
end
elseif pars.theta > 1.0
pars.theta = 1.0;
elseif pars.theta < 0.01
pars.theta = 0.01;
end
if ~isfield(pars,'stepdif')
pars.stepdif = 2; %adaptive step-differentiation
end
if ~isfield(pars,'w')
pars.w = [1;1];
elseif length(pars.w)~=2
warning('pars.w should be vector of order 2')
pars.w = [1;1];
else
pars.w = max(pars.w,1e-8); % positive weights
end
pars.w = reshape(pars.w,2,1);
% -------------------------------------------------
% Preprocessing
% -------------------------------------------------
% How to treat free variables: 0: split them, 1: put them in Q-cone
% (default)
if ~isfield(pars,'free')
pars.free=1;
end
if ~isfield(pars,'sdp')
pars.sdp=1; %Enable/disable SDP preprocessing
end
% --------------------------------------------------
% Initialization
% --------------------------------------------------
if ~isfield(pars,'mu') | pars.mu <= 0
pars.mu = 1;
end
% --------------------------------------------------
% Stopping and reporting criteria
% --------------------------------------------------
if ~isfield(pars,'fid') % iter output file handle
pars.fid = 1;
end
if ~isfield(pars,'eps') % stopping tolerance
pars.eps = 1E-8;
end
if ~isfield(pars,'bigeps') % threshold for numerr=1 vs 2.
pars.bigeps = 1E-3;
end
if ~isfield(pars,'maxiter')
pars.maxiter = 150;
end
% --------------------------------------------------
% Debugging and algorithmic/diagnostic analysis
% --------------------------------------------------
if ~isfield(pars,'vplot')
pars.vplot = 0;
end
if ~isfield(pars,'stopat')
pars.stopat = -1;
end
if ~isfield(pars,'errors') %Print and return the DIMACS errors
pars.errors = 1;
end
if ~isfield(pars,'prep') %Print preprocessing information
pars.prep=1;
end
% --------------------------------------------------
% Dense column handling
% --------------------------------------------------
if ~isfield(pars,'denq')
pars.denq = 0.75;
end
if ~isfield(pars,'denf')
pars.denf=10;
end
% --------------------------------------------------
% Numerical control
% --------------------------------------------------
if ~isfield(pars,'numtol') % Criterion for refinement
pars.numtol = 5E-7;
end
if ~isfield(pars,'bignumtol') % Criterion for failure
pars.bignumtol = 0.9; % will be multiplied by y0.
end
if ~isfield(pars,'numlvl')
pars.numlvl = 0;
end
if isfield(pars,'chol')
cholpars = pars.chol;
if ~isfield(cholpars,'skip')
cholpars.skip = 1;
end
if ~isfield(cholpars,'abstol')
cholpars.abstol = 1E-20;
end
if ~isfield(cholpars,'canceltol') % Cancelation in LDL computation
cholpars.canceltol = 1E-12;
end
if ~isfield(cholpars,'maxu')
cholpars.maxu = 5E5;
end
if ~isfield(cholpars,'maxuden')
cholpars.maxuden = 5E2;
end
else
cholpars.skip = 1;
cholpars.abstol = 1e-20;
cholpars.canceltol = 1E-12;
cholpars.maxu = 5E5;
cholpars.maxuden = 5E2;
end
pars.chol = cholpars;
if isfield(pars,'cg') % Criterion Conjugate Gradient
cgpars = pars.cg;
if ~isfield(cgpars,'qprec') % Use quadruple precision on main iters
cgpars.qprec = 1;
end
if ~isfield(cgpars,'restol') % Required relative residual accuracy
cgpars.restol = 5E-3;
end
if ~isfield(cgpars,'stagtol') % Stagnation in function progress
cgpars.stagtol = 5E-14;
end
if ~isfield(cgpars,'maxiter') % Max number of cg steps
cgpars.maxiter = 49;
end
if ~isfield(cgpars,'refine')
cgpars.refine = 1;
end
else
cgpars.qprec = 1;
cgpars.restol = 5E-3;
cgpars.stagtol = 5E-14;
cgpars.maxiter = 49;
cgpars.refine = 1;
end
pars.cg = cgpars; |
github | urbste/MLPnP_matlab_toolbox-master | optstep.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/optstep.m | 6,305 | utf_8 | 48415e80b179e639152e1a6da3307dd2 | % [x,y] = optstep(A,b,c, y0,y,d,v,dxmdz, K,L,symLden,...
% dense,Ablkjc,Aord,ADA,DAt, feasratio, R,pars)
% OPTSTEP Implements Mehrotra-Ye type optimality projection for
% IPM-LP solver.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [x,y] = optstep(A,b,c, y0,y,d,v,dxmdz, K,L,symLden,...
dense,Ablkjc,Aord,ADA,DAt, feasratio, R,pars)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
% ------------------------------------------------------------
% For LP-problems, we PROJECT onto OPTIMAL FACE (x0 > 0) *OR*
% onto a direction (x0 = 0) with the same sign for c'*x and b'*y.
% ------------------------------------------------------------
if abs(abs(feasratio)-1) < 0.1
x0 = sqrt(d.l(1)) * v(1);
z0 = x0 / d.l(1);
%This value is never used.
%deptol = 1E-10 * max(x0,z0);
if (feasratio < -0.5) & (x0 < z0^2)
x0 = 0; % Try project onto direction.
end
% ------------------------------------------------------------
% Set d(Non-basic-LP) = 0
% Nonbasic is where dx < dz i.e. dxmdz < 0, ideally: dx_N = -v_N, dz_N = 0.
% ------------------------------------------------------------
lpNB = find(dxmdz < 0);
d.l(lpNB) = 0;
% --------------------------------------------------
% Compute ADA, with d[N] = 0. Hence A[B]*D[B]^2*A[B]'.
% --------------------------------------------------
DAt = getDAtm(A,Ablkjc,dense,DAt.denq,d,K);
if sum(K.s)==0
%ADA is global already
absd=getada(A,K,d,DAt);
else
ADA = getada1(ADA, A, Ablkjc(:,3), Aord.lqperm, d, K.qblkstart);
ADA = getada2(ADA, DAt, Aord, K);
[ADA,absd] = getada3(ADA, A, Ablkjc(:,3), Aord, invcholfac(d.u, K, d.perm), K);
end
% ------------------------------------------------------------
% Block Sparse Cholesky: ADA(L.perm,L.perm) = L.L*diag(L.d)*L.L'
% ------------------------------------------------------------
[L.L,L.d,L.skip,L.add] = blkchol(L,ADA,pars.chol,absd);
clear ADA;
% ------------------------------------------------------------
% Factor dense columns
% ------------------------------------------------------------
[Lden,L.d] = deninfac(symLden, L,dense,DAt,d,absd,K.qblkstart,pars.chol);
% ------------------------------------------------------------
% Solve ADAt*psi = -x0*b+A*D*v, dx = v-D*At*psi. LEAST SQUARES.
% ------------------------------------------------------------
[psi,dx,err.kcg,err.b] = wrapPcg(L,Lden,A,dense,d, DAt,K,...
(-x0) * b,v, pars.cg,pars.eps / pars.cg.restol);
x = sqrt(d.l) .* dx;
% ----------------------------------------
% CHECK WHETHER x[B] >= 0 AND WHETHER RESIDUAL DID NOT DETERIORATE.
% ----------------------------------------
if (min(x) < 0.0) | ...
(norm(err.b,inf) > 2 * max(max(y0,1e-10 * x0) * R.maxb, y0 * R.maxRb))
x = []; % Incorrect guess of LP-basis
return
else
% ==================== DUAL PART (LP ONLY) ====================
% ------------------------------------------------------------
% Solve A[B]'*dy = x0*c[B]-A[B]'*y, so that zB=0. We solve
% the equivalent system obtained after pre-multiplying with A[B]*P(d[b]).
% ------------------------------------------------------------
rhs = sqrt(d.l) .* (x0*c - Amul(A,dense,y,1));
% ------------------------------------------------------------
% Solve ADA*dy = A*D*rhs. THIS IS DEBATABLE !
% ------------------------------------------------------------
dy = wrapPcg(L,Lden,A,dense,d, DAt,K,...
zeros(length(b),1),rhs, pars.cg,pars.eps / pars.cg.restol);
y = y+dy;
% ------------------------------------------------------------
% CHECK WHETHER Z[N] >= 0 AND RESID ON Z[B]=0 DID NOT DETERIORATE.
% ALSO, we need z0 >= 0 and x0+z0 > 0.
% ------------------------------------------------------------
z = x0*c - Amul(A,dense,y,1);
z(1) = 0;
zB = z;
zB(lpNB) = 0;
normzB = norm(zB,inf);
cx = c'*x;
by = b'*y;
z0 = by - cx; %[JFS 9/2003: changed condition below
if (~isempty(lpNB) & (min(z(lpNB)) < 0.0)) | ...
normzB > 5 * max(1E-10 * (x0+(x0==0)) * norm(c), min(y0,1e-8) * norm(R.c))
x = []; % Incorrect guess of LP-basis
return
end
if x0 == 0
if z0 <= 0
x = []; % z0 <= 0 --> P/D Direction not improving anymore
return
end
elseif z0 < - (5E-8) * (1+abs(by) +max(abs(b)))
x = []; % x0>0, z0 << 0 then not optimal.
return
end
end
else
% ------------------------------------------------------------
% If optimality step impossible , then return emptyset.
% ------------------------------------------------------------
x = []; y = [];
end |
github | urbste/MLPnP_matlab_toolbox-master | pretransfo.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/pretransfo.m | 12,320 | utf_8 | b696ed8c17798178167ef32da61fa239 | % [At,b,c,K,prep] = pretransfo(At,b,c,K)
% PRETRANSFO Checks data and then transforms into internal SeDuMi format.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [At,b,c,K,prep,origcoeff] = pretransfo(At,b,c,K,pars)
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
% ----------------------------------------
% Make sure that all fields exist in K-structure
% ----------------------------------------
if ~isfield(K,'f') % K.f
K.f = 0;
elseif isempty(K.f)
K.f = 0;
elseif (K.f~= floor(K.f)) | (K.f < 0)
error('K.f should be nonnegative integer')
end
if ~isfield(K,'l') % K.l
K.l = 0;
elseif isempty(K.l)
K.l = 0;
elseif (K.l~= floor(K.l)) | (K.l < 0)
error('K.l should be nonnegative integer')
end
if ~isfield(K,'q') % K.q
K.q = [];
elseif sum(K.q) == 0
K.q = [];
elseif ~isempty(K.q)
if (min(K.q) < 2) | any(K.q~= floor(K.q))
error('K.q should contain only integers bigger than 1')
end
if size(K.q,1) > 1
K.q = K.q';
end
end
if ~isfield(K,'r') % K.r
K.r = [];
elseif sum(K.r) == 0
K.r = [];
elseif ~isempty(K.r)
if (min(K.r) < 3) | any(K.r~= floor(K.r))
error('K.r should contain only integers bigger than 2')
end
if size(K.r,1) > 1
K.r = K.r';
end
end
if ~isfield(K,'s') % K.s
K.s = [];
elseif sum(K.s) == 0
K.s = [];
elseif ~isempty(K.s)
if min(K.s < 1) | any(K.s~= floor(K.s))
error('K.s should contain only positive integers')
end
if size(K.s,2) > 1
K.s = K.s';
end
end
% ------------------------------------------------------------
% Validity check: Info on complex interpretation of variables
% ------------------------------------------------------------
if ~isfield(K,'ycomplex') % K.ycomplex
K.ycomplex = [];
elseif ~isempty(K.ycomplex)
if (min(K.ycomplex) < 1) | (min(size(K.ycomplex)) > 1) | ...
any(K.ycomplex~= floor(K.ycomplex))
error('K.ycomplex should be a list containing only positive integers')
end
if size(K.ycomplex,1) > 1
K.ycomplex = K.ycomplex';
end
if max(K.ycomplex) > length(b)
error('K.ycomplex out of range')
end
end
if ~isfield(K,'xcomplex') % K.xcomplex
K.xcomplex = [];
elseif ~isempty(K.xcomplex)
if (min(K.xcomplex) < 1) | (min(size(K.xcomplex))) > 1 | ...
any(K.xcomplex~= floor(K.xcomplex))
error('K.xcomplex should be a list containing only positive integers')
end
if size(K.xcomplex,1) > 1
K.xcomplex = K.xcomplex';
end
if max(K.xcomplex) > K.f+K.l+sum(K.q)+sum(K.r)
error('K.xcomplex out of range')
end
end
if ~isfield(K,'scomplex') % K.scomplex
K.scomplex = [];
elseif ~isempty(K.scomplex)
if min(K.scomplex) < 1 | min(size(K.scomplex)) > 1 | ...
any(K.scomplex~= floor(K.scomplex))
error('K.scomplex should be a list containing only positive integers')
end
if size(K.scomplex,1) > 1
K.scomplex = K.scomplex';
end
if max(K.scomplex) > length(K.s)
error('K.scomplex out of range')
end
end
% ----------------------------------------
% Check size of At,b,c (w.r.t. K)
% Let m = #eq-constraints, N = #variables (before transformations)
% ----------------------------------------
if (min(size(b)) > 1) | (min(size(c)) > 1)
error('Parameters b and c must be vectors')
end
m = min(size(At));
N = K.f + K.l + sum(K.q) + sum(K.r) + sum((K.s).^2);
if nnz(b) == 0
b = sparse(m,1);
elseif length(b) ~= m
error('Size b mismatch')
end
if m ~= size(b,1) % make b an m x 1 vector
b = b';
end
if nnz(c) == 0
c = sparse(N,1);
elseif length(c) ~= N
error('Size c mismatch')
end
if N ~= size(c,1) % make c an N x 1 vector
c = c';
end
if N <= m
error('Should have length(c) > length(b) in any sensible model')
end
if size(At,2) ~= m
if m == size(At,1)
At = At'; %user gave A instead of At.
else
error('Size At mismatches b.')
end
end
if size(At,1) ~= N;
error('Size At mismatches cone K.')
end
% ------------------------------------------------------------
% Check for NaN and Inf
% ------------------------------------------------------------
if any(any(isnan(At))) | any(isnan(b)) | any(isnan(c))
error('A,b,c data contains NaN values')
end
if any(any(isinf(At))) | any(isinf(b)) | any(isinf(c))
error('A,b,c data contains Inf values')
end
% ------------------------------------------------------------
% Save the standardized data for further use if needed
% ------------------------------------------------------------
if isfield(pars,'errors') & pars.errors==1
origcoeff.At=At;
origcoeff.c=c;
origcoeff.b=b;
origcoeff.K=K;
else
origcoeff=[];
end
% ----------------------------------------
% First add constraints IM(Ax)=IM(b) where i in K.ycomplex, i.e.
% Make "imag(Ax) = imag(b)" and "imag(y)" explicit.
% ----------------------------------------
if ~isempty(K.ycomplex)
b = [real(b);...
imag(b(K.ycomplex))]; % RE b'*y = [RE b; IM b]'*[RE y; IM y].
At = [At, sqrt(-1) * At(:,K.ycomplex)];
else
b = real(b);
end
m = length(b);
% ----------------------------------------
% Transform any complex data into internal format,
% which uses only MATLAB's real representation.
% ----------------------------------------
cpx = whichcpx(K);
cpx.s = K.scomplex;
cpx.dim = length(K.xcomplex) + sum(K.s(K.scomplex).^2);
At = makereal(sparse(At),K,cpx);
c = makereal(sparse(c),K,cpx);
K.f = K.f + length(cpx.f); % Update cone K structure wrt complex
K.q = vec(K.q) + vec(cpx.q);
K.r = vec(K.r) + vec(cpx.r);
sperm = ones(length(K.s),1);
sperm(cpx.s) = 0;
sperm = find(sperm);
K.rsdpN = length(sperm); % #real sym PSD blocks
K.s = K.s([vec(sperm); vec(cpx.s)]');
prep.cpx = cpx;
% ----------------------------------------
% Transform R-cones (rotated Lorentz) into Q-cones (standard Lorentz).
% ----------------------------------------
prep.lenKq = length(K.q);
if ~isempty(K.r)
c(K.f+1:end) = rotlorentz(c(K.f+1:end),K);
At(K.f+1:end,:) = rotlorentz(At(K.f+1:end,:),K);
K.q = [K.q; K.r];
K.r = [];
prep.rq=1;
else
prep.rq=0;
end
% ---------------------------------------------------
% Remove diagonal SDP blocks
% ---------------------------------------------------
if ~isfield(pars,'sdp')
pars.sdp=1; % Enable/disable SDP preprocessing
end
if cpx.dim>0
pars.sdp=0; % No SDP preprocessing for complex problems
end
if length(K.s)>1000 | max(K.s)<10
pars.sdp=0;
end
if pars.sdp==1
Atf=At(1:K.f,:);
cf=c(1:K.f);
Kf=K.f;
K.f=0;
[At,b,c,K,prep.sdp]=preprocessSDP(At(Kf+1:end,:),b,c(Kf+1:end),K);
At=[Atf;At];
c=[cf;c];
K.f=Kf;
clear Atf cf Kf
end
% ------------------------------------------------------------
% Search for hidden free variables in split form and convert them into free
% variables if pars.free=1 (they stay split if pars.free=0)
% ------------------------------------------------------------
if ~isfield(pars,'free')
pars.free=1;
end
if 0 & pars.free & K.l>0 %temporarily disabled due to a bug
stest=c(K.f+1:K.f+K.l)-At(K.f+1:K.f+K.l,:)*rand(m,1);
%Now we detect if stest contains the same vector twice, or opposite
%vectors.
[sabssorted,sindex]=sort(abs(stest));
sabsdiff=diff(sabssorted);
zeroindex=find(sabsdiff==0);
if length(zeroindex)>=2
%Allocate storage for the indices
block1ind=zeros(1,length(zeroindex));
block2ind=block1ind;
blockind=1;
for i=zeroindex'
if stest(sindex(i))==-stest(sindex(i+1))
block1ind(blockind)=sindex(i);
block2ind(blockind)=sindex(i+1);
blockind=blockind+1;
end
end
%Get rid of the tails
block1ind=block1ind(1:blockind-1);
block2ind=block2ind(1:blockind-1);
block1=false(1,K.l);
block2=block1;
block1(block1ind)=true;
block2(block2ind)=true;
%block1ind and block2ind contain the corresponding indices of the split
%variables, while block1 and block2 the logical vectors that are used
%for indexing
At=[At(K.f+block1ind,:);At(1:K.f,:);At([false(1,K.f),~(block1+block2)],:);At(K.f+K.l+1:end,:)];
c=[c(K.f+block1ind);c(1:K.f);c([false(1,K.f),~(block1+block2)]);c(K.f+K.l+1:end)];
K.f=K.f+length(block1ind);
K.l=K.l-2*length(block1ind);
prep.freeblock1=block1ind;
prep.freeblock2=block2ind;
end
end
% ------------------------------------------------------------
% Transform F-cone into L-cone or Q-cone
% Split if pars.free=0, put in Q-cone otherwise
% ------------------------------------------------------------
prep.Kf = K.f;
if K.f>0
switch pars.free
case 0
At = [-At(1:K.f,:);At];
c = [-c(1:K.f);c];
K.l = K.l + 2 * K.f;
K.f = 0;
case 1
c=[c(K.f+1:K.f+K.l);0;c(1:K.f);c(K.f+K.l+1:end)];
At=[At(K.f+1:K.f+K.l,:);zeros(1,m);At(1:K.f,:);At(K.f+K.l+1:end,:)];
K.q=[K.f+1;K.q];
K.f=0;
end
end
% --------------------------------------------------
% Split Lorentz blocks in trace-block + norm-bound-blocks
% --------------------------------------------------
if ~isempty(K.q)
At = qreshape(At,0,K);
c = qreshape(c,0,K);
end
% ----------------------------------------
% Correct A s.t. At has tril-blocks (for PSD),
% ----------------------------------------
At = vectril(At,K);
c = vectril(c,K);
% ----------------------------------------
% Create artificial (x0,z0) variable for
% self-dual model
% ----------------------------------------
c = [0;c]; %does not affect sparse/dense status of c.
At = [zeros(1,m); At];
K.l = K.l + 1; % add (x0,z0)
% ----------------------------------------
% Now K has field K.{l,q,s}
% Make more detailed description of cone K:
% Let K.blkstart(i):K.blkstart(i+1)-1 give the index range of block i.
% Compute maxN=max(order), len=sum(order) for LORENTZ, real PSD and herm PSD.
% yields: K.{l,q,s, rsdpN,blkstart, rLen,hLen, qMaxn,rMaxn,hMaxn}
% ----------------------------------------
K.rsdpN = length(K.s) - length(prep.cpx.s); % # real symmetric PSD vars
K = statsK(K);
K.mainblks = K.blkstart(cumsum([1 1 length(K.q)]));
K.qblkstart = K.blkstart(2:2+length(K.q)); % Also include blkend
K.sblkstart = K.blkstart(2+length(K.q):end);
K.lq = K.mainblks(end)-1;
K.N = length(c);
%Correct the sparsity structure of the variables, this can save a lot of
%memory.
%Correct the sparsity structure of the variables, this can save a lot of
%memory.
[i j s]=find(At);
At=sparse(i,j,s,K.N,m);
[i j s]=find(c);
c=sparse(i,j,s,K.N,1);
[i j s]=find(b);
b=sparse(i,j,s,m,1);
|
github | urbste/MLPnP_matlab_toolbox-master | deninfac.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/deninfac.m | 3,918 | utf_8 | 503533718cba50772b20a1ec05ff62ec | % [Lden, Ld] = deninfac(symLden, L,dense,DAt, d, absd, qblkstart,pars)
% DENINFAC
% Uses pars.maxuden as max. allowable |L(i,k)|. Otherwise num. reordering.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function [Lden, Ld] = deninfac(symLden, L,dense,DAt, d, absd, qblkstart,pars)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% ------------------------------------------------------------
% INITIALIZE: check the numerical tolerance parameters in "pars",
% and supply with defaults if necessary.
% ------------------------------------------------------------
if nargin < 7
pars.maxuden = 10; % Stability of product-form factors
else
if ~isfield(pars,'maxuden')
pars.maxuden = 10; % Stability of product-form factors
end
end
% --------------------------------------------------
% Scaling: let Ad = Aden * Dden, as [LP, QBLK, QNORM, QTR]
% with QBLK=DAt.denq, and the others dense.A(:,j)*dj,
% with dj = sqrt(d.l(k)) or dj=sqrt(d.det(k)).
% NOTE that A*P(d)*A' = ADA + Ad * Ad'.
% --------------------------------------------------
if length(dense.cols) > 0
i1 = dense.l+1; i2 = i1 + length(dense.q);
Ad = [dense.A(:,1:i1-1), DAt.denq, dense.A(:,i2:end), dense.A(:,i1:i2-1)];
smult = [d.l(dense.cols(1:dense.l)); ones(length(dense.q),1); ...
adenscale(dense,d,qblkstart); -d.det(dense.q)];
% --------------------------------------------------
% Correct for sparse part, i.e. let LAD = L\Ad
% (this also handles L.perm)
% --------------------------------------------------
LAD = sparfwslv(L,Ad, symLden.LAD);
clear Ad;
% --------------------------------------------------
% Factor the dense columns as "diag+rank-1"=diag(L.d)+LAD(:,k)*LAD(:,k)'
% --------------------------------------------------'
[Lden, Ld] = dpr1fact(LAD, L.d, symLden, smult, pars.maxuden);
Lden.dz = symLden.dz;
Lden.first = symLden.first;
Lden.perm = symLden.perm;
clear LAD;
else
% --------------------------------------------------
% If no dense columns
% --------------------------------------------------
Lden.betajc = 0;
Ld = L.d;
Lden.rowperm = 1:length(L.d);
end
% ------------------------------------------------------------
% If still Ld(i) = 0, then set to something positive. Otherwise
% we cannot do PCG.
% ------------------------------------------------------------
skip = find(L.skip);
if length(skip) > 0
dtol = pars.canceltol * absd(L.perm(skip));
dtol = max(dtol, pars.abstol);
Ld(skip(Ld(skip) <= dtol)) = 1;
end |
github | urbste/MLPnP_matlab_toolbox-master | eigK.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/eigK.m | 4,372 | utf_8 | 06d3bd415e6d53fd32cb95cbdc12ff37 | % [lab,q,f] = eigK(x,K)
%
% EIGK Computes the spectral values ("eigenvalues") or even the complete
% spectral decomposition of a vector x with respect to a self-dual
% homogeneous cone K.
%
% > LAB = EIGK(x,K) This yield the spectral values of x with respect to
% the self-dual homogeneous cone that you describe in the structure
% K. Up to 3 fields can be used, called K.l, K.q and K.s, for
% Linear, Quadratic and Semi-definite. Type `help sedumi' for more
% details on this structure.
%
% The length of the vector LAB is the order of the cone. Remark that
% x in K if and only if LAB>=0, and x in int(K) if and only if LAB>0.
%
% > [LAB,Q,F] = EIGK(x,K) Also produces the eigenvectors for the symmetric and
% Hermitian parts of x (corresponding to K.s), and the Lorentz frame F
% for the Lorentz blocks in x (corresponding to K.q). This extended
% version of EIGK is intended for INTERNAL USE BY SEDUMI.
%
% See also sedumi, mat, vec, eyeK.
function [lab,q,f] = eigK(x,K)
% THE M-FILE VERSION OF THIS FUNCTION IS HERE ONLY AS ILLUSTRATION.
% SEE THE C-SOURCE FOR THE MEX-VERSION.
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')
lab = zeros(K.l + 2*length(K.q) + sum(K.s),1);
% ----------------------------------------
% LP: lab = x
% ----------------------------------------
lab(1:K.l) = x(1:K.l);
firstk = K.l+1;
nextlab = K.l+1;
% ----------------------------------------
% LORENTZ: (lab, f) = qeig(x)
% ----------------------------------------
if nargout < 3
for k=1:length(K.q)
nk = K.q(k); lastk = firstk + nk - 1;
lab(nextlab:nextlab+1) = qeig(x(firstk:lastk));
firstk = lastk + 1; nextlab = nextlab + 2;
end
else
nextf = 1;
for k=1:length(K.q)
nk = K.q(k); lastk = firstk + nk - 1;
[labk, fk] = qeig(x(firstk:lastk));
lab(nextlab:nextlab+1) = labk;
f(nextf:nextf+nk-2) = fk;
firstk = lastk + 1; nextlab = nextlab + 2; nextf = nextf + nk-1;
end
end
% ----------------------------------------
% SDP: [q,lab] = eig(x)
% ----------------------------------------
offq = firstk - 1;
q = zeros(length(x)-offq,1);
for k = 1:K.rsdpN
nk = K.s(k); lastk = firstk + nk*nk - 1;
Xk = mat(x(firstk:lastk),nk);
Xk = (Xk + Xk') / 2;
[Qk, Labk] = eig(Xk);
lab(nextlab:nextlab+nk-1) = diag(Labk);
q(firstk-offq:lastk-offq) = Qk;
firstk = lastk + 1; nextlab = nextlab + nk;
end
for k = (1+K.rsdpN):length(K.s)
nk = K.s(k); ifirstk = firstk + nk*nk; lastk = ifirstk + nk*nk - 1;
Xk = mat(x(firstk:ifirstk-1)+sqrt(-1)*x(ifirstk:lastk),nk);
[Qk, Labk] = eig(Xk);
lab(nextlab:nextlab+nk-1) = real(diag(Labk));
q(firstk-offq:ifirstk-1-offq) = real(Qk);
q(ifirstk-offq:lastk-offq) = imag(Qk);
firstk = lastk + 1; nextlab = nextlab + nk;
end |
github | urbste/MLPnP_matlab_toolbox-master | wrapPcg.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/wrapPcg.m | 4,662 | utf_8 | 33ac2b19c5fe1a1134b316f4ebd23ff3 | % [y,r,k, DAy] = normeqPcg(L,Lden,At,dense,d, DAt,K, b, cgpars, y0,rhs)
%
% WRAPPCG Solve y from AP(d)A' * y = b
% using PCG-method and Cholesky L as conditioner.
% If L is sufficiently accurate, then only 1 CG-step is needed.
% In general, proceeds until ||DAy - DA'(AD^2A')^{-1}b||
% has converged (to zero). k = #(CG-iterations).
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi, loopPcg
function [y,dx,k, r] = wrapPcg(L,Lden,At,dense,d, DAt,K, rb,rv,cgpars, y0)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% --------------------------------------------------
% INITIALIZE:
% --------------------------------------------------
restol = y0 * cgpars.restol;
dx = [sqrt(d.l).*rv(1:K.l); asmDxq(d,rv,K); psdscale(d,rv,K,1)];
r = Amul(At,dense,dx);
if ~isempty(rb)
r = r+rb;
end
% --------------------------------------------------
% Pre - Conditioning/ Direct Solving:
% Solve L*THETA*L'*p = r, set ssqrNew = r'*inv(L*THETA*L')*r.
% --------------------------------------------------
p = fwdpr1(Lden,sparfwslv(L, r));
y = p ./ L.d;
ssqrNew = p'*y;
p = sparbwslv(L, bwdpr1(Lden,y));
% --------------------------------------------------
% SCALING OPERATION AND MATRIX*VECTOR.
% Let dx = D*A'*p
% Set alpha = ssqrNew / ||dx||^2
% --------------------------------------------------
x = vecsym(Amul(At,dense,p,1), K);
dx = [sqrt(d.l).*x(1:K.l); asmDxq(d,x,K); psdscale(d,x,K)];
ssqrdx = norm(dx)^2;
if ssqrdx <= 0.0
y = zeros(length(r),1);
k = 0;
dx = rv;
return
end
% --------------------------------------------------
% Take 1st step: y *= alpha, alpha:=ssqrNew / ssqrdx,
% dx = rv - alpha * dx.
% --------------------------------------------------
k = 1;
alpha = ssqrNew / ssqrdx;
y = alpha * p;
dx = rv - alpha * dx;
% --------------------------------------------------
% Compute 1st residual r := b + A*D*dx. (MATRIX*VECTOR).
% --------------------------------------------------
x = [sqrt(d.l).*dx(1:K.l); asmDxq(d,dx,K); psdscale(d,dx,K,1)];
r = Amul(At,dense,x);
if ~isempty(rb)
r = r + rb;
end
normr = norm(r,inf);
if normr < restol
return % No CG nor refinement needed.
end
STOP = 0;
trial = 0;
k = 1;
% --------------------------------------------------
% Conjugate Gradient until convergence
% --------------------------------------------------
while ~STOP
[dy,dk, x] = loopPcg(L,Lden,At,dense,d, DAt,K, r,p,ssqrNew,...
cgpars, restol);
if isempty(dy)
return
else
% ------------------------------------------------------------
% Add step from PCG-method. If P(d) is highly ill-conditioned, then
% "x=DA*dy" as returned from PCG is inaccurate, and the residual
% based on x can differ from the internal PCG residual. Therefore,
% we recompute r based on x, and refine if needed & allowed.
% ------------------------------------------------------------
k = k + dk;
y = y + dy;
dx = dx - x;
x = [sqrt(d.l).*dx(1:K.l); asmDxq(d,dx,K); psdscale(d,dx,K,1)];
r = Amul(At,dense,x);
if ~isempty(rb)
r = r+rb;
end
normr = norm(r,inf);
if normr < restol
return
elseif trial >= cgpars.refine
return
else
p = [];
trial = trial + 1; % Refine
end
end
end |
github | urbste/MLPnP_matlab_toolbox-master | tdet.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/tdet.m | 1,694 | utf_8 | 7a2fdbbae2cf6f49c63b0fbe423048b2 | % tdetx = tdet(x,K)
% TDET Computes twice determinant for Lorentz block
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function tdetx = tdet(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
if isempty(K.q)
tdetx = zeros(0,1);
else
ix = K.mainblks;
tdetx = x(ix(1):ix(2)-1).^2 - ddot(x(ix(2):ix(3)-1),x,K.qblkstart);
end |
github | urbste/MLPnP_matlab_toolbox-master | ordmmdmex.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/ordmmdmex.m | 1,271 | utf_8 | 52e36ec5ff391ea9ae94aeabe2ec625a | % perm = ordmmdmex(adjncy)
% Computes multiple-minimum-degree permutation, for sparse
% Cholesky. Adjncy is a sparse symmetric matrix; its diagonal
% is irrelevant.
%
% Invokes SPARSPAK-A Release III.
%
% ********** INTERNAL FUNCTION OF CHOLTOOL **********
function perm = ordmmdmex(adjncy)
%
% This file is part of CholTool 1.00
% Copyright (C) 1998 Jos F. Sturm
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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., 675 Mass Ave, Cambridge, MA 02139, USA.
%
error('At OS prompt, type "make" to create cholTool mex-files.') |
github | urbste/MLPnP_matlab_toolbox-master | quadadd.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/quadadd.m | 1,820 | utf_8 | c572f57ef1c018be8ff6b54d32f1f68a | % [zhi,zlo] = quadadd(xhi,xlo,y)
% QUADADD Compute (zhi+zlo) = (xhi+xlo) + y.
% x an z are in double-double format (quad precision)
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [zhi,zlo] = quadadd(xhi,xlo,y)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | vectril.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/vectril.m | 1,762 | utf_8 | 596076d71a5720b9d23f6c2af80d7169 | % y = vectril(x,K)
% VECTRIL converts "PSD" blocks to lower triangular form.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = vectril(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | partitA.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/partitA.m | 1,819 | utf_8 | ac14fb30f072acdffff699c73c39969a | % Ablkjc = partitA(At,blkstart)
% PARTITA Partition columns of A according to the subscripts listed in blkstart.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function Ablkjc = partitA(At,blkstart)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | psdinvjmul.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/psdinvjmul.m | 1,787 | utf_8 | 2f5dd1773e6936a7c8110592366f1204 | % z = psdinvjmul(xlab,xfrm, y, K)
% PSDINVJMUL solves x jmul z = y, with x = XFRM*diag(xlab)*XFRM'
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function z = psdinvjmul(xlab,xfrm, y, K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | getDAt.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/getDAt.m | 2,042 | utf_8 | 5003dccd008c5373ceb19926294a9cad | % [DAtq, DAts] = getDAt(At,Ablk,colsel, d,ud,K)
%
%Creates
% DAt.s full nnz x 1 vector, containing nonzeroblocks(T) with T a
% sparse N x length(colsel) matrix, with Ablk.s(:,colsel) block struct.
% NOTE: only triu(.) stored per block, with redundant 0's in tril.
% So triu(Ud*Aik*Ud') in nonzero block (i,k).
% DAt.q length(K.q) x m with Ablk.q sparsity structure.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [DAtq, DAts] = getDAt(At,Ablk,colsel, d,ud,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | bwdpr1.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/bwdpr1.m | 1,834 | utf_8 | 9c24d885cc3170d12fbb75ca74edecb1 | % y = bwdpr1(Lden, b)
% BWDPR1 Solves "PROD_k L(pk,betak)' * y = b", where
% L(p,beta) = eye(n) + tril(p*beta',-1).
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi, dpr1fact, fwdpr1
function y = bwdpr1(Lden, b)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | frameit.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/frameit.m | 1,599 | utf_8 | ba115a5f45db40a0d4b7b0d571b6d132 | % x = frameit(lab,frmq,frms,K)
% FRAMEIT
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function x = frameit(lab,frmq,frms,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
x = [lab(1:K.l); qframeit(lab,frmq,K); psdframeit(lab,frms,K)]; |
github | urbste/MLPnP_matlab_toolbox-master | getada1.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/getada1.m | 2,344 | utf_8 | 72456fbfce3581bef8cffe63918f52ef | % ADA = getada1(ADA, A,Ajc2,perm, d, blkstart)
% GETADA1 Compute ADA(i,j) = (D(d^2; LP,Lorentz)*A.t(:,i))' *A.t(:,j),
% and exploit sparsity as much as possible.
% Ajc2 points just beyond LP/Lorentz nonzeros for each column
% blkstart = K.qblkstart partitions into Lorentz blocks.
%
% IMPORTANT 1: only LP and sparse Lorentz part. PSD part ignored altogether.
% For Lorentz, it uses only det(dk) * ai[k]'*aj[k].
% IMPORTANT 2: Computes ADA only on triu(ADA(Aord.lqperm,Aord.lqperm)).
% Remaining entries are set to 0. (CAUTION: sparse(ADA) will therefore
% destroy the sparsity structure !).
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi, getada2, getada3
function ADA = getada1(ADA, A,Ajc2,perm, d, blkstart)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | sddir.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/sddir.m | 3,345 | utf_8 | 00ebfa573895fcf59bc790b35a0eb489 | % [dx,dy,dz,dy0, err] = sddir(L,Lden,Lsd,p,...
% d,v,vfrm,At,DAt,dense, R,K,y,y0,b, pars)
% SDDIR Direction decomposition for Ye-Todd-Mizuno self-dual embedding.
% Here, p is the direction p = dx+dz. If p=[], then assume p=-v,
% the "affine scaling" direction.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [dx,dy,dz,dy0, err] = sddir(L,Lden,Lsd,pv,...
d,v,vfrm,At,DAt,dense, R,K,y,y0,b, pars,pMode)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% ------------------------------------------------
% dy0 = v'*pv, ADp = A*D(d)*pv
% ------------------------------------------------
switch pMode,
case 1,
% Spectral values w.r.t. vfrm
dy0 = (vfrm.lab'*pv) / R.b0;
pv = frameit(pv,vfrm.q,vfrm.s,K); % Let p = VFRM * p.
case 2,
% Affine scaling
dy0 = -y0;
pv = -v;
case 3,
dy0 = (v'*pv) / R.b0;
end
% ------------------------------------------------------------
% Solve AP(d)A' * ypv = dy0 * Rb + AD(dy0*DRc - pv)
% and let xpv = (dy0*DRc - pv) - DA'*ypv.
% This yields AD*xpv = err.b-dy0*Rb.
% ------------------------------------------------------------
[dy,dx,err.kcg,err.b] = wrapPcg(L,Lden,At,dense,d, DAt,K,...
dy0*R.b, dy0*Lsd.DRc - pv, pars.cg,min(1,y0) * R.maxRb);
% ------------------------------------------------------------
% Solve denom * rdx0 = y0*(DRc'*xpv+Rb'*ypv)-(err.b'*y)
% Here, rdx0 = deltax0/x0.
% ------------------------------------------------------------
rdx0 = (y0*(Lsd.DRc'*dx+R.b'*dy) - err.b'*y) / Lsd.denom;
% ------------------------------------------------------------
% Set dy -= rdx0 * ysd
% dx = rdx0 * xsd - dx
% error dRb := rdx0 * Lsd.b - err.b
% ------------------------------------------------------------
dy = dy - rdx0 * Lsd.y;
dx = rdx0 * Lsd.x - dx; % Now, AD*dx = deltax0*b + dy0*Rb...
err.b = rdx0 * Lsd.b - err.b; % ... + err.b
err.maxb = norm(err.b,inf);
dx(1) = rdx0 * v(1);
dz = pv - dx;
|
github | urbste/MLPnP_matlab_toolbox-master | bwblkslv.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/bwblkslv.m | 1,547 | utf_8 | 8392d4a8efb4ba647f3f5059fc90edc4 | % BWBLKSLV Solves block sparse upper-triangular system.
% y = bwblkslv(L,b) yields the same result as
% y(L.perm,:) = L.L'\b
% However, BWBLKSLV is faster than the built-in operator "\",
% because it uses dense linear algebra and loop-unrolling on
% supernodes.
%
% Typical use, with X sparse m x m positive definite and b is m x n:
% L = sparchol(symbchol(X),X);
% y = bwblkslv(L,fwblkslv(L,b));
% Then y solves X*y=b.
%
% See also symbchol, fwblkslv, mldivide, mrdivide
function y = bwblkslv(L,b)
%
% This file is part of CholTool 1.00
% Copyright (C) 1998 Jos F. Sturm
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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., 675 Mass Ave, Cambridge, MA 02139, USA.
%
error('At OS prompt, type "make" to create cholTool mex-files.') |
github | urbste/MLPnP_matlab_toolbox-master | sqrtinv.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/sqrtinv.m | 1,819 | utf_8 | 1d87c91e62f09b80ad5b80563b96d812 | % y = sqrtinv(q,vlab,K)
% SQRTINV Computes for PSD-cone, y = (Q / diag(sqrt(vlab)))', so that
% Y'*Y = inv(Q * diag(vlab) * Q').
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = sqrtinv(q,vlab,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | vecsym.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/vecsym.m | 1,769 | utf_8 | 836318344fa94f06b78511242b1f98df | % y = vecsym(x,K)
% VECSYM For the PSD submatrices, we let Yk = (Xk+Xk')/2
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = vecsym(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | makereal.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/makereal.m | 1,811 | utf_8 | 2a6f23ea7781f51d1b806b9a14c7f8e3 | % y = makereal(x,K,cpx)
% MAKEREAL Converts matrix in MATLAB-complex format to internal
% SeDuMi format.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function y = makereal(x,K,cpx)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | Amul.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/Amul.m | 2,017 | utf_8 | 3aaf3bc6429b1b21f6f9c4d526ef9653 | % y = Amul(At,dense,x,transp)
% AMUL Computes A*x (transp=0) or A'*x (transp=1), taking care of dense.A.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = Amul(At,dense,x,transp)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
if nargin < 4
transp = 0;
end
if transp == 0
%Since At is sparse calculating At'*x takes a lot of time, while x'*At
%is much faster!
y = (x'*At)'; %y(m) and x(N).
else
y = full(At*x); % y(N) and x(m)
end
if length(dense.cols) > 0
if transp == 0
y = y + dense.A*x(dense.cols);
else
y = full(At*x);
y(dense.cols) = dense.A'*x;
end
end |
github | urbste/MLPnP_matlab_toolbox-master | stepdif.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/stepdif.m | 6,835 | utf_8 | 803f391d9c0c26053c444dba070d4fcf | % [t,rcdx] = stepdif(d,R,y0,x,y,z,dy0,dx,dy,dz,b,mint,tpmtd)
% STEPDIF Implements Primal-Dual Step-Differentiation for self-dual model
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [t,rcdx] = stepdif(d,R,y0,x,y,z,dy0,dx,dy,dz,b,mint,tpmtd)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% ------------------------------------------------------------
% Self-Dual Primal/Dual Step length differentiation:
% ------------------------------------------------------------
d0 = sqrt(d.l(1));
% ------------------------------------------------------------
% Compute (rdy0, rcdx) := ((dy0,cdx) - rdx0 * (y0,cx))/y0 using that
% cx - by + z0 = y0*R.sd.
% ------------------------------------------------------------
rdx0 = dx(1) / x(1);
rdy0 = dy0 / y0 - rdx0;
rcdx = full(b'*dy - rdx0*(b'*y)) - (dz(1)-rdx0*z(1))/d0;
rcdx = rdy0 * R.sd + rcdx / y0;
gap = R.b0 * y0;
if tpmtd > 0
del1 = (z'*dx) / gap;
dRg = rdx0 * R.sd + rcdx;
else
del1 = (x'*dz) / gap;
dRg = (dy0/y0) * R.sd - rcdx;
end
% ------------------------------------------------------------
% CASE Rsd > 0: gap constraint locally part of merit.
% CASE Rsd < 0: gap constraint locally not part of merit.
% ------------------------------------------------------------
usegap = (R.sd > 0) | (R.sd == 0 & dRg > 0);
if usegap
r0 = R.w(1)+R.w(2)+R.sd;
beta = (rdy0 * R.w(1) + rcdx)/ r0;
else
r0 = R.w(1)+R.w(2);
beta = rdy0 * R.w(1)/ r0;
end
% ------------------------------------------------------------
% CASE tp > td: merit is multiplied by 1 + t * (rdx0 + beta)
% CASE tp < td: merit is multiplied by 1 + t * (dy0/y0 - beta)
% ------------------------------------------------------------
if tpmtd > 0
beta = rdx0 + beta;
else
beta = (dy0/y0) - beta;
end
% ------------------------------------------------------------
% Compute the minimizer t of the local merit function
% ------------------------------------------------------------
c = 2*[beta;rdx0*del1] - (rdx0 + del1)*[1;beta];
if c(1) <= 0
% ------------------------------------------------------------
% If merit decreasing at t=0, i.e. c(1)<0, then consider t > 0
% ------------------------------------------------------------
if c(2) >= 0
t = abs(tpmtd); % merit decreasing for all feasible t>=0
else
t = min(abs(tpmtd),c(1) / c(2)); % Set derivative c(1)-t*c(2) to zero
end
else
% ------------------------------------------------------------
% If merit increasing at t=0, i.e. c(1)>0, then consider t < 0
% ------------------------------------------------------------
if c(2) >= 0
t = mint; % c(1)-t*c(2) > 0 for all feasible t<=0
else
t = max(mint,c(1) / c(2)); % Set derivative c(1)-t*c(2) to zero
end
end
% ------------------------------------------------------------
% Compute the break point, where R.sd + t*dRg = 0.
% ------------------------------------------------------------
if dRg ~= 0
tg = -R.sd / dRg;
else
tg = t; % no break point, keep optimal t
end
if tg <= 0
if t > 0
tg = t; % no positive break point, keep optimal t > 0.
end
else
if t < 0
tg = t; % break point positive, keep optimal t < 0.
end
end
% ------------------------------------------------------------
% If t beyond break point, then minimize merit for t >= tg.
% ------------------------------------------------------------
if abs(t) > abs(tg)
if usegap % Now, EXCLUDE gap for |t|>|tg|:
beta = rdy0 * R.w(1)/ r0;
alpha = 1 - R.sd / r0; % Remove contribution from Rsd
else % Now, INCLUDE gap for |t|>|tg|:
beta = (rdy0 * R.w(1) + rcdx)/ r0;
alpha = 1 + R.sd / r0; % Include contribution from Rsd
end
if tpmtd > 0
beta = rdx0*alpha + beta;
else
beta = (dy0/y0)*alpha - beta;
end
% ------------------------------------------------------------
% Compute the minimizer |t| >= |tg| of the merit function beyond tg
% ------------------------------------------------------------
c = 2*[beta;rdx0*del1] - (rdx0 + del1)*[1;beta];
% ------------------------------------------------------------
% If t >= tg >= 0:
% ------------------------------------------------------------
if t >= 0
if c'*[1;-tg] <= 0
if c(2) >= 0
t = abs(tpmtd); % c(1)-t*c(2)<=0 for all feasible t>=tg
else
t = min(abs(tpmtd),c(1) / c(2)); % Set c(1)-t*c(2) to zero
end
else
t = tg; % merit is increasing at t=tg >= 0.
end
% ------------------------------------------------------------
% If t <= tg <= 0:
% ------------------------------------------------------------
else
if c'*[1;-tg] >= 0
if c(2) >= 0
t = mint; % c(1)-t*c(2)>=0 for all feasible t<=tg
else
t = max(mint,c(1) / c(2)); % Set c(1)-t*c(2) to zero
end
else
t = tg; % merit is decreasing at t=tg <= 0.
end
end
end % |t|>|tg|
% ------------------------------------------------------------
% Observe the break-point of Rp (tpmtd>0) or Rd (tpmtd<0), where
% y0+t*dy0 = 0. Hitting this makes (P) resp. (D) feasible.
% ------------------------------------------------------------
if y0+t*dy0 <= 0
t = -y0/dy0; % For simplicity, we don't search beyond break point.
end
rcdx = y0*rcdx;
|
github | urbste/MLPnP_matlab_toolbox-master | qblkmul.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/qblkmul.m | 1,854 | utf_8 | 6d0657e21b25ab28c73f188a12897063 | % y = qblkmul(mu,d,blkstart)
% QBLKMUL yields length(y)=blkstart(end)-blkstart(1) vector with
% y[k] = mu(k) * d[k]; the blocks d[k] are partitioned by blkstart.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = qblkmul(mu,d,blkstart)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | psdjmul.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/psdjmul.m | 1,879 | utf_8 | ecb7cb8f061c366336a3f25c0fb25188 | % z = psdmul(x,y, K)
% PSDMUL for full x,y. Computes (XY+YX)/2
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function z = psdjmul(x,y, K)
%
% This file is part of SeDuMi 1.3 by Imre Polik
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
startindices=K.sblkstart;
z=zeros(K.N-startindices(1)+1,1);
Ks=K.s;
endindex=K.mainblks(end);
clear K
for k = 1:length(Ks)
Ksk=Ks(k);
startk=startindices(k);
startkp=startindices(k+1);
temp=reshape(x(startk:startkp-1),Ksk,Ksk)*reshape(y(startk:startkp-1),Ksk,Ksk);
z(startk-endindex+1:startkp-endindex)=temp+temp';
end
z=z/2; |
github | urbste/MLPnP_matlab_toolbox-master | widelen.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/widelen.m | 4,536 | utf_8 | 7ad4c5e8a463c198e9e5bc466e5c5bf2 | % [t,wr,w] = widelen(xc,zc,y0, dx,dz,dy0,d2y0, maxt,pars,K)
%
% WIDELEN Computes approximate wide-region neighborhood step length.
% Does extensive line search only if it pays, that is the resulting
% rate will be at most twice the best possible rate, and the step-length
% at least half of the best possible step length.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [t,wr,w] = widelen(xc,zc,y0, dx,dz,dy0,d2y0, maxt,pars,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
thetaSQR = pars.theta^2;
ix = K.mainblks;
% --------------------------------------------------
% For descent directions (dy0/y0 < 0), let fullt be
% s.t. y0 + fullt * dy0 + fullt^2 * min(d2y0,0) = 0 (NB: y0 is duality gap)
% This is used to compute the desired accuracy in t (when rate -> 0).
% --------------------------------------------------
if dy0 < -1E-5 * y0
if d2y0 < 0 % Concave decreasing: gap(fullt) < 0 where y0+fullt*dy0=0.
fullt = 2 * y0 /(-dy0 + sqrt(dy0^2 - 4*y0*d2y0)); % < y0/abs(dy0).
else
fullt = y0 / (-dy0);
end
if fullt <= 0
error('Assertion failed: fullt <= 0')
end
else
fullt = 2*maxt;
end
tR = min(maxt, fullt);
if tR < 0
error('Assertion failed: tR >= 0')
end
% ------------------------------------------------------------
% rate = (y0+t*dy0)/y0 = 1 - (t/fullt) = (fullt - t)/fullt.
% It can never be better than (fullt - tR)/fullt.
% The next criterion ensures that we're never worse than twice best rate'
% ------------------------------------------------------------
t = 0.0;
ntry = 0; % do loop at least once
while (t < 0.5 * tR) | ( (fullt-tR) + (1e-7 * fullt) < (tR - t) ) | ntry==0
ntry = 1;
if tR == maxt % Bisection
tM = 0.1 * t + 0.9 * tR;
else
tM = 0.5 * (t + tR);
end
xM = xc + tM*dx;
zM = zc + tM*dz;
% --------------------------------------------------
% Let w = D(xM)*zM, compute lambda(w).
% --------------------------------------------------
% LORENTZ
wM.tdetx = tdet(xM,K);
wM.tdetz = tdet(zM,K);
detxz = wM.tdetx .* wM.tdetz / 4;
if isempty(K.q)
lab2q = zeros(0,1);
else
halfxz = (xM(ix(1):ix(2)-1).*zM(ix(1):ix(2)-1)...
+ ddot(xM(ix(2):ix(3)-1),zM,K.qblkstart)) / 2;
tmp = halfxz.^2 - detxz;
if tmp > 0
lab2q = halfxz + sqrt(tmp);
else
lab2q = halfxz;
end
end
% PSD
wM.ux = psdfactor(xM,K);
wM.s = psdscale(wM.ux,zM,K);
% ALL:
wM.lab = [xM(1:K.l).*zM(1:K.l); detxz ./ lab2q; lab2q; psdeig(wM.s,K)];
[deltaM,hM,alphaM] = iswnbr(wM.lab, thetaSQR);
if (deltaM <= pars.beta) | ((tM < fullt / 10) & (deltaM < 1))
w = wM;
t = tM;
wr.h=hM;
wr.alpha=alphaM;
wr.delta=deltaM;
else
tR = tM;
end
end
% ------------------------------------------------------------
% In the nasty case that we could not make any progress, (t=0),
% take last middle value.
% ------------------------------------------------------------
if t == 0
w = wM;
t = tM;
wr.h=hM;
wr.alpha=alphaM;
wr.delta=deltaM;
end
wr.desc = 1; % always descent direction. |
github | urbste/MLPnP_matlab_toolbox-master | psdeig.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/psdeig.m | 2,542 | utf_8 | bc17e014fe3b156a7abb2d2def46cf81 | % [lab,q] = psdeig(x,K)
% PSDEIG Computes spectral coefficients of x w.r.t. K
% Arguments "q" is optional - without it's considerably faster.
% FLOPS indication: 1.3 nk^3 versus 9.0 nk^3 for nk=500,
% 1.5 nk^3 9.8 nk^3 for nk=50.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [lab,q] = psdeig(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
Ks=K.s;
if isempty(Ks)
lab=[];
return
end
lab(sum(Ks),1)=0;
startindices=K.sblkstart-K.mainblks(end)+1;
labindices=cumsum([1,Ks]);
ncones=length(Ks);
if nargout==1
%only eigenvalues are needed, not eigenvectors
for k = 1:ncones
Xk = reshape(x(startindices(k):startindices(k+1)-1),Ks(k),Ks(k));
lab(labindices(k):labindices(k+1)-1) = eig(Xk + Xk');
end
else
%eigenvalues and eigenvectors
q=zeros(sum(Ks.^2),1);
for k = 1:ncones
Xk = reshape(x(startindices(k):startindices(k+1)-1),Ks(k),Ks(k));
[q(startindices(k):startindices(k+1)-1), temp] = eig(Xk + Xk');
lab(labindices(k):labindices(k+1)-1)=diag(temp);
end
end
%We actually got the eigenvalues of twice the matrices, so we need to scale
%them back.
lab=lab/2;
|
github | urbste/MLPnP_matlab_toolbox-master | sdfactor.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/sdfactor.m | 2,631 | utf_8 | e62701908298cc22d28d0d80e71a8eda | % [Lsd,Rscl] = sdfactor(L,Lden, dense,DAt, d,v,y, At,K,R,y0,pars)
% SDFACTOR Factor self-dual embedding
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function Lsd = sdfactor(L,Lden, dense,DAt, d,v,y, At,c,K,R,y0,pars)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% ------------------------------------------------------------
% Compute D*Rc
% ------------------------------------------------------------
Lsd.DRc = [sqrt(d.l).*R.c(1:K.l); asmDxq(d,R.c,K); psdscale(d,R.c,K)];
% ------------------------------------------------------------
% Solve AP(d)A' * ysd = y0*Rb + AD(y0*DRc-2v)
% and let xsd = (y0*DRc-2v) - DA'*ysd.
% ------------------------------------------------------------
[Lsd.y,Lsd.x,Lsd.kcg,Lsd.b] = wrapPcg(L,Lden,At,dense,d, DAt,K, y0*R.b,...
y0*Lsd.DRc - 2*v, pars.cg, min(1,y0)*R.maxRb);
% ------------------------------------------------------------
% Now let ysd -= y and xsd += v.
% It follows then that AD*xsd = x0 * b + Lsd.b, where Lsd.b = numerical error.
% ------------------------------------------------------------
Lsd.y = Lsd.y - y;
Lsd.x = Lsd.x + v;
% ------------------------------------------------------------
% Compute denom = norm(xsd)^2
% ------------------------------------------------------------
Lsd.denom = norm(Lsd.x)^2 + Lsd.b'*Lsd.y; |
github | urbste/MLPnP_matlab_toolbox-master | maxstep.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/maxstep.m | 2,654 | utf_8 | db3c75d25c32a5a7d4faacb1fec04a1a | % tp = maxstep(dx,x,auxx,K)
% MAXSTEP Computes maximal step length to the boundary of the cone K.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function tp = maxstep(dx,x,auxx,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% ------------------------------------------------------------
% LP:
% ------------------------------------------------------------
mindx = min(dx(1:K.l) ./ x(1:K.l));
% ------------------------------------------------------------
% Lorentz: compute min(eig(y)) with y:=D(x)\dx. We have
% lab1+lab2 = tr y = x'Jdx / detx, and
% (lab2-lab1)^2 = (tr y)^2 - 4 det y = [(x'Jdx)^2 - tdetx*tdetdx] / detx^2
% ------------------------------------------------------------
if ~isempty(K.q)
ix = K.mainblks;
reltr = x(ix(1):ix(2)-1).*dx(ix(1):ix(2)-1)...
- ddot(x(ix(2):ix(3)-1),dx,K.qblkstart);
norm2 = reltr.^2 - tdet(dx,K).*auxx.tdet;
if norm2 > 0
norm2 = sqrt(norm2);
end
mindxq = min( (reltr - norm2)./auxx.tdet);
mindx = min(mindx, mindxq);
end
% ------------------------------------------------------------
% PSD:
% ------------------------------------------------------------
if ~isempty(K.s)
reldx = psdinvscale(auxx.u, dx,K);
mindxs = minpsdeig(reldx, K);
mindx = min(mindx, mindxs);
end
tp = 1 / max(-mindx, 1E-16); |
github | urbste/MLPnP_matlab_toolbox-master | getada3.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/getada3.m | 2,058 | utf_8 | d49bb1a28bf96a590093e290a6d3a67d | % [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K)
% GETADA3 Compute ADA(i,j) = (D(d^2)*A.t(:,i))' *A.t(:,j),
% and exploit sparsity as much as possible.
% absd - length m output vector, containing
% absd(i) = abs((D(d^2)*A.t(:,i))' *abs(A.t(:,i)).
% Hence, diag(ADA)./absd gives a measure of cancelation (in [0,1]).
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi, getada1, getada2
function [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | mat.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/mat.m | 1,783 | utf_8 | b49140ac21c615f717adf5867e9c6906 | % Y = MAT(x,n) or Y = MAT(x) (the 2nd argument is optional)
% Given a vector of length n^2, this produces the n x n matrix
% Y such that x = vec(Y). In other words, x contains the columns of the
% matrix Y, stacked below each other.
%
% See also vec.
function X = mat(x,n)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
if nargin < 2
n = floor(sqrt(length(x)));
if (n*n) ~= length(x)
error('Argument X has to be a square matrix')
end
end
X = reshape(x,n,n); |
github | urbste/MLPnP_matlab_toolbox-master | blkchol.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/blkchol.m | 2,546 | utf_8 | c68bccd002bc901358fe00cd2e2c0720 | % [L.L, L.d, L.skip, L.add] = blkchol(L,X,pars,absd)
% BLKCHOL Fast block sparse Cholesky factorization.
% The sparse Cholesky factor will be placed in the fields L.L, L.d;
% the symbolic factorization fields remain unchanged.
% On input, L should be the symbolic factorization structure of X,
% as created by SYMBCHOL.
% Performs LDL' factorization of X(L.perm,L.perm).
%
% There are important differences with CHOL(X(L.perm,L.perm))':
%
% - BLKCHOL uses the supernodal partition L.XSUPER,
% to use dense linear algebra on dense subblocks.
% This explains the performance benefit of BLKCHOL over CHOL.
%
% - BLKCHOL never fails.
%
% - To solve "X*y = b", use
% >> [L.L,L.d,L.skip,L.add] = blkchol(symbchol(X),X);
% >> L.d(find(L.skip)) = inf;
% >> y = sparbwslv(L, sparfwslv(L,b) ./ L.d);
%
% For numerical reasons, "blkchol" may skip unstable pivots,
% or add on the diagonal. Such pivots are then listed in L.{skip,add}.
%
% See also symbchol, sparfwslv, sparbwslv, [symbfact, symmmd, chol].
function [L.L, L.d, L.skip, L.add] = blkchol(L,X,pars,absd)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
error('Build the SeDuMi binaries by typing make at the command prompt.'); |
github | urbste/MLPnP_matlab_toolbox-master | psdfactor.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/psdfactor.m | 2,394 | utf_8 | 4b39d3f804a5c6dd20d084a82c1a41e3 | % [ux,ispos] = psdfactor(x,K)
% PSDFACTOR UX'*UX Cholesky factorization
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function [ux,ispos] = psdfactor(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% disp('The SeDuMi binaries are not installed.')
% disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
% disp('For more information see the file Install.txt.')
% error(' ')
Ks=K.s;
N=sum(Ks.^2);
ux=zeros(N,1);
ispos=true;
startindices=K.sblkstart-K.mainblks(end)+1;
%Sometimes x containts only the PSD part, sometimes the whole thing
xstartindices=startindices+(length(x)-N);
for i=1:K.rsdpN
[temp, flag]=chol(reshape(x(xstartindices(i):xstartindices(i+1)-1),Ks(i),Ks(i)),'lower');
if ~flag
%The matrix is PD
ux(startindices(i):startindices(i+1)-1)=(temp+tril(temp,-1)');
% TODO This could be made a bit faster
else
%The matrix is not PD, stop immediately.
ispos=false;
break
end
end
%TODO: Check if the matrices are ever sparse. |
github | urbste/MLPnP_matlab_toolbox-master | adendotd.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/adendotd.m | 1,833 | utf_8 | e21167ad58997c4f3bdd86d2433972f2 | % Ad = Adendotd(dense, d, sparAd, Ablk, blkstart)
% ADENDOTD Computes d[k]'*Aj[k] for Lorentz blocks that are to be factored
% by dpr1fact.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function Ad = Adendotd(dense, d, sparAd, Ablk, blkstart)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | qjmul.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/qjmul.m | 2,476 | utf_8 | e434772ee132e40b3ab58f68111dd18d | % z = qjmul(x,y,K)
% QJMUL Implements Jordan product for Lorentz cones
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function z = qjmul(x,y,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
if isempty(K.q)
z = zeros(0,1);
else
% ------------------------------------------------------------
% Let i1, i2 such that x(i1:i2-1) = "x1", i.e. Lorentz trace part.
% ------------------------------------------------------------
if length(x) ~= length(y)
error('x,y size mismatch');
end
ix = K.mainblks;
if length(x) < K.lq % Only q-part given?
ix = (1-ix(1)) + ix;
if length(x) ~= length(y)
error('x, y size mismatch')
end
end
% ------------------------------------------------------------
% Let z1 = x'*y/sqrt2, z2 = (x1*y2+y1*x2)/sqrt2
% ------------------------------------------------------------
z1 = x(ix(1):ix(2)-1).*y(ix(1):ix(2)-1)...
+ ddot(x(ix(2):ix(3)-1),y,K.qblkstart);
z = [z1; qblkmul(x(ix(1):ix(2)-1),y,K.qblkstart)...
+ qblkmul(y(ix(1):ix(2)-1),x,K.qblkstart)] / sqrt(2);
end |
github | urbste/MLPnP_matlab_toolbox-master | wregion.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/wregion.m | 8,078 | utf_8 | ce92b33341db85f802e7d9e5cd2a69d7 | % [xscl,y,zscl,y0, w,relt, dxmdz,err, wr] = wregion(L,Lden,Lsd,...
% d,v,vfrm,A,DAt,dense, R,K,y,y0,b, pars, wr)
% WREGION Implements Sturm-Zhang Wide-region Interior Point Method.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function [xscl,y,zscl,y0, w,relt, dxmdz,err, wr] = ...
wregion(L,Lden,Lsd,d,v,vfrm,A,DAt,dense, R,K,y,y0,b, pars, wr)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
STOP = 0;
n = length(vfrm.lab);
% ----------------------------------------
% INITIAL CENTERING
% ----------------------------------------
if wr.delta > 0.0 % initial centering needed ?
vTAR = (1-wr.alpha) * max(wr.h,vfrm.lab);
pv = 2*(vTAR-vfrm.lab);
pMode = 1;
[dx, dy, dz, dy0, errc] = sddir(L,Lden,Lsd,pv,...
d,v,vfrm,A,DAt,dense, R,K,y,y0,b, pars,pMode);
% ------------------------------------------------------------
% Take initial centering step
% ------------------------------------------------------------
xc = v + dx; %scaled
zc = v + dz;
yc = y + dy;
y0c = y0+dy0;
uxc.tdet = tdet(xc,K);
uzc.tdet = tdet(zc,K);
[uxc.u,xispos] = psdfactor(xc,K);
[uzc.u,zispos] = psdfactor(zc,K);
critval = max(y0, sqrt(min(d.l(1),1/d.l(1)))*v(1)); % >= y0
critval = max(1E-3, pars.cg.restol) * critval * R.maxRb;
if (~xispos) | (~zispos) | (errc.maxb > critval) ...
| ( (~isempty(uxc.tdet)) & (min(uxc.tdet) <= 0.0)) ...
| ( (~isempty(uzc.tdet)) & (min(uzc.tdet) <= 0.0))
STOP = -1; % Reject and terminate
dxmdz = [];
err = errc;
end
pv = -vTAR;
else
vTAR = vfrm.lab;
xc = v; % No initial centering needed.
ix = K.mainblks;
uxc.tdet = 2*vfrm.lab(ix(1):ix(2)-1) .* vfrm.lab(ix(2):2*ix(2)-ix(1)-1);
[uxc.u] = psdfactor(xc,K);
zc = v; uzc = uxc; %zscl=xscl=v
yc = y;
y0c = y0;
errc.b = sparse(length(y),1);
errc.maxb = 0; errc.db0 = 0;
pv = []; % Means pv = -v, the predictor direction.
pMode = 2;
end
% ----------------------------------------
% PREDICTOR
% ----------------------------------------
if STOP ~= -1
[dx,dy,dz,dy0, err] = sddir(L,Lden,Lsd,pv,...
d,v,vfrm,A,DAt,dense, R,K,y,y0,b, pars,pMode);
dxmdz = dx-dz;
if (pars.alg ~= 0)
pMode = 3;
gd1 = [dxmdz(1:K.l)./vTAR(1:K.l);qinvjmul(vTAR,vfrm.q,dxmdz, K);...
psdinvjmul(vTAR,vfrm.s,dxmdz, K)];
maxt1 = min(maxstep(dx,xc,uxc,K), maxstep(dz,zc,uzc,K));
% ----------------------------------------
% 2ND ORDER CORRECTOR
% alg == 1 : 2nd order expansion of v = sqrt(eig(D(x)z)), like Sturm-Zhang.
% alg == 2 : 2nd order expansion of vsqr = eig(D(x)z), like Mehrotra.
% ----------------------------------------
switch pars.alg
case 1 % alg 1: v-expansion
tTAR = 1-(1-maxt1);
pv = tTAR^2*[gd1(1:K.l).*dxmdz(1:K.l); qjmul(gd1,dxmdz,K);...
psdjmul(gd1,dxmdz,K)];
pv2 = 2*tTAR*(1-tTAR)*((sum(vTAR)/n)*ones(n,1) - vTAR) -(2*tTAR)*vTAR;
case 2 % alg 2: v^2, like Mehrotra.
tTAR = 1-(1-maxt1)^3;
pv = (tTAR / 4) * [gd1(1:K.l).*dxmdz(1:K.l); qjmul(gd1,dxmdz,K);...
psdjmul(gd1,dxmdz,K)];
pv2 = ((1-tTAR)*tTAR*R.b0*y0/n)./vTAR - (1+tTAR/4)*vTAR;
end
pv = pv + frameit(pv2, vfrm.q, vfrm.s, K);
[dx,dy,dz,dy0, err] = sddir(L,Lden,Lsd,pv,...
d,v,vfrm,A,DAt,dense, R,K,y,y0,b, pars,pMode);
end
% ----------------------------------------
% The steplength should be such that
% y0(t) * maxRb + t*errb <= (1+phi*t*|dy0/y0|) * y0(t)*maxRb
% i.e. errb <= phi*(-dy0) * (1+t*dy0/y0) * maxRb
% ----------------------------------------
PHI = 0.5;
if dy0 < 0 & (PHI*dy0^2*R.maxRb)~=0
critval = - (PHI * dy0*R.maxRb + err.maxb)*y0c / (PHI*dy0^2*R.maxRb);
else
critval = 1;
end
if critval <= 0
STOP = -1;
else
% ----------------------------------------
% Compute boundary step length "maxt".
% ----------------------------------------
tp = maxstep(dx,xc,uxc,K);
td = maxstep(dz,zc,uzc,K);
if dy0 < 0 % keep (t/y0Next)*errmaxb <= R.maxRb.
tp = min(tp,critval);
end
if xc(1)+ td * dx(1) < 0 % Cannot step beyond x0=0.
td = xc(1) / (-dx(1));
end
maxt = min(tp,td);
% ----------------------------------------
% CREGION NBRHD STEP OF PRED+COR
% ----------------------------------------
[t,wr,w] = widelen(xc,zc,y0c, dx,dz,dy0,0, maxt,pars,K);
% ----------------------------------------
% Take step (in scaled space)
% ----------------------------------------
xscl = xc + t*dx;
y = yc + t*dy;
zscl = zc + t*dz;
y0 = y0c + t*dy0;
if pars.stepdif == 1
[tdif,rcdx]=stepdif(d,R,y0,xscl,y,zscl,dy0,dx,dy,dz,b,-t,tp-td);
if tdif ~= 0
rdx0 = dx(1) / xscl(1);
mu = 1+tdif*rdx0;
if tp > td
newx = xscl + tdif*dx;
newz = mu*zscl;
else
newx = mu*xscl;
newz = zscl+tdif*dz;
end
[tdif,wr,w] = trydif(tdif,wr,w, newx,newz,pars,K);
end
else
tdif = 0;
end
if tdif ~= 0
rdy0 = dy0 - rdx0 * y0;
zscl = newz;
xscl = newx;
if tp > td
y = mu*y;
y0 = mu*y0;
err.b = (tdif*rdy0) * R.b + errc.b + (t+tdif) * err.b;
err.g = tdif * rcdx;
relt.p = (t+tdif)/tp;
relt.d = t/td;
else % td > tp
y = y + tdif * dy;
y0 = y0 + tdif * dy0;
err.b = -(tdif*rdy0)*R.b + mu*(errc.b + t * err.b);
err.g = -tdif * rcdx;
relt.p = t/tp;
relt.d = (t+tdif)/td;
end
else
err.b = errc.b + t * err.b;
err.g = 0;
relt.p = t / maxt;
relt.d = relt.p;
end
wr.tpmtd = tp-td;
err.maxb = (errc.maxb + t*err.maxb); % to be divided by y0
err.db0 = xscl'*zscl - y0*R.b0; % to be divided by y0
end % critval > 0
end % STOP ~= -1
if STOP == -1
relt.p = 0;
relt.d = 0;
w = [];
xscl = [];
zscl = [];
err.b=zeros(size(b));
err.db0 = 0;
err.g = 0;
end
|
github | urbste/MLPnP_matlab_toolbox-master | ddot.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/ddot.m | 2,037 | utf_8 | 84d2f349adf12e8af949276642e7f8b7 | % ddotX = ddot(d,X,blkstart [, Xblkjc])
% DDOT Given N x m matrix X, creates (blkstart(end)-blkstart(1)) x m matrix
% ddotX, having entries d[i]'* xj[i] for each (Lorentz norm bound) block
% blkstart(i):blkstart(i+1)-1. If X is sparse, then Xblkjc(:,2:3) should
% point to first and 1-beyond-last nonzero in blkstart range for each column.
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi, partitA
function ddotX = ddot(d,X,blkstart, Xblkjc)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | getdense.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/getdense.m | 4,750 | utf_8 | 148ac691260be32d5670b2a037c94119 | % [dense,Adotdden] = getdense(At,Ablkjc,K,pars)
% GETDENSE Creates dense.{l,cols,q}.
% Try to find small proportion of the cone primitives that appear
% in a large proportion of the primal constraints.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi
function [dense,Adotdden] = getdense(At,Ablkjc,K,pars)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
% ------------------------------------------------------------
% Initialize: colnz = #nz-constraints per LP/LOR variable,
% h = MAX(5, max{#nz-constraints | PSD-blocks})
% "5" is taken as a number that should not be beyond the denq-quantile.
% ------------------------------------------------------------
NORMDEN = 5;
colnz = sum(spones(extractA(At,Ablkjc,0,3,1,K.lq+1)),2);
h = max([NORMDEN; sum(findblks(At,Ablkjc,3,[],K.sblkstart),2)]);
[N,m] = size(At);
% ------------------------------------------------------------
% Replace colnz-entries for the Lorentz-trace ("x1") variables by
% nnz-constraints for that Lorentz block. Namely, these variables
% must be removed if the Lorentz block (d[k]*d[k]'*a[k]) is removed.
% ------------------------------------------------------------
i1 = K.mainblks(1); i2 = K.mainblks(2); % Bounds Lorentz trace.
Ablkq = extractA(At,Ablkjc,1,2,i1,i2);
if i1 < i2 % MATLAB 5.0, 5.1 cannot handle spones(empty)
Ablkq2 = findblks(At,Ablkjc,2,3,K.qblkstart); % Tag if any nonzero in block
Ablkq = spones(spones(Ablkq) + Ablkq2);
colnz(i1:i2-1) = sum(Ablkq,2); % And store at Lorentz trace pos.
end
% ------------------------------------------------------------
% FIND THE denq-quantile for DENSE COLUMNS:
% If e.g. pars.denq = 0.75 and pars.denf = 20:
% Find 75% quantile spquant. anything denser than 20*spquant is
% tagged as dense.
% NB: spquant is chosen such that all columns with nnz <= h are to left of it.
% This is because we don't allow PSD-block removal.
% ------------------------------------------------------------
bigcolnz = colnz(colnz > h); % h must be left anyhow
denqN = ceil(pars.denq * length(colnz)) - (N-length(bigcolnz));
if denqN < 1 % denqN is quantile on 1:length(bigcolnz) basis
spquant = h; % Take h as threshold
else
ordnzs = sort(bigcolnz);
spquant = ordnzs(denqN); % Take spquant > h as threshold
end
% ------------------------------------------------------------
% Find LP cols, LORENTZ cols, and LORENTZ blocks with >denf*spquant nzs
% ------------------------------------------------------------
dense.cols = find(colnz > pars.denf * spquant); %dense LP, Q-blk, Q-cols
dense.q = find(colnz(i1:i2-1) > pars.denf * spquant); %dense Q-blks
dense.l = length(find(dense.cols < i1)); %#dense LP cols.
% ----------------------------------------
% The number of dense columns should be small relative to
% the number of constraints - otherwise we better do 1 full Chol.
% ----------------------------------------
if length(dense.cols) > m / 2;
dense.l = 0; dense.cols = []; dense.q = [];
end
if isempty(dense.q)
Adotdden = sparse(m,0); % = Ablkq(dense.q,:)' block struct.
else
% --------------------------------------------------
% HANDLE DENSE LORENTZ BLOCKS
% Let Adotdden lists the nz-constraints for each dense q-block.
% --------------------------------------------------
Adotdden = Ablkq(dense.q,:)';
end |
github | urbste/MLPnP_matlab_toolbox-master | givensrot.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/givensrot.m | 1,725 | utf_8 | 9208cb8125b4fadfb9abc085d8b315db | % y = givensrot(gjc,g,x,K)
% GIVENSROT
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi
function y = givensrot(gjc,g,x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ') |
github | urbste/MLPnP_matlab_toolbox-master | sparbwslv.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/sparbwslv.m | 1,987 | utf_8 | ddbdea0707b9d46c24cbca973a60de5f | % SPARBWSLV Solves block sparse upper-triangular system.
% y = sparbwslv(L,b) yields the same result as
% y(L.perm,:) = L.L'\b
% However, SPARBWSLV is faster than the built-in operator "\",
% because it uses dense linear algebra and loop-unrolling on
% supernodes.
%
% Typical use, with X sparse m x m positive definite and b is m x n:
% L = sparchol(symbchol(X),X);
% L.d(L.dep) = inf;
% y = sparbwslv(L,sparfwslv(L,b) ./ L.d);
% Then y solves X*y=b.
%
% See also symbchol, sparchol, sparfwslv, mldivide, mrdivide.
function y = sparbwslv(L,b)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
y = bwblkslv(L,b);
%y(L.perm,:) = L.L'\b; |
github | urbste/MLPnP_matlab_toolbox-master | cellK.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/cellK.m | 3,487 | utf_8 | 4fc2753dbba84d2e10c5a8ff4e7def27 | % xcell = cellK(x,K)
% CELLK Stores SeDuMi cone K-vector in cell-array format.
%
% On output xcell.f and xcell.l are the free and >=0 components,
% xcell.q{k}, xcell.r{k} and xcell.s{k} contain the Lorentz,
% Rotated Lorentz, and PSD-components, resp.
% xcell.s{k} is a K.s(k) x K.s(k) matrix.
%
% See also eigK, eyeK, sedumi.
function xcell = cellK(x,K)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
% Remark: the cell-array scheme is inspired by SDPT3.
% Unlike in SDPT3 though, the cells are grouped in
% fields like xcell.q and xcell.s.
if nargin < 2
error('cellK needs 2 input arguments')
end
if ~isstruct(K)
error('K should be a structure')
end
i = 1;
if isfield(K,'f')
xcell.f = x(i:i+K.f-1);
i = i + K.f;
end
if isfield(K,'l')
xcell.l = x(i:i+K.l-1);
i = i + K.l;
end
% ------------------------------------------------------------
% Lorentz: this only works OUTSIDE sedumi, not for internal storage
% ------------------------------------------------------------
if isfield(K,'q')
for k = 1: length(K.q)
xcell.q{k} = x(i:i+K.q(k)-1);
i = i + K.q(k);
end
end
if isfield(K,'r')
for k = 1: length(K.r)
xcell.r{k} = x(i:i+K.r(k)-1);
i = i + K.r(k);
end
end
% ------------------------------------------------------------
% PSD-blocks:
% ------------------------------------------------------------
if isfield(K,'s')
if ~isfield(K,'rsdpN')
for k = 1: length(K.s)
xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
i = i + K.s(k)^2;
end
else
% ------------------------------------------------------------
% Only applicable for internal storage: complex-as-real-storage
% ------------------------------------------------------------
for k = 1: K.rsdpN
xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
i = i + K.s(k)^2;
end
j = sqrt(-1);
for k = K.rsdpN+1:length(K.s)
xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
i = i + K.s(k)^2;
xcell.s{k} = xcell.s{k} + j * mat(x(i:i+K.s(k)^2-1));
i = i + K.s(k)^2;
end
end
end |
github | urbste/MLPnP_matlab_toolbox-master | prelp.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/prelp.m | 3,778 | utf_8 | 90dcf5c14b1c6445ecad52fc904fd1ec | % PRELP Loads and preprocesses LP from an MPS file.
%
% > [A,b,c,lenx,lbounds] = PRELP('problemname')
% The above command results in an LP in standard form,
% - Instead of specifying the problemname, you can also use PRELP([]), to
% get the problem from the file /tmp/default.mat.
% - Also, you may type PRELP without any input arguments, and get prompted
% for a name.
%
% MINIMIZE c'*x SUCH THAT A*x = b AND x>= 0.
%
% So, you can solve it with SeDuMi:
% > [x,y,info] = SEDUMI(A,b,c);
%
% After solving, post-process it with
% > [x,objp] = POSTPROCESS(x(1:lenx),lbounds).
%
% REMARK x(lenx+1:length(x)) will contain upper-bound slacks.
%
% IMPORTANT works only if LIPSOL is installed on your system.
%
% See also sedumi, getproblem, postprocess (LIPSOL), frompack, lipsol.
function [A,b,c,lenx,lbounds] = prelp(pname)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
global OUTFID
global Ubounds_exist
if ~exist('loadata','file') | ~exist('preprocess','file')
error('To use PRELP, you need to have LIPSOL installed.')
end
%--------------------------------------------------
% LOAD LP PROBLEM INTO MEMORY
%--------------------------------------------------
if (nargin == 0)
pname = input('Enter problem name: ','s');
end
t0 = cputime;
[A,b,c,lbounds,ubounds,BIG,NAME] = loadata(pname);
times(1) = cputime - t0;
%--------------------------------------------------
% PREPROCESS LP PROBLEM
% NB: Y.Zhang's preprocess returns lbounds for post-
% processing; the pre-processed problem has x>=0.
%--------------------------------------------------
t0 = cputime;
[A,b,c,lbounds,ubounds,FEASIBLE] = ...
preprocess(A,b,c,lbounds,ubounds,BIG);
if ~FEASIBLE
fprintf('\n');
if isempty(OUTFID)
return;
end;
msginf = 'Infeasibility detected in preprocessing';
fprintf(OUTFID, [pname ' 0 ' msginf '\n']);
return;
end;
%[A,b,c,ubounds] = scaling(A,b,c,ubounds);
%--------------------------------------------------
% INSERT UBOUND- CONSTRAINTS IN THE A-MATRIX
%--------------------------------------------------
b = full(b); c = full(c);
[m,lenx] = size(A);
if Ubounds_exist
nub = nnz(ubounds);
A= [ A sparse(m,nub); sparse(1:nub,find(ubounds),1,nub,lenx) speye(nub) ];
b = [b; nonzeros(ubounds)];
c = [c; zeros(nub,1)];
else
ubounds = [];
end
%--------------------------------------------------
% LOCATE DENSE COLUMNS
%--------------------------------------------------
%checkdense(A);
times(2) = cputime - t0;
|
github | urbste/MLPnP_matlab_toolbox-master | feasreal.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/feasreal.m | 4,144 | utf_8 | 454dcb6c42c0642ed5c5a524e84bec58 | % FEASREAL Generates a random sparse optimization problem with
% linear, quadratic and semi-definite constraints. Output
% can be used by SEDUMI. All data will be real-valued.
%
% The following two lines are typical:
% > [AT,B,C,K] = FEASREAL;
% > [X,Y,INFO] = SEDUMI(AT,B,C,K);
%
% An extended version is:
% > [AT,B,C,K] = FEASREAL(m,lpN,lorL,rconeL,sdpL,denfac)
%
% SEE ALSO sedumi AND feascpx.
function [At,b,c,K] = feasreal(m,nLP,qL,rL,nL,denfac)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
if nargin < 6
denfac = 0.1;
if nargin < 5
nL = 1+ round(7*rand(1,5));
fprintf('Choosing random SDP-product cone K.s.\n')
if nargin < 4
rL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ R-product cone K.r.\n')
if nargin < 3
qL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ-product cone K.q.\n')
if(nargin < 2)
nLP = 10;
fprintf('Choosing default K.l=%3.0f.\n',nLP)
if nargin < 1
m=10;
fprintf('Choosing default m=%3.0f.\n',m)
end
end
end
end
end
end
if isempty(nLP)
nLP = 0;
end
nblk = length(nL) + length(rL) + length(qL) + nLP;
denfac = min(1, max(denfac,2/nblk));
fprintf('Choosing block density denfac=%6.4f per row\n',denfac)
Apattern=sparse(m,nblk);
for j=1:m
pati = sprandn(1,nblk,denfac);
Apattern(j,:) = (pati~= 0);
end
sumnLsqr = sum(nL.^2);
x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1);
x(1:nLP) = rand(nLP,1);
At = sparse(length(x),m);
At(1:nLP,:) = sprandn(Apattern(:,1:nLP)');
firstk = nLP+1;
%[nA, mA] = size(At);
% LORENTZ:
for k=1:length(qL)
nk = qL(k); lastk = firstk + nk - 1;
x(firstk) = rand;
for j=1:m
if Apattern(j,nLP+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk));
end
end
firstk = lastk + 1;
end
% RCONE (Rotated Lorentz):
for k=1:length(rL)
nk = rL(k); lastk = firstk + nk - 1;
x(firstk) = rand; x(firstk+1) = rand;
for j=1:m
if Apattern(j,nLP+length(qL)+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk));
end
end
firstk = lastk + 1;
end
% SDP:
for k=1:length(nL)
nk = nL(k); lastk = firstk + nk*nk - 1;
Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure
x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts.
for j=1:m
if Apattern(j,nLP+length(qL)+length(rL)+k)==1
Aik = sprandsym(nk,1/nk); %on average 1 nonzero per row
At(firstk:lastk,j) = vec( (Aik+Aik') );
end
end
firstk = lastk + 1;
end
b = full(At'*x);
y = rand(m,1)-0.5;
c = sparse(At*y)+x;
K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
|
github | urbste/MLPnP_matlab_toolbox-master | sdpa2vec.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/sdpa2vec.m | 2,352 | utf_8 | f055b4df357f6cf3b426ce27869bc738 | % x = sdpavec(E,K)
% Takes an SDPA type sparse data description E, i.e.
% E(1,:) = block, E(2,:) = row, E(3,:) = column, E(4,:) = entry,
% and transforms it into a "long" vector, with vectorized matrices for
% each block stacked under each other. The size of each matrix block
% is given in the field K.s.
% ********** INTERNAL FUNCTION OF SEDUMI **********
function x = sdpa2vec(E,K,invperm)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA %
% ------------------------------------------------------------
% Split E into blocks E[1], E[2], ..., E[length(K.s)]
% ------------------------------------------------------------
[xir,xjc] = sdpasplit(E(1,:),length(K.s));
x = sparse([],[],[],0,0,2*size(E,2));
for knz = 1:length(xir)
permk = xir(knz);
k = invperm(permk);
if k > K.l
k = k - K.l; % matrix
nk = K.s(k);
Ek = E(2:4,xjc(knz):xjc(knz+1)-1);
Xk = sparse(Ek(1,:),Ek(2,:),Ek(3,:),nk,nk);
Xk = Xk + triu(Xk,1)';
x=[x;Xk(:)];
else
x=[x;E(4,xjc(knz))];
end
end
|
github | urbste/MLPnP_matlab_toolbox-master | blk2vec.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/blk2vec.m | 1,653 | utf_8 | 0d48b96f66e746fce480e7a3e9c271a5 | % x = blk2vec(X,nL)
%
% Converts a block diagonal matrix into a vector.
%
% ********** INTERNAL FUNCTION OF FROMPACK **********
function x = blk2vec(X,nL)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA %
nblk = length(nL);
sumnk = 0;
x = [];
for k = 1:nblk
nk = nL(k);
x = [x; vec(X(sumnk+1:sumnk + nk,sumnk+1:sumnk + nk))] ;
sumnk = sumnk + nk;
end
|
github | urbste/MLPnP_matlab_toolbox-master | writesdp.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/writesdp.m | 4,727 | utf_8 | 7ee3825bacdd560c93d4b6b930c5796f | % This function takes a problem in SeDuMi MATLAB format and writes it out
% in SDPpack format.
%
% Usage:
%
% writesdp(fname,A,b,c,K)
%
% fname Name of SDPpack file, in quotes
% A,b,c,K Problem in SeDuMi form
%
% Notes:
%
% Problems with complex data are not allowed.
%
% Rotated cone constraints are not supported.
%
% Nonsymmetric A.s and C.s matrices are symmetrized with A=(A+A')/2
% a warning is given when this happens.
%
% Floating point numbers are written out with 18 decimal digits for
% accuracy.
%
% Please contact the author (Brian Borchers, [email protected]) with any
% questions or bug reports.
%
function writesdp(fname,A,b,c,K)
%From: Brian Borchers[SMTP:[email protected]]
%Sent: Wednesday, December 08, 1999 12:33 PM
%To: [email protected]
%
%Here's a MATLAB routine that will take a problem in SeDuMi's MATLAB format
%and write it out in SDPpack format.
%
% First, check for complex numbers in A, b, or c.
%
if (isreal(A) ~= 1),
disp('A is not real!');
return;
end;
if (isreal(b) ~= 1),
disp('b is not real!');
return;
end;
if (isreal(c) ~= 1),
disp('c is not real!');
return;
end;
%
% Check for any rotated cone constraints.
%
if (isfield(K,'r') & (~isempty(K.r)) & (K.r ~= 0)),
disp('rotated cone constraints are not yet supported.');
return;
end;
%
% Get the size data.
%
if (isfield(K,'l')),
nlin=K.l;
sizelin=nlin;
if (isempty(sizelin)),
sizelin=0;
nlin=0;
end;
else
nlin=0;
sizelin=0;
end;
if (isfield(K,'s')),
nsdpblocks=length(K.s);
%sizesdp=sum((K.s).^2);
%if (isempty(sizesdp)),
%sizesdp=0;
%nsdpblocks=0;
%end;
else
%sizesdp=0;
nsdpblocks=0;
end;
if (isfield(K,'q')),
nqblocks=length(K.q);
sizeq=sum(K.q);
if (isempty(sizeq)),
sizeq=0;
nqblocks=0;
end;
else
nqblocks=0;
sizeq=0;
end;
m=length(b);
%
% Open up the file for writing.
%
fid=fopen(fname,'w');
%
% Print out m, the number of constraints.
%
fprintf(fid,'%d \n',m);
%
% Next, b, with one entry per line.
%
fprintf(fid,'%.18e\n',full(b));
%
% Next, the semidefinite part.
%
if (nsdpblocks == 0),
fprintf(fid,'0\n');
else
%
% Print out the number of semidefinite blocks.
%
fprintf(fid,'%d\n',nsdpblocks);
%
% For each block, print out its size.
%
fprintf(fid,'%d\n',full(K.s));
%
% Next, the cost matrix C.s.
%
%
% First, calculate where in c things start.
%
base=sizelin+sizeq+1;
%
% Next, work through the blocks.
%
for i=1:nsdpblocks,
fprintf(fid,'1\n');
work=c(base:base+K.s(i)^2-1);
work=reshape(work,K.s(i),K.s(i));
if (work ~= work'),
disp('Non symmetric C.s matrix!');
work=(work+work')/2;
end;
work=triu(work);
[II,JJ,V]=find(work);
cnt=length(II);
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% Next, update to the next base.
%
base=base+K.s(i)^2;
end;
%
% Now, loop through the constraints, one at a time.
%
for cn=1:m,
%
% Print out the SDP part of constraint cn.
%
base=sizelin+sizeq+1;
for i=1:nsdpblocks,
fprintf(fid,'1\n');
work=A(cn,base:base+K.s(i)^2-1);
work=reshape(work,K.s(i),K.s(i));
if (work ~= work'),
disp('Non symmetric A.s matrix!');
work=(work+work')/2;
end;
work=triu(work);
[II,JJ,V]=find(work);
cnt=length(II);
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% Next, update to the next base.
%
base=base+K.s(i)^2;
end;
%
% Done with constraint cn
%
end;
%
% Done with SDP part.
%
end;
%
% Next, handle the Quadratic part.
%
%
% Describe the Q blocks.
%
if (nqblocks == 0),
fprintf(fid,'0\n');
else
fprintf(fid,'%d\n',nqblocks);
fprintf(fid,'%d\n',full(K.q));
%
% Find C.q.
%
base=sizelin+1;
cq=c(base:base+sizeq-1);
%
% Print out the C.q coefficients.
%
fprintf(fid,'%.18e\n',full(cq));
%
% Next, the constraint matrix A.q.
%
Aq=A(:,base:base+sizeq-1);
%
% Print out the count of nonzeros.
%
[II,JJ,V]=find(Aq);
cnt=length(II);
fprintf(fid,'1\n');
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% End of handling quadratic part.
%
end;
%
%
% Finally, handle the linear part.
%
if (nlin == 0),
fprintf(fid,'0\n');
else
%
% Print out the number of linear variables.
%
fprintf(fid,'%d\n',nlin);
%
% Print out C.l
%
fprintf(fid,'%.18e\n',full(c(1:nlin)));
%
% Print out the A matrix.
%
Al=A(:,1:nlin);
[II,JJ,V]=find(Al);
cnt=length(II);
fprintf(fid,'1\n');
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
end;
|
github | urbste/MLPnP_matlab_toolbox-master | frompack.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/frompack.m | 2,509 | utf_8 | a4730dcb4ec069944953dce753da973d | % FROMPACK Converts a cone problem in SDPPACK format to SEDUMI format.
%
% [At,c] = frompack(A,b,C,blk) Given a problem (A,b,C,blk) in the
% SDPPACK-0.9-beta format, this produces At and c for use with
% SeDuMi. This lets you execute
%
% [x,y,info] = SEDUMI(At,b,c,blk);
%
% IMPORTANT: this function assumes that the SDPPACK function `smat'
% exists in your search path.
%
% SEE ALSO sedumi.
function [At,c] = frompack(A,b,C,blk)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
m = length(b);
% ----------------------------------------
% In SDPPACK, 0s are sometimes used as emptyset and vice versa.
% ----------------------------------------
if blk.l == 0
A.l = []; C.l = [];
end
if isempty(blk.q)
A.q = []; C.q = [];
end
if isempty(blk.s)
A.s = []; C.s = [];
end
% ----------------------------------------
% SDP:
% ----------------------------------------
Asdp = [];
if sum(blk.s) == 0
csdp = [];
else
for i=1:m
Asdp = [Asdp blk2vec( smat(sparse(A.s(i,:)),blk.s), blk.s ) ];
end
csdp = blk2vec(C.s,blk.s);
end
% ----------------------------------------
% Assemble LP, LORENTZ and SDP.
%----------------------------------------
At = [A.l'; A.q'; Asdp];
c = [C.l; C.q; csdp];
|
github | urbste/MLPnP_matlab_toolbox-master | feascpx.m | .m | MLPnP_matlab_toolbox-master/gOp/SeDuMi_1_3 2/conversion/feascpx.m | 4,385 | utf_8 | c48c6cf336cdb94ad12b04e1efd2417b | % FEASCPX Generates a random sparse optimization problem with
% linear, quadratic and semi-definite constraints. Output
% can be used by SEDUMI. Includes complex-valued data.
%
% The following two lines are typical:
% > [AT,B,C,K] = FEASCPX;
% > [X,Y,INFO] = SEDUMI(AT,B,C,K);
%
% An extended version is:
% > [AT,B,C,K] = FEASCPX(m,lpN,lorL,rconeL,sdpL,denfac)
%
% SEE ALSO sedumi AND feasreal.
function [At,b,c,K] = feascpx(m,nLP,qL,rL,nL,denfac)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
if nargin < 6
denfac = 0.1;
if nargin < 5
nL = 1+ round(7*rand(1,5));
fprintf('Choosing random SDP-product cone K.s.\n')
if nargin < 4
rL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ R-product cone K.r.\n')
if nargin < 3
qL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ-product cone K.q.\n')
if(nargin < 2)
nLP = 10;
fprintf('Choosing default K.l=%3.0f.\n',nLP)
if nargin < 1
m=10;
fprintf('Choosing default m=%3.0f.\n',m)
end
end
end
end
end
end
if isempty(nLP)
nLP = 0;
end
nblk = length(nL) + length(rL) + length(qL) + nLP;
denfac = min(1, max(denfac,2/nblk));
fprintf('Choosing block density denfac=%6.4f per row\n',denfac)
Apattern=sparse(m,nblk);
for j=1:m
pati = sprandn(1,nblk,denfac);
Apattern(j,:) = (pati~= 0);
end
sumnLsqr = sum(nL.^2);
x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1);
x(1:nLP) = rand(nLP,1);
At = sparse(length(x),m);
At(1:nLP,:) = sprandn(Apattern(:,1:nLP)');
firstk = nLP+1;
%[nA, mA] = size(At);
% LORENTZ:
for k=1:length(qL)
nk = qL(k); lastk = firstk + nk - 1;
x(firstk) = rand;
for j=1:m
if Apattern(j,nLP+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ...
sparse([0;sprand(nk-1,1,1/sqrt(nk))]);
end
end
firstk = lastk + 1;
end
% RCONE (Rotated Lorentz):
for k=1:length(rL)
nk = rL(k); lastk = firstk + nk - 1;
x(firstk) = rand; x(firstk+1) = rand;
for j=1:m
if Apattern(j,nLP+length(qL)+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ...
sparse([0;0;sprand(nk-2,1,1/sqrt(nk-1))]);
end
end
firstk = lastk + 1;
end
% SDP:
for k=1:length(nL)
nk = nL(k); lastk = firstk + nk*nk - 1;
Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure
x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts.
for j=1:m
if Apattern(j,nLP+length(qL)+length(rL)+k)==1
rAik = sprandsym(nk,1/nk); %on average 1 nonzero per row
iAik = sprand(nk,nk,1/nk); %on average 1 nonzero per row
At(firstk:lastk,j) = vec(rAik + sqrt(-1)*(iAik-iAik'));
end
end
firstk = lastk + 1;
end
b = real(full(At'*x));
y = rand(m,1)-0.5;
c = sparse(At*y)+x;
K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
|
github | urbste/MLPnP_matlab_toolbox-master | appendimages.m | .m | MLPnP_matlab_toolbox-master/ASPnP/appendimages.m | 461 | utf_8 | a7ad42558236d4f7bd90dc6e72631d54 | % im = appendimages(image1, image2)
%
% Return a new image that appends the two images side-by-side.
function im = appendimages(image1, image2)
% Select the image with the fewest rows and fill in enough empty rows
% to make it the same height as the other image.
rows1 = size(image1,1);
rows2 = size(image2,1);
if (rows1 < rows2)
image1(rows2,1) = 0;
else
image2(rows1,1) = 0;
end
% Now append both images side-by-side.
im = [image1 image2];
|
github | urbste/MLPnP_matlab_toolbox-master | PnP_Reproj_NLS_Matlab.m | .m | MLPnP_matlab_toolbox-master/ASPnP/PnP_Reproj_NLS_Matlab.m | 1,767 | utf_8 | 10261b578cc0cc01f64c72439bf7f95f | function [Rr tr] = PnP_Reproj_NLS_Matlab(U,u,R0,t0)
%to refine the column-triplet by using nonlinear least square
%it's much better than the fminunc used by CVPR12.
%there are three fractional formulations, anyone is equivalently good.
%there are two constrained formulations, yet neither is good.
%the reason is that: eliminating the unkown scale. ---> similar to
%reprojection error and homogeneous error
%transform matrix to unit quaternion
q = matrix2quaternion(R0);
%nonlinear least square parameter setting
options = optimset('Algorithm','trust-region-reflective','Jacobian','on','DerivativeCheck','off','Display','off');
%call matlab lsqnonlin
[var,resnorm] = lsqnonlin(@(var)valuegradient(var,U,u),[q(:);t0(:)],[],[],options);
%denormalize data
qr = var(1:4); tr = var(5:end);
normqr = norm(qr);
tr = tr/(normqr)^2;
qr = qr/normqr;
%trasform back into matrix form
Rr = quaternion2matrix(qr);
end
%formulation 1
function [fval grad] = valuegradient(var,U,u)
npt = size(U,2);
fval = zeros(2*npt,1);
grad = zeros(2*npt,7);
a = var(1); b = var(2); c = var(3); d = var(4);
R = [a^2+b^2-c^2-d^2 2*b*c-2*a*d 2*b*d+2*a*c
2*b*c+2*a*d a^2-b^2+c^2-d^2 2*c*d-2*a*b
2*b*d-2*a*c 2*c*d+2*a*b a^2-b^2-c^2+d^2];
t1 = var(5); t2 = var(6); t3 = var(7);
for i = 1:npt
vec = R*U(:,i) + [t1;t2;t3];
fval(2*(i-1)+1) = u(1,i) - vec(1)/vec(3);
fval(2*i) = u(2,i) - vec(2)/vec(3);
temp1 = [2*[a -d c;b c d; -c b a; -d -a b]*U(:,i); 1; 0; 0].';
temp2 = [2*[d a -b;c -b -a;b c d; a -d c]*U(:,i); 0; 1; 0].';
temp3 = [2*[-c b a;d a -b;-a d -c; b c d]*U(:,i); 0; 0; 1].';
grad(2*(i-1)+1,:) = (-temp1*vec(3) + temp3*vec(1))/(vec(3)^2);
grad(2*i,:) = (-temp2*vec(3) + temp3*vec(2))/(vec(3)^2);
end
end
|
github | urbste/MLPnP_matlab_toolbox-master | matrix2quaternion.m | .m | MLPnP_matlab_toolbox-master/ASPnP/matrix2quaternion.m | 2,010 | utf_8 | ad7a1983aceaa9953be167eddabb22ae | % MATRIX2QUATERNION - Homogeneous matrix to quaternion
%
% Converts 4x4 homogeneous rotation matrix to quaternion
%
% Usage: Q = matrix2quaternion(T)
%
% Argument: T - 4x4 Homogeneous transformation matrix
% Returns: Q - a quaternion in the form [w, xi, yj, zk]
%
% See Also QUATERNION2MATRIX
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% 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, 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.
function Q = matrix2quaternion(T)
% This code follows the implementation suggested by Hartley and Zisserman
R = T(1:3, 1:3); % Extract rotation part of T
% Find rotation axis as the eigenvector having unit eigenvalue
% Solve (R-I)v = 0;
[v,d] = eig(R-eye(3));
% The following code assumes the eigenvalues returned are not necessarily
% sorted by size. This may be overcautious on my part.
d = diag(abs(d)); % Extract eigenvalues
[s, ind] = sort(d); % Find index of smallest one
if d(ind(1)) > 0.001 % Hopefully it is close to 0
warning('Rotation matrix is dubious');
end
axis = v(:,ind(1)); % Extract appropriate eigenvector
if abs(norm(axis) - 1) > .0001 % Debug
warning('non unit rotation axis');
end
% Now determine the rotation angle
twocostheta = trace(R)-1;
twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';
twosintheta = axis'*twosinthetav;
theta = atan2(twosintheta, twocostheta);
Q = [cos(theta/2); axis*sin(theta/2)];
|
github | urbste/MLPnP_matlab_toolbox-master | ASPnP_V2.m | .m | MLPnP_matlab_toolbox-master/ASPnP/ASPnP_V2.m | 1,810 | utf_8 | c026dfb2094099da6ec6ceccacdc2472 | function [R0, t0, cost] = ASPnP_V2(U, u)
%
R = cat(3, rotx(pi/2), roty(pi/2), rotz(pi/2));
t = mean(U,2);
cost = inf;
C_est = [];
t_est = [];
for i = 1:3
% Make a random rotation
pp = R(:,:,i) * (U - repmat(t, 1, size(U,2)));
%case1
[C_est_i, t_est_i] = ASPnP_Case1_V2(pp, u);
%rotate back to the original system
for j = 1:size(t_est_i,2)
t_est_i(:,j) = t_est_i(:,j) - C_est_i(:,:,j) * R(:,:,i) * t;
C_est_i(:,:,j) = C_est_i(:,:,j) * R(:,:,i);
end
%stack all rotations and translations
if size(t_est_i,2) > 0
C_est = cat(3,C_est, C_est_i);
t_est = [t_est t_est_i];
end
end
%among all these solutions, choose the one with smallest reprojection error
%how to determine multiple solutions with the same reprojection error???
index = ones(1,size(t_est,2));
for i = 1:size(t_est,2)
proj = C_est(:,:,i)*U+t_est(:,i)*ones(1,size(u,2));
%not in front of the camera
if min(proj(3,:)) < 0
index(i) = 0;
end
%calculate reprojection error
proj = proj./repmat(proj(3,:),3,1);
err = proj(1:2,:)-u;
error(i) = sum(sum(err.*err));
end
%choose the one with smallest reprojection error
error0 = min(error(index>0));
if isempty(error0)
R0 = []; t0 = []; cost = inf;
return;
end
%using 5% as tolerance to detect multiple solutions
rr = find((error<error0*1.05).*(index>0));
R0 = C_est(:,:,rr);
t0 = t_est(:,rr);
cost = error(rr);
end
function r = rotx(t)
ct = cos(t);
st = sin(t);
r = [1 0 0;
0 ct -st;
0 st ct];
end
function r = roty(t)
% roty: rotation about y-axi-
ct = cos(t);
st = sin(t);
r = [ct 0 st;
0 1 0;
-st 0 ct];
end
function r = rotz(t)
% rotz: rotation about z-axis
ct = cos(t);
st = sin(t);
r = [ct -st 0
st ct 0
0 0 1];
end
|
github | urbste/MLPnP_matlab_toolbox-master | quaternion2matrix.m | .m | MLPnP_matlab_toolbox-master/ASPnP/quaternion2matrix.m | 1,431 | utf_8 | 49448898df2a32720040da4eb82aced9 | % QUATERNION2MATRIX - Quaternion to a 4x4 homogeneous transformation matrix
%
% Usage: T = quaternion2matrix(Q)
%
% Argument: Q - a quaternion in the form [w xi yj zk]
% Returns: T - 4x4 Homogeneous rotation matrix
%
% See also MATRIX2QUATERNION, NEWQUATERNION, QUATERNIONROTATE
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% 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, 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.
function T = quaternion2matrix(Q)
Q = Q/norm(Q); % Ensure Q has unit norm
% Set up convenience variables
w = Q(1); x = Q(2); y = Q(3); z = Q(4);
w2 = w^2; x2 = x^2; y2 = y^2; z2 = z^2;
xy = x*y; xz = x*z; yz = y*z;
wx = w*x; wy = w*y; wz = w*z;
T = [w2+x2-y2-z2 , 2*(xy - wz) , 2*(wy + xz) , 0
2*(wz + xy) , w2-x2+y2-z2 , 2*(yz - wx) , 0
2*(xz - wy) , 2*(wx + yz) , w2-x2-y2+z2 , 0
0 , 0 , 0 , 1];
T = T(1:3,1:3);
end |
github | urbste/MLPnP_matlab_toolbox-master | p3p.m | .m | MLPnP_matlab_toolbox-master/p3p_code_final/p3p.m | 6,878 | utf_8 | d624eafb3c1568d6d9f7f7751a6cab47 | % Copyright (c) 2011, Laurent Kneip, ETH Zurich
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
% * Neither the name of ETH Zurich nor the
% names of its contributors may be used to endorse or promote products
% derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%
% p3p.m
%
%
% Author: Laurent Kneip
% Description: Compute the absolute pose of a camera using three 3D-to-2D correspondences
% Reference: A Novel Parametrization of the P3P-Problem for a Direct Computation of
% Absolute Camera Position and Orientation
%
% Input: worldPoints: 3x3 matrix with corresponding 3D world points (each column is a point)
% imageVectors: 3x3 matrix with UNITARY feature vectors (each column is a vector)
% Output: poses: 3x16 matrix that will contain the solutions
% form: [ 3x1 position(solution1) 3x3 orientation(solution1) 3x1 position(solution2) 3x3 orientation(solution2) ... ]
% the obtained orientation matrices are defined as transforming points from the cam to the world frame
function poses = p3p( worldPoints, imageVectors )
% Initialization of the solution matrix, extraction of world points and feature vectors
poses = zeros(3,4*4);
P1 = worldPoints(:,1);
P2 = worldPoints(:,2);
P3 = worldPoints(:,3);
% Verification that world points are not colinear
vector1 = P2 - P1;
vector2 = P3 - P1;
if norm(cross(vector1,vector2)) == 0
return
end
% Creation of intermediate camera frame
f1 = imageVectors(:,1);
f2 = imageVectors(:,2);
f3 = imageVectors(:,3);
e1 = f1;
e3 = cross(f1,f2);
norm_e3 = sqrt(sum(e3.*e3));
e3 = e3 ./ repmat(norm_e3,3,1);
e2 = cross(e3,e1);
T = [ e1'; e2'; e3' ];
f3 = T*f3;
% Reinforce that f3[2] > 0 for having theta in [0;pi]
if ( f3(3,1) > 0 )
f1 = imageVectors(:,2);
f2 = imageVectors(:,1);
f3 = imageVectors(:,3);
e1 = f1;
e3 = cross(f1,f2);
norm_e3 = sqrt(sum(e3.*e3));
e3 = e3 ./ repmat(norm_e3,3,1);
e2 = cross(e3,e1);
T = [ e1'; e2'; e3' ];
f3 = T*f3;
P1 = worldPoints(:,2);
P2 = worldPoints(:,1);
P3 = worldPoints(:,3);
end
% Creation of intermediate world frame
n1 = P2-P1;
norm_n1 = sqrt(sum(n1.*n1));
n1 = n1 ./ repmat(norm_n1,3,1);
n3 = cross(n1,(P3-P1));
norm_n3 = sqrt(sum(n3.*n3));
n3 = n3 ./ repmat(norm_n3,3,1);
n2 = cross(n3,n1);
N = [ n1'; n2'; n3' ];
% Extraction of known parameters
P3 = N*(P3-P1);
d_12 = sqrt(sum((P2 - P1).^2));
f_1 = f3(1,1)/f3(3,1);
f_2 = f3(2,1)/f3(3,1);
p_1 = P3(1,1);
p_2 = P3(2,1);
cos_beta = f1'*f2;
b = 1/(1-cos_beta^2) - 1;
if cos_beta < 0
b = -sqrt(b);
else
b = sqrt(b);
end
% Definition of temporary variables for avoiding multiple computation
f_1_pw2 = f_1^2;
f_2_pw2 = f_2^2;
p_1_pw2 = p_1^2;
p_1_pw3 = p_1_pw2 * p_1;
p_1_pw4 = p_1_pw3 * p_1;
p_2_pw2 = p_2^2;
p_2_pw3 = p_2_pw2 * p_2;
p_2_pw4 = p_2_pw3 * p_2;
d_12_pw2 = d_12^2;
b_pw2 = b^2;
% Computation of factors of 4th degree polynomial
factor_4 = -f_2_pw2*p_2_pw4 ...
-p_2_pw4*f_1_pw2 ...
-p_2_pw4;
factor_3 = 2*p_2_pw3*d_12*b ...
+2*f_2_pw2*p_2_pw3*d_12*b ...
-2*f_2*p_2_pw3*f_1*d_12;
factor_2 = -f_2_pw2*p_2_pw2*p_1_pw2 ...
-f_2_pw2*p_2_pw2*d_12_pw2*b_pw2 ...
-f_2_pw2*p_2_pw2*d_12_pw2 ...
+f_2_pw2*p_2_pw4 ...
+p_2_pw4*f_1_pw2 ...
+2*p_1*p_2_pw2*d_12 ...
+2*f_1*f_2*p_1*p_2_pw2*d_12*b ...
-p_2_pw2*p_1_pw2*f_1_pw2 ...
+2*p_1*p_2_pw2*f_2_pw2*d_12 ...
-p_2_pw2*d_12_pw2*b_pw2 ...
-2*p_1_pw2*p_2_pw2;
factor_1 = 2*p_1_pw2*p_2*d_12*b ...
+2*f_2*p_2_pw3*f_1*d_12 ...
-2*f_2_pw2*p_2_pw3*d_12*b ...
-2*p_1*p_2*d_12_pw2*b;
factor_0 = -2*f_2*p_2_pw2*f_1*p_1*d_12*b ...
+f_2_pw2*p_2_pw2*d_12_pw2 ...
+2*p_1_pw3*d_12 ...
-p_1_pw2*d_12_pw2 ...
+f_2_pw2*p_2_pw2*p_1_pw2 ...
-p_1_pw4 ...
-2*f_2_pw2*p_2_pw2*p_1*d_12 ...
+p_2_pw2*f_1_pw2*p_1_pw2 ...
+f_2_pw2*p_2_pw2*d_12_pw2*b_pw2;
% Computation of roots
x=solveQuartic([factor_4 factor_3 factor_2 factor_1 factor_0]);
% Backsubstitution of each solution
for i=1:4
cot_alpha = (-f_1*p_1/f_2-real(x(i))*p_2+d_12*b)/(-f_1*real(x(i))*p_2/f_2+p_1-d_12);
cos_theta = real(x(i));
sin_theta = sqrt(1-real(x(i))^2);
sin_alpha = sqrt(1/(cot_alpha^2+1));
cos_alpha = sqrt(1-sin_alpha^2);
if cot_alpha < 0
cos_alpha = -cos_alpha;
end
C = [ d_12*cos_alpha*(sin_alpha*b+cos_alpha);
cos_theta*d_12*sin_alpha*(sin_alpha*b+cos_alpha);
sin_theta*d_12*sin_alpha*(sin_alpha*b+cos_alpha) ];
C = P1 + N'*C;
R = [ -cos_alpha -sin_alpha*cos_theta -sin_alpha*sin_theta;
sin_alpha -cos_alpha*cos_theta -cos_alpha*sin_theta;
0 -sin_theta cos_theta ];
R = N'*R'*T;
poses(1:3,(i-1)*4+1) = C;
poses(1:3,(i-1)*4+2:(i-1)*4+4) = R;
end
end
|
github | urbste/MLPnP_matlab_toolbox-master | solveQuartic.m | .m | MLPnP_matlab_toolbox-master/p3p_code_final/solveQuartic.m | 2,592 | utf_8 | 74f88b5276461cd93fe0d00b39cd0b76 | % Copyright (c) 2011, Laurent Kneip, ETH Zurich
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
% * Neither the name of ETH Zurich nor the
% names of its contributors may be used to endorse or promote products
% derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function roots = solveQuartic( factors )
A = factors(1,1);
B = factors(1,2);
C = factors(1,3);
D = factors(1,4);
E = factors(1,5);
A_pw2 = A*A;
B_pw2 = B*B;
A_pw3 = A_pw2*A;
B_pw3 = B_pw2*B;
A_pw4 = A_pw3*A;
B_pw4 = B_pw3*B;
alpha = -3*B_pw2/(8*A_pw2)+C/A;
beta = B_pw3/(8*A_pw3)-B*C/(2*A_pw2)+D/A;
gamma = -3*B_pw4/(256*A_pw4)+B_pw2*C/(16*A_pw3)-B*D/(4*A_pw2)+E/A;
alpha_pw2 = alpha*alpha;
alpha_pw3 = alpha_pw2*alpha;
P = -alpha_pw2/12-gamma;
Q = -alpha_pw3/108+alpha*gamma/3-beta^2/8;
R = -Q/2+sqrt(Q^2/4+P^3/27);
U = R^(1/3);
if U == 0
y = -5*alpha/6-Q^(1/3);
else
y = -5*alpha/6-P/(3*U)+U;
end
w = sqrt(alpha+2*y);
roots(1,1) = -B/(4*A) + 0.5*(w+sqrt(-(3*alpha+2*y+2*beta/w)));
roots(2,1) = -B/(4*A) + 0.5*(w-sqrt(-(3*alpha+2*y+2*beta/w)));
roots(3,1) = -B/(4*A) + 0.5*(-w+sqrt(-(3*alpha+2*y-2*beta/w)));
roots(4,1) = -B/(4*A) + 0.5*(-w-sqrt(-(3*alpha+2*y-2*beta/w)));
end
|
github | OpenWaterAnalytics/epanet-example-networks-master | nh2cl.m | .m | epanet-example-networks-master/msx-examples/Batch-NH2Cl/nh2cl.m | 2,326 | utf_8 | df91b63da638b7e7db9bdaad7fa25448 | function [t,y]=nh2cl(ph)
%Matlab code to verify NH2CL bacth model results of EPANET-MSX
%input argument: pH value
%output: t = time in hour
% y = matrix to store the time series of the species concentration
% y[:,j] is the time series vector of spcies with index j
% species index in the DAE systemn
%HOCL 1 Hypochlorous acid
%NH3 2 Ammonia
%NH2CL 3 Monochloramine
%NHCL2 4 Dichloramine
%I 5 Unidentified intermediate compound
%H 6
%ALK 7 Alkalinity
%OCL 8 Hypochlorite Ion
%NH4 9 Ammonium Ion
%CO3 10
%H2CO3 11
%HCO3 12
%OH 13
%M is the Mass matrix for DAE, first 7 equations are differential equations and the
%other 6 are algebraic equations
M = zeros(13,13);
for i = 1:7
M(i,i)= 1.0;
end
% Initial condition
y0 =zeros(13,1);
y0(3) = 0.05e-3; % Initial [NH2CL]
y0(6) = 10^(-ph); % Initial [H]
y0(7) = 0.004; % Initial [ALK]
tspan = [0 168]; % Simulation Time
tol = 1e-8*ones(1,13); % Absolute tolerance
options = odeset('Mass',M,'RelTol',1e-4,'AbsTol',tol, ...
'Vectorized','off', 'BDF', 'on');
[t,y] = ode15s(@f,tspan,y0,options);
%--------------------------------------------------------------------------
function out = f(t,y)
k1 = 1.5e10;
k2 = 7.6e-2;
k3 = 1.0e6;
k4 = 2.3e-3;
k6 = 2.2e8;
k7 = 4.0e5;
k8 = 1.0e8;
k9 = 3.0e7;
k10 = 55.0;
k5 = 2.5e7*y(6)+4.0e4*y(11)+800*y(12);
a1 = k1*y(1)*y(2);
a2 = k2*y(3);
a3 = k3*y(1)*y(3);
a4 = k4*y(4);
a5 = k5*y(3)*y(3);
a6 = k6*y(4)*y(2)*y(6);
a7 = k7*y(4)*y(13);
a8 = k8*y(5)*y(4);
a9 = k9*y(5)*y(3);
a10 = k10*y(3)*y(4);
%Evalutaion of DAEs
out(1,1) = -a1+a2-a3+a4+a8; %d[HOCL]/dt
out(2,1) = -a1+a2+a5-a6; %d[NH3]/dt
out(3,1) = a1-a2-a3+a4-a5+a6-a9-a10; %d[NH2CL]/dt
out(4,1) = a3-a4+a5-a6-a7-a8-a10; %d[NHCL2]/dt
out(5,1) = a7-a8-a9; %d[I]/dt
out(6,1) = 0; %constant pH
out(7,1) = 0; %constant alkalinity
%The following are equilibrium equations
out(8,1) = y(6)*y(8) - 3.16e-8*y(1);
out(9,1) = y(6)*y(2) - 5.01e-10*y(9);
out(10,1) = y(6)*y(10)- 5.01e-11*y(12);
out(11,1) = y(6)*y(12) - 5.01e-7*y(11);
out(12,1) = y(7) - y(12) - 2*y(10) - y(13) + y(6);
out(13,1) = y(6)*y(13) - 1.0e-14;
|
github | zinsmatt/StructureFromMotion-master | torr_unit2sphere.m | .m | StructureFromMotion-master/code/torr_unit2sphere.m | 575 | utf_8 | ff5aaca95792e2cc250b4fe118d1bc84 | % By Philip Torr 2002
% copyright Microsoft Corp.
function [a,b] = torr_unit2sphere(rot_axis)
% %convert rot_axis to spherical coords
% sin a sin b
% sin a cos b
% cos a
rot_axis = rot_axis/norm(rot_axis);
%normalize so second coordinate + ve
%rot_axis = rot_axis * sign(rot_axis(2));
a = acos(rot_axis(3));
%b = atan(rot_axis(1)/rot_axis(2));
b = acos(rot_axis(2)/sin(a));
%need to sort the signs out:
% %there are two solutions for a
% a2 = -a;
% b2 = -b;
if abs(rot_axis(1) - sin(a) * sin(b)) < 0.000001
return
else
b = -b;
end
|
github | zinsmatt/StructureFromMotion-master | torr_triangulate.m | .m | StructureFromMotion-master/code/torr_triangulate.m | 1,372 | utf_8 | fae00b93ffeacd252c09620d63df8527 | % By Philip Torr 2002
% copyright Microsoft Corp.
%this function calculates the set of 3D points given matches and two projection matrices
%for this method to work best the matches must be corrected to lie on the epipolar lines
%P-i ith row of the P matrix then
%constraints are of the form x p_3^t - p_1 & y p_3^t - p_2
function X = torr_triangulate(matches, m3, P1, P2)
%first establish the 4 x 4 matrix J such that J^X = 0
[nr no_matches] = size(matches);
x1 = matches(:,1)/m3;
y1 = matches(:,2)/m3;
x2 = matches(:,3)/m3;
y2 = matches(:,4)/m3;
for i = 1:nr
J(1,1) = P1(3,1) * x1(i) - P1(1,1);
J(1,2) = P1(3,2) * x1(i) - P1(1,2);
J(1,3) = P1(3,3) * x1(i) - P1(1,3);
J(1,4) = P1(3,4) * x1(i) - P1(1,4);
J(2,1) = P1(3,1) * y1(i) - P1(2,1);
J(2,2) = P1(3,2) * y1(i) - P1(2,2);
J(2,3) = P1(3,3) * y1(i) - P1(2,3);
J(2,4) = P1(3,4) * y1(i) - P1(2,4);
J(3,1) = P2(3,1) * x2(i) - P2(1,1);
J(3,2) = P2(3,2) * x2(i) - P2(1,2);
J(3,3) = P2(3,3) * x2(i) - P2(1,3);
J(3,4) = P2(3,4) * x2(i) - P2(1,4);
J(4,1) = P2(3,1) * y2(i) - P2(2,1);
J(4,2) = P2(3,2) * y2(i) - P2(2,2);
J(4,3) = P2(3,3) * y2(i) - P2(2,3);
J(4,4) = P2(3,4) * y2(i) - P2(2,4);
X(:,i) = torr_ls(J);
end
%at the moment this is unnormalized so that chierality can be determined |
github | zinsmatt/StructureFromMotion-master | torr_linear_EtoPX.m | .m | StructureFromMotion-master/code/torr_linear_EtoPX.m | 4,403 | utf_8 | 72468f003e54de860e3dda2c72e05ed4 | % By Philip Torr 2002
% copyright Microsoft Corp.
%takes an essential matrix and a set of corrected matches, and outputs projection matrices, 3D points etc
%all via linear estimation; need camera calibration matrix too
function [P1,P2,R,t,rot_axis,rot_angle,g] = torr_linear_EtoPX(E,matches,C,m3)
%stage 1 generate twisted pairs etc
[U,S,V] = svd(E);
%note that there is a one p[arameter family of SVD's for E
S(2,2) = S(1,1);
S(3,3)=0;
if abs(S(3,3)) > 0.00001
error('E must be rank 2 to self calibrate');
end
if abs(S(1,1) - S(2,2)) > 0.00001
error('E must have two equal singular values');
end
%use Hartley matrices:
W = [0 -1 0; 1 0 0; 0 0 1];
Z = [0 1 0; -1 0 0; 0 0 0];
Tx = U * Z * U';
R1 = U * W * V';
R2 = U * W' * V';
R1 = R1 * sign(det(R1)) * sign(det(C));
R2 = R2 * sign(det(R2)) * sign(det(C));
%the left epipole is, which gives the direction of translation
u3 = U(:,3);
%such that u3' * E = 0,
%next establish the four possible camera matrix pairs as points out in Maybank, Hartley & zisserman etc
%first camera is 3x4 at origin of the world system.
P1 = [C'; 0,0,0]';
%given this there are four choices for the second, we normalize them so that the
%determinant of the first 3x3 is greater than zero, this is useful for determining chierality later
P21 = C * [ R1'; u3']';
P22 = C * [ R1'; -u3']';
P23 = C * [ R2'; u3']';
P24 = C * [ R2'; -u3']';
%next we take one point to determine the chierality of the camera
X1 = torr_triangulate(matches, m3, P1, P21);
X2 = torr_triangulate(matches, m3, P1, P22);
X3 = torr_triangulate(matches, m3, P1, P23);
X4 = torr_triangulate(matches, m3, P1, P24);
%next reproject and compare with the images
%the chieral constraint is sign(det M) * sign (third homog coord of reprojected image) * sign (fourth homog coord X)
% to make sure we dont get any outliers we average the inequalities over all the points, ones with a bad sign
% can later be removed as outleirs.
%we want chieral for both cameras to be positive
ax1 = P1 * X1;
%ax1 = ax1 *m3/ax1(3)
ax2 = P1 * X2;
%ax2 = ax2 *m3/ax2(3)
ax3 = P1 * X3;
%ax3 = ax3 *m3/ax3(3)
ax4 = P1 * X4;
%ax4 = ax4 *m3/ax4(3);
bx1 = P21 * X1;
%bx1 = bx1 *m3/bx1(3)
bx2 = P22 * X2;
%bx2 = bx2 *m3/bx2(3)
bx3 = P23 * X3;
%bx3 = bx3 *m3/bx3(3)
bx4 = P24 * X4;
%bx4 = bx4 *m3/bx4(3);
chieral1 = (sign(ax1(3,:) ) .* sign (X1(4,:))) + (sign(bx1(3,:) ) .* sign (X1(4,:)));
chieral2 = (sign(ax2(3,:) ) .* sign (X1(4,:))) + (sign(bx2(3,:) ) .* sign (X2(4,:)));
chieral3 = (sign(ax3(3,:) ) .* sign (X1(4,:))) + (sign(bx3(3,:) ) .* sign (X3(4,:)));
chieral4 = (sign(ax4(3,:) ) .* sign (X1(4,:))) + (sign(bx4(3,:) ) .* sign (X4(4,:)));
chieral_sum = [sum(chieral1) sum(chieral2) sum(chieral3) sum(chieral4)];
[max_ch correct_interpretation] = max(chieral_sum);
switch correct_interpretation
case 1
R = R1;
t = u3;
P2 = P21;
case 2
R = R1;
t = -u3;
P2 = P22;
case 3
R = R2;
t = u3;
P2 = P23;
case 4
R = R2;
t = -u3;
P2 = P24;
end
%next recover the parameters of the rotation...
% [VR,DR] = eig(R);
%
% dd = [DR(1,1), DR(2,2), DR(3,3)];
% [Y Index] = find(dd==1);
%
% %determine axis of rotation
% axis = VR(:,Index(1));
rot_axis = [R(3,2)-R(2,3), R(1,3) - R(3,1), R(2,1) - R(1,2)];
rot_axis = rot_axis /norm(rot_axis);
rot_angle = acos( (trace(R)-1)/2);
[a b] = torr_unit2sphere(rot_axis);
[ta tb] = torr_unit2sphere(t);
%put together intrinisc and extrinsic parameters
%
% %here p is the set of paramets such that
% g(1) = focal length
% g(2-3) rotation axis
% g(4) rotation angle
% g(5-6) translation direction
g(1) = 1/C(3,3);
g(2) = a;
g(3) = b;
g(4) = rot_angle;
g(5) = ta;
g(6) = tb;
%
% CCC = C;
% %convert intrinsic and extinsics to a F matrix
% C(3,3) = 1/g(1);
% rot_axis2 = torr_sphere2unit([g(2) g(3)]);
% tt = torr_sphere2unit([g(5) g(6)]);
% rot_angle2 = g(4);
%
% %Rogregues
% II = [1 0 0; 0 1 0; 0 0 1];
% AX = torr_skew_sym(rot_axis2);
%
% %note -sin produce RR'
% RR = (cos(rot_angle2) * II +sin(rot_angle2) * AX + (1 - cos(rot_angle2)) * rot_axis2 * rot_axis2');
%
% TX = torr_skew_sym(tt);
% nnE = TX * RR;
%
% %F = inv(C') * nnE * inv(C);
% F = inv(C') * nnE * inv(C);
% f = reshape(F,9,1);
|
github | zinsmatt/StructureFromMotion-master | torr_ls.m | .m | StructureFromMotion-master/code/torr_ls.m | 722 | utf_8 | 7c4c0bc1a34e1fcfbd3cf317115e4055 | % By Philip Torr 2002
% copyright Microsoft Corp.
%
% %designed for the good of the world by Philip Torr
% copyright Philip Torr and Microsoft Corp 2002
% orthogonal regression see
% @article{Torr97c,
% author="Torr, P. H. S. and Murray, D. W. ",
% title="The Development and Comparison of Robust Methods for Estimating the Fundamental Matrix",
% journal="IJCV",
% volume = 24,
% number = 3,
% pages = {271--300},
% year=1997
% }
%
function [vec, error] = torr_ls(D)
try
[U, S, V] = svd(D);
catch
disp('what happeend?');
end
V;
vec = V(:,length(V));
error = S(length(V),length(V));
%disp('performing least squares')
|
github | karaimer/camera-pipeline-white-balancing-experiment-master | general_cc.m | .m | camera-pipeline-white-balancing-experiment-master/ColorConstancy/general_cc.m | 3,050 | utf_8 | 22c2d001fd8a73a38eca87458096413a | % general_cc: estimates the light source of an input_image.
%
% Depending on the parameters the estimation is equal to Grey-Wolrd, Max-RGB, general Grey-World,
% Shades-of-Gray or Grey-Edge algorithm.
%
% SYNOPSIS:
% [white_R ,white_G ,white_B,output_data] = general_cc(input_data,njet,mink_norm,sigma,mask_im)
%
% INPUT :
% input_data : color input image (NxMx3)
% njet : the order of differentiation (range from 0-2).
% mink_norm : minkowski norm used (if mink_norm==-1 then the max
% operation is applied which is equal to minkowski_norm=infinity).
% mask_im : binary images with zeros on image positions which
% should be ignored.
% OUTPUT:
% [white_R,white_G,white_B] : illuminant color estimation
% output_data : color corrected image
% LITERATURE :
%
% J. van de Weijer, Th. Gevers, A. Gijsenij
% "Edge-Based Color Constancy"
% IEEE Trans. Image Processing, accepted 2007.
%
% The paper includes references to other Color Constancy algorithms
% included in general_cc.m such as Grey-World, and max-RGB, and
% Shades-of-Gray.
function [white_R ,white_G ,white_B,output_data] = general_cc(input_data,njet,mink_norm,sigma,mask_im)
if(nargin<2), njet=0; end
if(nargin<3), mink_norm=1; end
if(nargin<4), sigma=1; end
if(nargin<5), mask_im=zeros(size(input_data,1),size(input_data,2)); end
% remove all saturated points
saturation_threshold = 255;
mask_im2 = mask_im + (dilation33(double(max(input_data,[],3)>=saturation_threshold)));
mask_im2=double(mask_im2==0);
mask_im2=set_border(mask_im2,sigma+1,0);
% the mask_im2 contains pixels higher saturation_threshold and which are
% not included in mask_im.
output_data=input_data;
if(njet==0)
if(sigma~=0)
for ii=1:3
input_data(:,:,ii)=gDer(input_data(:,:,ii),sigma,0,0);
end
end
end
if(njet>0)
[Rx,Gx,Bx]=norm_derivative(input_data, sigma, njet);
input_data(:,:,1)=Rx;
input_data(:,:,2)=Gx;
input_data(:,:,3)=Bx;
end
input_data=abs(input_data);
if(mink_norm~=-1) % minkowski norm = (1,infinity >
kleur=power(input_data,mink_norm);
white_R = power(sum(sum(kleur(:,:,1).*mask_im2)),1/mink_norm);
white_G = power(sum(sum(kleur(:,:,2).*mask_im2)),1/mink_norm);
white_B = power(sum(sum(kleur(:,:,3).*mask_im2)),1/mink_norm);
som=sqrt(white_R^2+white_G^2+white_B^2);
white_R=white_R/som;
white_G=white_G/som;
white_B=white_B/som;
else %minkowski-norm is infinit: Max-algorithm
R=input_data(:,:,1);
G=input_data(:,:,2);
B=input_data(:,:,3);
white_R=max(R(:).*mask_im2(:));
white_G=max(G(:).*mask_im2(:));
white_B=max(B(:).*mask_im2(:));
som=sqrt(white_R^2+white_G^2+white_B^2);
white_R=white_R/som;
white_G=white_G/som;
white_B=white_B/som;
end
output_data(:,:,1)=output_data(:,:,1)/(white_R*sqrt(3));
output_data(:,:,2)=output_data(:,:,2)/(white_G*sqrt(3));
output_data(:,:,3)=output_data(:,:,3)/(white_B*sqrt(3)); |
github | karaimer/camera-pipeline-white-balancing-experiment-master | normalize.m | .m | camera-pipeline-white-balancing-experiment-master/ColorConstancy/normalize.m | 361 | utf_8 | b8213b1fd1409a252b98087255fb1194 |
function Y = normalize(X, min, max)
% Normalize the data into the range of 0 and 1 according to the name of the
% camera
% input:
% X: data needed to be normalized
% min: minimum value
% max: maximum value
% output:
% Y: data after normalizing
% Normalize the data X
X = double(X);
Y = (X - min) / (max - min);
Y(Y<0) = 0;
Y(Y>1) = 1; |
github | Wiesen/Robotics-Estimation-and-Learning-master | occGridMapping.m | .m | Robotics-Estimation-and-Learning-master/2D Occupancy Grid Mapping/AssignmentWEEK3/occGridMapping.m | 1,672 | utf_8 | 1e30e43c6c1f9fd9ce0543be233bfaad | % Robotics: Estimation and Learning
% WEEK 3
%
% Complete this function following the instruction.
function myMap = occGridMapping(ranges, scanAngles, pose, param)
%% Parameters
% the number of grids for 1 meter.
myResol = param.resol;
% the initial map size in pixels
myMap = zeros(param.size);
% the origin of the map in pixels
myOrigin = param.origin;
% Log-odd parameters
lo_occ = param.lo_occ;
lo_free = param.lo_free;
lo_max = param.lo_max;
lo_min = param.lo_min;
%% Loop
N = size(pose,2);
K = size(ranges, 1);
for i = 1:N % for each time
pose_orig = [pose(1, i), pose(2, i)];
theta = pose(3, i);
% local coordinates of occupied points in real world
occ_local = [ranges(:,i) .* cos(theta + scanAngles), -ranges(:,i) .* sin(theta + scanAngles)];
% coordinate of robot in metric map
pose_grid = ceil(myResol * pose_orig);
for j = 1:K
% Find grids hit by the rays (in the gird map coordinate)
occ_grid = ceil(myResol * (occ_local(j,:) + pose_orig));
% Find occupied-measurement cells and free-measurement cells
[freex, freey] = bresenham(pose_grid(1), pose_grid(2), occ_grid(1), occ_grid(2));
free = sub2ind(size(myMap),freey + myOrigin(2), freex + myOrigin(1));
occ = sub2ind(size(myMap), occ_grid(2) + myOrigin(2), occ_grid(1) + myOrigin(1));
% Update the log-odds
myMap(free) = myMap(free) - lo_free;
myMap(occ) = myMap(occ) + lo_occ;
end
end
myMap(myMap < lo_min) = lo_min;
myMap(myMap > lo_max) = lo_max;
end
|
github | Wiesen/Robotics-Estimation-and-Learning-master | detectBall.m | .m | Robotics-Estimation-and-Learning-master/Color Learning and Target Detection/AssignmentWEEK1/detectBall.m | 1,313 | utf_8 | 395dd878f3e2f3573c1c707d1ea21202 | % Robotics: Estimation and Learning
% WEEK 1
%
% Complete this function following the instruction.
function [segI, loc] = detectBall(I)
% function [segI, loc] = detectBall(I)
%
% INPUT
% I 120x160x3 numerial array
%
% OUTPUT
% segI 120x160 numeric array
% loc 1x2 or 2x1 numeric array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Hard code your learned model parameters here
load('mu.mat', 'mu');
load('sig.mat', 'sig');
thre = 8e-6;
% Find ball-color pixels using your model
dI = double(I);
row = size(dI, 1);
col = size(dI, 2);
for i = 1:3
dI(:,:,i) = dI(:,:,i) - mu(i);
end
dI = reshape(dI, row*col, 3);
dI = exp(-0.5 * sum(dI * inv(sig) .* dI, 2)) ./ (2 * pi)^1.5 ./ det(sig)^0.5;
dI = reshape(dI, row, col);
% Do more processing to segment out the right cluster of pixels.
dI = dI > thre;
segI = false(size(dI));
CC = bwconncomp(dI);
numPixels = cellfun(@numel,CC.PixelIdxList);
[~,idx] = max(numPixels);
segI(CC.PixelIdxList{idx}) = true;
% figure, imshow(segI); hold on;
% Compute the location of the ball center
S = regionprops(CC,'Centroid');
loc = S(idx).Centroid;
% plot(loc(1), loc(2),'r+');
% Note: In this assigment, the center of the segmented ball area will be considered for grading.
% (You don't need to consider the whole ball shape if the ball is occluded.)
end
|
github | EoinDavey/Competitive-master | d08.m | .m | Competitive-master/AdventOfCode2021/d08_octave/d08.m | 2,282 | utf_8 | eca51b7f494841063e25532af674fa52 | 1; % Mark this as a script-file, not a function file (octave weirdness)
function cell = split2sets( l )
cell = strsplit(l, " ");
cell = cellfun(@unique, cell, "UniformOutput", false);
endfunction
function splt = splitInpLine( line )
splt = strsplit(line, " | ");
splt = cellfun(@split2sets, splt, "UniformOutput", false);
splt = cell2struct(splt, { "in", "out" }, 2);
endfunction
function cnt = count1478( l )
cnt = 0;
for x = l,
s = x{1};
if ismember(length(s), [ 2 3 4 7 ])
cnt++;
endif
end
endfunction
function part1( inp )
sm = 0;
for x = inp,
l = x{1};
sm += count1478(l.out);
end
printf("Part 1: %d\n", sm);
endfunction
function f = firstMatch(func, arr)
for elt = arr,
x = elt{1};
if func(x)
f = x;
return
endif
end
endfunction
function part2(inp)
sm = 0;
for x = inp,
l = x{1};
mp = {};
ls = arrayfun(@(x) firstMatch(@(y) length(y) == x, l.in), [ 2 3 4 7 ], "UniformOutput", false);
mp{1} = ls{1};
mp{7} = ls{2};
mp{4} = ls{3};
mp{8} = ls{4};
t = setdiff(mp{7}, mp{1});
uw = setdiff(mp{4}, mp{1});
mp{10} = firstMatch(@(x) length(x) == 6 && length(setdiff(uw, x)) != 0, l.in);
w = setdiff(mp{8}, mp{10});
u = setdiff(uw, w);
mp{5} = firstMatch(@(x) length(x) == 5 && length(setdiff(union(t,uw), x)) == 0, l.in);
v = setdiff(mp{1}, mp{5});
y = setdiff(mp{1}, v);
mp{9} = union(mp{5},v);
z = setdiff(mp{9}, unique([t u v w y]));
x = setdiff(mp{8}, unique([t u v w y z]));
mp{2} = unique([t v w x z]);
mp{3} = unique([t v y z w]);
mp{6} = unique([t u w x y z]);
val = 0;
for x = l.out,
x = x{1};
val *= 10;
for k = 1:10,
if strcmp(mp{k}, x) == 1
val += mod(k, 10) ;
endif
end
end
sm += val;
end
printf("Part 2: %d\n", sm)
endfunction
inp = strsplit(fileread("/code/d08_octave/d08.txt"), "\n") ;
inp(end) = [];
inp = cellfun("splitInpLine", inp, "UniformOutput", false);
part1(inp);
part2(inp);
|
github | ihowat/setsm_postprocessing-master | boundaryAdjust.m | .m | setsm_postprocessing-master/boundaryAdjust.m | 4,292 | utf_8 | 376829e3e673a4e1a0fdce4d6ef23a33 | function boundaryAdjust(fileNames,varargin)
% boundaryAdjust adjust tile based on offsets with neighbors over buffers
%
% boundaryAdjust(fileNames) where fileNames is a cell of full filenames of
% tile files. Files must be named row_col_*.mat, where the row and col are
% the tile row and column numbers in the tile arrangment (so the tile above
% would be (row+1)_col_*.mat . The tiles above, below, left and right are
% loading and the offset over the buffer is caculated. The values are then
% upscaled by the resizeFraction, which should be ~ the fractional width
% of the buffer, and added along the edges of a correction field (dz0)
% that is then filled through interpolation. dz0 is generated for all
% tiles in the list and then, afterward, is applied to all tiles in the
% list. A flag, adusted, is added with value false if dz0 has not been
% applied and true if it has.
%
% boundaryAdjust(fileNames,'noApply')only calculates/saves the dz0 field
% but does not apply it to z.
resizeFraction=0.1;
if ~iscell(fileNames)
fileNames = {fileNames};
end
%% dz0 calc and write loop - this could be run simultaneously/parallel
i=1;
for i =1:length(fileNames)
fprintf('Calculating offset grid for %s .... ',fileNames{i})
m0=matfile(fileNames{i});
if any(strcmp(fields(m0),'dz0'))
fprintf('dz0 already exists, skipping\n')
continue
end
calcdz0(fileNames{i},resizeFraction)
fprintf('done\n')
end
if ~isempty(varargin)
if any(strcmpi(varargin,'noapply'))
return
end
end
%% dz0 apply loop - this could be run simultaneously/parallel
i=1;
for i =1:length(fileNames)
fprintf('Applying offset to %s ....',fileNames{i})
m0=matfile(fileNames{i});
if any(strcmp(fields(m0),'adjusted'))
if m0.adjusted
fprintf('adjusted flag already true, skipping\n')
continue
end
end
if ~any(strcmp(fields(m0),'dz0'))
fprintf('dz0 doesnt exist, skipping\n')
continue
end
m0.Properties.Writable = true;
m0.z = m0.z - m0.dz0;
m0.adjusted = true;
fprintf('done\n')
end
function calcdz0(fileName,resizeFraction)
m0=matfile(fileName);
s=whos(m0);
sz= s(strcmp({s.name},'z')).size;
dz0 = nan(ceil(sz.*resizeFraction));
[path,name,ext]=fileparts(fileName);
if isempty(path)
path='.';
end
a = strsplit(name,'_');
stringLength=num2str(length(a{1}));
tileRow=str2num(a{1});
tileCol=str2num(a{2});
formatString = ['%s/%0',stringLength,'d_%0',stringLength,'d'];
% above
file1 = [sprintf(formatString,path,tileRow+1,tileCol),...
sprintf('_%s',a{3:end}),ext];
if exist(file1,'file')
m1=matfile(file1);
dzbuff = getdzbuff(m0,m1);
dz0(1,:) = imresize(nanmean(dzbuff),resizeFraction);
else
dz0(1,:) = 0;
end
% below
file1 = [sprintf(formatString,path,tileRow-1,tileCol),...
sprintf('_%s',a{3:end}),ext];
if exist(file1,'file')
m1=matfile(file1);
dzbuff = getdzbuff(m0,m1);
dz0(end,:) =imresize(nanmean(dzbuff),resizeFraction);
else
dz0(end,:) = 0;
end
% left
file1 = [sprintf(formatString,path,tileRow,tileCol-1),...
sprintf('_%s',a{3:end}),ext];
if exist(file1,'file')
m1=matfile(file1);
dzbuff = getdzbuff(m0,m1);
dz0(:,1) = imresize(nanmean(dzbuff,2),resizeFraction);
else
dz0(:,1) = 0;
end
% right
file1 = [sprintf(formatString,path,tileRow,tileCol+1),...
sprintf('_%s',a{3:end}),ext];
if exist(file1,'file')
m1=matfile(file1);
dzbuff = getdzbuff(m0,m1);
dz0(:,end) = imresize(nanmean(dzbuff,2),resizeFraction);
else
dz0(:,end) = 0;
end
dz0=single(inpaint_nans(double(dz0),2));
dz0 = imresize(dz0,sz);
dz0 = dz0./2;
m0.Properties.Writable = true;
m0.dz0 = dz0;
m0.adjusted = false;
function dzbuff=getdzbuff(m0,m1)
c0 = m0.x >= min(m1.x) & m0.x <= max(m1.x);
r0 = m0.y >= min(m1.y) & m0.y <= max(m1.y);
c0 = [find(c0,1,'first'),find(c0,1,'last')];
r0 = [find(r0,1,'first'),find(r0,1,'last')];
if isempty(c0) || isempty(r0); error('no overlap between tiles'); end
c1 = m1.x >= min(m0.x) & m1.x <= max(m0.x);
r1 = m1.y >= min(m0.y) & m1.y <= max(m0.y);
c1 = [find(c1,1,'first'),find(c1,1,'last')];
r1 = [find(r1,1,'first'),find(r1,1,'last')];
dzbuff = m0.z(r0(1):r0(2),c0(1):c0(2)) - m1.z(r1(1):r1(2),c1(1):c1(2));
|
github | ihowat/setsm_postprocessing-master | edgeFeather.m | .m | setsm_postprocessing-master/edgeFeather.m | 3,170 | utf_8 | 84c92b942f4233783b93659efa115329 | function W = edgeFeather(M0,M1,varargin)
% EDGEFEATHER get weights for merging two images with edge feathering
%
%W = edgeFeather(M0,M1,buff) where M0 and M1 are equally sized BW images
%with ones for data and zeros for no data. buff is the cutline buffer for
%merging - greater == means more overlap used for feather
buff=0;
f0=0; % overlap fraction where back z weight goes to zero
f1=1; % overlap fraction where back z weight goes to one
maxInterpPixels = 1e6;
% parse input args
for i=1:2:length(varargin)
switch lower(varargin{i})
case 'buffer'
buff=varargin{i+1};
case 'overlaprange'
f0=varargin{i+1}(1);
f1=varargin{i+1}(2);
otherwise
error('Unknown input arguments')
end
end
% crop to just region of overlap
A= single(M0 & M1);
% if no overlap, send 1/0 mask back
if ~any(A(:))
W=nan(size(M0));
W(M0) = 1;
W(M1) = 0;
return
end
% crop to area of overlap
A(A==0)=NaN;
[~,rb,cb] = cropnans(A,buff);
%Make overlap mask removing isolated pixels
A=single(bwareaopen(...
~M0(rb(1):rb(2),cb(1):cb(2)) & M1(rb(1):rb(2),cb(1):cb(2)),...
1000)); % nodata in back and data in front = 1
A(bwareaopen(...
M0(rb(1):rb(2),cb(1):cb(2)) & ~M1(rb(1):rb(2),cb(1):cb(2)),...
1000)) =2 ; % data in back and nodata in front = 2
% do weight interpolation on low res grid for speed
if numel(A) <= maxInterpPixels; maxInterpPixels=numel(A); end
Ar=imresize(A,maxInterpPixels./numel(A),'nearest');
%Ar=imresize(A,.1,'nearest');
fprintf('%d pixels\n',numel(Ar));
% interpolation grid
[C,R] = meshgrid(1:size(Ar,2),1:size(Ar,1));
% pixles on outside of boundary of overlap region
B = bwboundaries(Ar~=0, 8, 'noholes');
B = cell2mat(B);
if size(B,2) ~= 2
warning('no overlap boundaries returned, no feathering applied');
W=nan(size(M0));
W(M1) = 0;
W(M0) = 1;
return
end
n=sub2ind(size(Ar),B(:,1),B(:,2));
warning off
F = scatteredInterpolant(C(n),R(n),double(Ar(n)));
warning on
try
Ar(Ar==0)=F(C(Ar==0),R(Ar==0));
catch
warning('interpolation failed, no feathering applied');
W=nan(size(M0));
W(M1) = 0;
W(M0) = 1;
return
end
Ar=imresize(Ar,size(A),'bilinear');
Ar(A==1 & Ar ~=1)=1;
Ar(A==2 & Ar ~=2)=2;
A=Ar-1;
A(A < 0) = 0;
A(A > 1) = 1;
W=single(M0);
W(rb(1):rb(2),cb(1):cb(2)) = A;
W(M0 & ~M1) = NaN;
clear A
% shift weights so that more of the reference layer is kept
W=(1/(f1-f0)).*W-f0/(f1-f0);
W(W > 1) = 1;
W(W < 0) = 0;
function [A,r,c] = cropnans(varargin)
% cropnans crop array of bordering nans
%
% [A,r,c] = cropnans(A)
A=varargin{1};
buff=0;
if nargin == 2; buff=varargin{2}; end
r = [];
c = [];
M = ~isnan(A);
if ~any(M(:)); return; end
rowsum = sum(M) ~= 0;
colsum = sum(M,2) ~= 0;
c(1) = find(rowsum,1,'first')-buff;
c(2) = find(rowsum,1,'last')+buff;
r(1) = find(colsum,1,'first')-buff;
r(2) = find(colsum,1,'last')+buff;
if c(1) < 1; c(1)=1; end
if r(1) < 1; r(1)=1; end
if c(2) > size(A,2); c(2)=size(A,2); end
if r(2) > size(A,1); r(2)=size(A,1); end
A = A(r(1):r(2),c(1):c(2));
|
github | ihowat/setsm_postprocessing-master | QCStrips.m | .m | setsm_postprocessing-master/QCStrips.m | 2,874 | utf_8 | caaf539387dedcf78e5b5d7dd67db162 | function QCStrips(stripDir,varargin)
outFile=[stripDir,'/qc.mat'];
system(['rm ',stripDir,'/._*']);
fileNames=dir([stripDir,'/*dem_browse.tif']);
fileNames=cellfun( @(x) [stripDir,'/',x], {fileNames.name},'uniformOutput',false);
fileNames=fileNames(:);
flag=zeros(size(fileNames));
x=cell(size(fileNames));
y=cell(size(fileNames));
if exist(outFile,'file')
a=load(outFile);
[~,IA,IB] = intersect(fileNames,a.fileNames);
flag(IA) = a.flag(IB);
x(IA) = a.x(IB);
y(IA) = a.y(IB);
clear a
end
if ~isempty(varargin)
switch lower(varargin{1})
case 'redolast'
n=find(flag ~=0,1,'last');
flag(n)=0;
x{n}=[];
y{n}=[];
end
end
for i=1:length(fileNames)
if flag(i) ~= 0; continue; end
fprintf('%d of %d\n',sum(flag ~= 0) + 1,length(fileNames))
[x{i},y{i},flag(i)]=imedit(fileNames{i});
save(outFile,'fileNames','x','y','flag');
eval(['! chmod 664 ',outFile]);
end
function [x,y,flag]=imedit(fileName)
I=readGeotiff(fileName);
%Ior=readGeotiff(strrep(fileName,'_dem_browse.tif','_ortho_browse.tif'));
% %%
% landclass = subsetGimpIceMask(...
% min(I.x)-30,max(I.x)+30,min(I.y)-30,max(I.y)+30);
%
% if ~isempty(landclass.ocean)
%
% if any(landclass.ocean(:))
%
%
% I.ocean = interp2(landclass.x,landclass.y(:),single(landclass.ocean),...
% I.x,I.y(:),'*nearest');
%
% I.z(logical(I.ocean))=0;
% end
% end
%%
imagesc(I.x,I.y,I.z,'alphadata',I.z ~= 0)
set(gca,'color','r')
axis xy equal tight;
colormap gray;
hold on;
% set(gcf,'units','normalized');
% set(gcf,'position',[0.01,0.01,.35,.9])
flag=[];
x=cell(1);
y=cell(1);
i=1;
while i
fprintf('%s\n',fileName)
flag=input('Enter quality flag: 1=good, 2=partial, 3=manual edit, 4=poor, 5=bad/error\n');
if ~isempty(flag)
if isnumeric(flag)
if flag == 1 || flag == 2 || flag == 3 || flag == 4 || flag == 5
break;
end
end
end
if iscell(flag); flag=flag{1}; end
fprintf('%d not recogized, try again\n',flag);
end
if flag == 1 || flag == 2; clf; return; end
if flag == 4 || flag == 5
x{1} = [min(I.x);min(I.x);max(I.x);max(I.x);min(I.x)];
y{1} = [min(I.y);max(I.y);max(I.y);min(I.y);min(I.y)];
clf
return
end
fprintf('entering manual edit mode\n')
while i
[~,x{i},y{i}] = roipoly;
plot(x{i},y{i},'r')
while i
s=input('continue editing this image? (y/n)\n','s');
if ~strcmpi(s,'y') && ~strcmpi(s,'n')
fprintf('%s not recogized, try again\n',s);
else
break
end
end
if strcmpi(s,'n'); break; end
i=i+1;
end
clf
|
github | ihowat/setsm_postprocessing-master | QCStripsByTile.m | .m | setsm_postprocessing-master/QCStripsByTile.m | 14,534 | utf_8 | b8a120517c227bece02070e7dbe83389 | function QCStripsByTile(regionNum,varargin)
%% Argins
%regionNum='02'; % region number
tilefile = 'PGC_Imagery_Mosaic_Tiles_Antarctica.mat'; %PGC/NGA Tile definition file, required
arcdemfile= 'rema_tiles.mat'; % lists which tiles go to which regions, required
dbasefile = 'rema_strips_8m_wqc_cs2bias.mat'; % database file
changePath='/Users/ihowat'; %if set, will change the path to the REMA directory from what's in the database file. set to [] if none.
% if an older set of mosaic files already exist, we can speed things up by
% check to see if they already have 100% coverage - will skip if do. Leave
% empty if none.
tileDir= dir(['/data4/REMA/region_',regionNum,'*']);
if ~isempty(tileDir)
tileDir= ['/data4/REMA/',tileDir(1).name,'/mosaic_reg_qc_feather/40m/'];
end
%% defaults
startfrom = 1;
minN = 500;
minArea = 500;
% parse inputs
for i=1:2:length(varargin)
eval([varargin{i},'=',num2str(varargin{i+1}),';']);
end
%% Find tiles in this region and load meta
% Get tile Defs
tiles=load(tilefile);
a=load(arcdemfile);
%remove duplicated tile entries keeping just first occurence
[~,n] = unique(a.tileName,'stable');
a = structfun(@(x) ( x(n) ), a, 'UniformOutput', false);
% get index of this region number
n=a.regionNum==str2num(regionNum);
% check to make sure we find sum
if ~(any(n)); error('no tiles matched for this region number'); end
% match region number to overlapping tiles
[~,n]=intersect(tiles.I,a.tileName(n));
% crop tile structure to overlapping tiles
tiles = structfun(@(x) ( x(n) ), tiles, 'UniformOutput', false);
% load database structure
meta=load(dbasefile);
% alter paths in database if set
if ~isempty(changePath)
meta.f = strrep(meta.f,'/data4',changePath);
meta.region = strrep(meta.region,'/data4',changePath);
end
%check meta file for required fields
if ~isfield(meta,'avg_rmse'); error('meta stucture missing avg_rmse field '); end
if ~isfield(meta,'xmax'); error('meta stucture missing xmax field '); end
if ~isfield(meta,'ymax'); error('meta stucture missing ymax field '); end
if ~isfield(meta,'xmin'); error('meta stucture missing ymin field '); end
if ~isfield(meta,'ymin'); error('meta stucture missing ymin field '); end
if ~isfield(meta,'x'); error('meta stucture missing x field '); end
if ~isfield(meta,'y'); error('meta stucture missing y field '); end
if ~isfield(meta,'f'); error('meta stucture missing f field '); end
% select the whichever registration has the better sigma_bias (all or 1 yr)
if isfield(meta,'sigma_all') && isfield(meta,'sigma_1yr') && ~isfield(meta,'sigma')
meta.sigma = nanmin([meta.sigma_all(:)';meta.sigma_1yr(:)'])';
end
% if no ground control error field, just set to nan
if ~isfield(meta,'sigma')
meta.sigma = nan(size(meta.f));
end
% if ground control error > 1, set to NaN
meta.sigma(meta.sigma > 1) = NaN;
% set 0 RMSE (single scenes) to NaN
meta.avg_rmse(meta.avg_rmse == 0) = NaN;
% tile loop
for i=startfrom:length(tiles.I)
fprintf(' \n')
fprintf('Working tile %d of %d: %s \n',i,length(tiles.I),tiles.I{i});
tile = structfun(@(x) ( x(i) ), tiles, 'UniformOutput', false);
% check existing tile for coverage
if ~isempty(tileDir)
if exist([tileDir,tile.I{1},'_40m_dem.mat'],'file')
load([tileDir,tile.I{1},'_40m_dem.mat'],'N');
if sum(N(:))./numel(N) == 1
fprintf('tile coverage complete, skipping\n')
clear N
continue
end
end
end
qctile(tile,meta,minN,minArea,changePath);
end
function qctile(tiles,meta,minN,minArea,changePath)
%% Spatial coverage search
% make tile boundary polygon
tilevx = [tiles.x0;tiles.x0;tiles.x1;tiles.x1;tiles.x0];
tilevy = [tiles.y0;tiles.y1;tiles.y1;tiles.y0;tiles.y0];
% quick search: find strips within range of this tile. This does not
% account for background area of around strips but just pairs them down to
% speed the poly intersection loop
n = meta.xmax > tiles.x0 & meta.xmin < tiles.x1 & ...
meta.ymax > tiles.y0 & meta.ymin < tiles.y1;
if ~any(n); fprintf('no strip overlap\n'); return; end
% get polys
meta = structfun(@(x) ( x(n,:) ), meta, 'UniformOutput', false);
% search for all strips overlapping this tile
in=zeros(size(meta.f));
for i=1:length(in)
in(i) = any(inpolygon(meta.x{i},meta.y{i},tilevx,tilevy)) | ...
any(inpolygon(tilevx,tilevy,meta.x{i},meta.y{i}));
end
if ~any(in); fprintf('no strip overlap\n'); return; end
% crop meta data struct to only overlapping strips
meta = structfun(@(x) ( x(logical(in),:) ), meta, 'UniformOutput', false);
fprintf('%d files overlapping this tile, ',sum(in));
% add existing qc data
meta = addQC2Meta(meta,changePath);
fprintf('%d files with existing qc\n',sum(meta.qc ~= 0));
% remove already added entries from metadata
if any(meta.qc == 5)
fprintf('removing %d files with qc flag=5\n',sum(meta.qc == 5));
meta = structfun(@(x) ( x(meta.qc ~= 5 ,:) ), meta, 'UniformOutput', false);
if isempty(meta.f); fprintf('all strips removed, returning \n'); return; end
end
% build grid
res = 40;
buff = 0;
x = tiles.x0-buff*res: res:tiles.x1+buff*res;
y = tiles.y1+buff*res:-res:tiles.y0-buff*res;
y = y(:);
N= zeros(length(y),length(x),'uint8');
% apply coastline
if isfield(tiles,'coastline')
fprintf('applying coastline, ');
A = false(size(N));
i=1;
for i=1:length(tiles.coastline{1})
if isempty(tiles.coastline{1}{i}); continue; end
A(roipoly(x,y,N,tiles.coastline{1}{i}(1,:),...
tiles.coastline{1}{i}(2,:))) = true;
end
percent_filled = 100*sum(~A(:))./numel(A);
if percent_filled > 0.2
N(~A) = 1;
else
percent_filled =0;
end
clear A
fprintf('%.2f%% filled as water\n',percent_filled);
if percent_filled == 100; fprintf('returning \n'); return; end
end
%% Build Grid Point Index Field
% make a cell for each file containing the col-wise indices of the data
% points on the tile grid. This is used search for new or existing data on
% the grid within each search iteration.
fprintf('calculating tile pixel coverage for each strip, ');
% initialize output field
meta.gridPointInd=cell(size(meta.f));
% can be slow, so we'll use a counter
count = 0;
% already qc'd files to add to N
add2N = meta.qc > 0 & meta.qc < 4;
fprintf('%d already qc-passed files will be added \n',sum(add2N))
if ~any(~add2N); fprintf('all files already passed qc, returning \n'); return; end
% file loop
for i=1:length(meta.f)
% counter
if i>1 for p=1:count fprintf('\b'); end; %delete line before
count = fprintf('strip %d of %d',i,size(meta.f,1));
end
% locate grid pixels within footprint polygon
BW = roipoly(x, y, N, meta.x{i}, meta.y{i});
%if mask data exists, apply it
if meta.qc(i) == 3
j=1;
for j=1:length(meta.maskPolyx{i})
BW(roipoly(x,y,BW,...
meta.maskPolyx{i}{j},meta.maskPolyy{i}{j}))=0;
end
end
% add if already qc'd
if add2N(i); N(BW) = 1; continue; end
% convert BW mask to col-wise indices and save to cell
meta.gridPointInd{i}=find(BW);
% get rid of mask
clear BW
end
% clear counter line
for p=1:count fprintf('\b'); end;
% check if filled
percent_filled = 100*sum(N(:))./numel(N);
fprintf('%.2f%% filled\n',percent_filled);
if percent_filled == 100; fprintf('returning \n'); return; end
% remove already added entries from metadata
meta = structfun(@(x) ( x(~add2N ,:) ), meta, 'UniformOutput', false);
% make another field with the number of data points
meta.gridPointN=cellfun(@length,meta.gridPointInd);
%remove strips below a minimum size
stripArea = nan(size(meta.f));
for i=1:length(meta.f)
stripArea(i) = polyarea(meta.x{i}, meta.y{i})./1000^2;
end
fprintf('removing %d strips smaller than %.1f km^2\n',sum(stripArea < minArea),minArea);
meta = structfun(@(x) ( x(stripArea >= minArea ,:) ), meta, 'UniformOutput', false);
%% coverage test loop
if ~isfield(meta,'rmse'); meta.rmse=nan(size(meta.f));end
if ~isfield(meta,'dtrans'); meta.dtrans=zeros(length(meta.f),3); end
if ~isfield(meta,'overlap'); meta.overlap=zeros(size(meta.f)); end % number existing data points overlapping file
%%
recountFlag=true;
skipn = 0;
while length(meta.f) >= 1
percent_filled = 100*sum(N(:))./numel(N);
if percent_filled == 100; fprintf('100%% filled returning \n',percent_filled); return; end
fprintf('%.2f%% filled\n', percent_filled);
% loop through files in boundary and find # of new/existing points
if recountFlag
for i=1:length(meta.f)
% subset of N at data points in this file
Nsub=N(meta.gridPointInd{i});
% count existing data points
meta.overlap(i)=sum(Nsub);
% count new data points
meta.gridPointN(i) = sum(~Nsub);
end
end
recountFlag=false;
% remove rendundant files (with already 100% coverage)
redundantFlag = meta.gridPointN < minN;
if any(redundantFlag)
% remove redundant files from lists
meta = structfun(@(x) ( x(~redundantFlag,:) ), meta, 'UniformOutput', false);
fprintf('%d redundant files (N < %d) removed\n',sum(redundantFlag),minN);
if isempty(meta.f); fprintf('all strips removed, returning \n'); return; end
end
A = nansum([100.*meta.gridPointN./numel(N),1./(meta.avg_rmse.^2)],2);
[~,n]=sort(A,'descend');
if skipn < 0; skipn = length(n)-1; end
% skip if skipped on last iteration
if length(n) >= 1+skipn
n = n(1+skipn);
else
n=n(1);
skipn = 0;
end
fprintf('%d of %d strips remaining\n',skipn+1,length(meta.f));
fileName=strrep(meta.f{n},'meta.txt','dem_browse.tif');
fprintf('%s\n',fileName);
fprintf('%d new pointsm, gcp sigma=%.2f, mean coreg RMSE=%.2f, max coreg RMSE=%.2f \n',...
meta.gridPointN(n),meta.sigma(n),meta.avg_rmse(n), meta.max_rmse(n));
% localfileName = strrep(fileName,'/data4/REMA','~/rema8mStripBrowse');
localfileName = fileName;
I=readGeotiff(localfileName);
Ni=interp2(x,y(:),N,I.x,I.y(:),'*nearest');
imagesc(I.x,I.y,I.z,'alphadata',single(I.z ~= 0))
set(gca,'color','r')
axis xy equal tight;
colormap gray;
hold on;
imagesc(I.x,I.y,Ni,'alphadata',single(Ni).*.5)
if isfield(tiles,'coastline')
i=1;
for i=1:length(tiles.coastline{1})
if isempty(tiles.coastline{1}{i}); continue; end
plot(tiles.coastline{1}{i}(1,:),...
tiles.coastline{1}{i}(2,:),'b','linewidth',1)
end
end
plot([tiles.x0,tiles.x0,tiles.x1,tiles.x1,tiles.x0], [tiles.y0,tiles.y1,tiles.y1,tiles.y0,tiles.y0],'w','linewidth',2)
set(gca,'xlim',[min(I.x)-500 max(I.x)+500],'ylim',[min(I.y)-500 max(I.y)+500]);
%set(gcf,'units','normalized');
%set(gcf,'position',[0.01,0.01,.35,.9])
qc=load([fileparts(fileName),'/qc.mat']);
fileNames = qc.fileNames;
% alter paths in database if set
if ~isempty(changePath)
fileNames = strrep(fileNames,'/data4',changePath);
end
[~,IA]=intersect(fileNames, fileName);
if isempty(IA); error('this file name not matched in the qc.mat, probably need to upadate it.'); end
if qc.flag(IA) ~= 4 && qc.flag(IA) ~= 0
fprintf('flag previoulsy changed to %d, applying\n',qc.flag(IA))
else
j=1;
while j
try
flag=input('Enter quality flag: 0=skip,9=back, 1=good, 2=partial, 3=manual edit, 4=poor, 5=unuseable, 6=quit\n');
if ~isempty(flag)
if isnumeric(flag)
if flag == 0 || flag == 9 || flag == 1 || flag == 2 || flag == 3 || flag == 4 || flag == 5 || flag == 6
break;
end
end
end
catch
fprintf('%d not recogized, try again\n',flag);
end
if iscell(flag); flag=flag{1}; end
fprintf('%d not recogized, try again\n',flag);
end
if flag == 6; clf; return; end
if flag == 0; skipn = skipn+1; clf; continue; end
if flag == 9; skipn = skipn-1; clf; continue; end
qc.flag(IA)=flag;
if flag == 1 || flag == 2
qc.x{IA}=cell(1); qc.y{IA}=cell(1);
end
if flag == 3
fprintf('entering manual edit mode\n')
j=1;
while j
[~,qc.x{IA}{j},qc.y{IA}{j}] = roipoly;
plot(qc.x{IA}{j},qc.y{IA}{j},'g','linewidth',2)
while j
s=input('continue editing this image? (y/n)\n','s');
if ~strcmpi(s,'y') && ~strcmpi(s,'n')
fprintf('%s not recogized, try again\n',s);
else
break
end
end
if strcmpi(s,'n'); break; end
j=j+1;
end
end
save([fileparts(fileName),'/qc.mat'],'-struct','qc');
end
clf
if qc.flag(IA) > 0 && qc.flag(IA) < 4
M = I.z ~=0;
j=1;
for j=1:length(qc.x{IA})
M(roipoly(I.x,I.y,M,qc.x{IA}{j},qc.y{IA}{j}))=0;
end
M=interp2(I.x,I.y(:),single(M),x,y(:),'*nearest');
N(M == 1) = 1;
recountFlag=true;
% remove this file from the meta struct
in=1:length(meta.f); in(n)=[];
meta = structfun(@(x) ( x(in,:) ), meta, 'UniformOutput', false);
skipn = 0;
elseif qc.flag(IA) == 4 || qc.flag(IA) == 5
% remove this file from the meta struct
in=1:length(meta.f); in(n)=[];
meta = structfun(@(x) ( x(in,:) ), meta, 'UniformOutput', false);
end
end
% |
github | ihowat/setsm_postprocessing-master | scenes2strips.m | .m | setsm_postprocessing-master/scenes2strips.m | 11,888 | utf_8 | 43d6e503811d77f86c6c1e33be32256c | function [X,Y,Z,M,O,trans,rmse,f]=scenes2strips(demdir,f)
%SCENES2STRIPS merge scenes into strips
%
% [x,y,z,m,o,trans,rmse,f]=scenes2strips(demdir,f) merges the
% scene geotiffs listed in cellstr f within directory demdir after
% ordering them by position. If a break in coverage is detected between
% scene n and n+1 only the first 1:n scenes will be merged. The data are
% coregistered at overlaps using iterative least squares, starting with
% scene n=1.
% Outputs are the strip grid coorinates x,y and strip elevation, z,
% matchtag, m and orthoimage, o. The 3D translations are given in 3xn
% vector trans, along with root-mean-squared of residuals, rmse. The
% output f gives the list of filenames in the mosaic. If a break is
% detected, the list of output files will be less than the input.
%
% Version 3.0, Ian Howat, Ohio State University, 2015
%% Order Scenes in north-south or east-west direction by aspect ratio
fprintf('ordering %d scenes\n',length(f))
f = orderPairs(demdir,f);
% intialize output stats
trans=zeros(3,length(f));
rmse=zeros(1,length(f));
% file loop
for i=1:length(f)
% construct filenames
demFile = [demdir,'/',f{i}];
matchFile= strrep(demFile,'dem.tif','matchtag.tif');
orthoFile= strrep(demFile,'dem.tif','ortho.tif');
%shadeFile= strrep(demFile,'dem.tif','dem_shade.tif');
edgeMaskFile= strrep(demFile,'dem.tif','edgemask.tif');
dataMaskFile= strrep(demFile,'dem.tif','datamask.tif');
fprintf('scene %d of %d: %s\n',i,length(f),demFile)
try
[x,y,z,o,m,me,md] = loaddata(demFile,matchFile,orthoFile,edgeMaskFile,...
dataMaskFile);
catch ME
fprintf('%s %s: data read error, skipping \n',ME.identifier,ME.message);
continue;
end
% check for no data
if ~any(md(:)); fprintf('no data, skipping \n'); continue; end;
%Apply Masks
[x,y,z,o,m] = applyMasks(x,y,z,o,m,me,md);
dx = x(2)-x(1);
dy = y(2)-y(1);
% check for non-integer grid
if rem(x(1)./dx,1) ~= 0 || rem(y(1)./dy,1) ~= 0
[x,y,z,m,o] = regrid(x,y,z,m,o);
end
% if first scene in strip, set as strip and continue to next scene
if ~exist('X','var')
X=x; clear x;
Y=y; clear y;
Z=z; clear z;
M=m; clear m;
O=o; clear o;
continue;
end
% pad new arrays to stabilize interpolation
buff=10*dx+1;
z=padarray(z,[buff buff],NaN);
m=padarray(m,[buff buff]);
o=padarray(o,[buff buff]);
x=[x(1)-dx.*(buff:-1:1),x,x(end)+dx.*(1:buff)];
y=[y(1)+dx.*(buff:-1:1),y,y(end)-dx.*(1:buff)];
% expand strip coverage to encompass new scene
if x(1) < X(1);
X1=x(1):dx:X(1)-dx;
X=[X1,X];
Z=[nan(size(Z,1),length(X1)),Z];
M=[false(size(M,1),length(X1)),M];
O=[zeros(size(O,1),length(X1)),O];
clear X1
end
if x(end) > X(end);
X1=X(end)+dx:dx:x(end);
X=[X,X1];
Z=[Z,nan(size(Z,1),length(X1))];
M=[M,false(size(M,1),length(X1))];
O=[O,zeros(size(O,1),length(X1))];
clear X1
end
if y(1) > Y(1);
Y1=y(1):-dx:Y(1)+dx;
Y=[Y1,Y];
Z=[nan(length(Y1),size(Z,2));Z];
M=[false(length(Y1),size(M,2));M];
O=[zeros(length(Y1),size(O,2));O];
clear Y1
end
if y(end) < Y(end);
Y1=Y(end)-dx:-dx:y(end);
Y=[Y,Y1];
Z=[Z;nan(length(Y1),size(Z,2))];
M=[M;false(length(Y1),size(M,2))];
O=[O;zeros(length(Y1),size(O,2))];
clear Y1;
end
% map new dem pixels to swath. These must return integers. If not,
% interpolation will be required, which is currently not supported.
c0 = find(x(1) == X);
c1 = find(x(end) == X);
r0 = find(y(1) == Y);
r1 = find(y(end) == Y);
%crop to overlap
Zsub=Z(r0:r1,c0:c1);
Xsub=X(c0:c1);
Ysub=Y(r0:r1);
Msub=M(r0:r1,c0:c1);
Osub=O(r0:r1,c0:c1);
%% NEW MOSAICING CODE
% crop to just region of overlap
A= single( ~isnan(Zsub) & ~isnan(z));
%check for segment break
if sum(A(:)) <= 1000;
f=f(1:i-1);
trans = trans(:,1:i-1);
rmse = rmse(1:i-1);
break
end
A(A==0)=NaN;
[~,r,c] = cropnans(A,buff);
%Make overlap mask removing isolated pixels
A=single(bwareaopen(...
isnan(Zsub(r(1):r(2),c(1):c(2))) & ~isnan(z(r(1):r(2),c(1):c(2))),...
1000)); % nodata in strip and data in scene is a one
% check for redundant scene
if sum(A(:)) <= 1000; fprintf('redundant scene, skipping \n'); continue; end;
A(bwareaopen(...
~isnan(Zsub(r(1):r(2),c(1):c(2))) & isnan(z(r(1):r(2),c(1):c(2))),...
1000))=2;
% data in strip and no data in scene is a two
% tic
% % USING REGIONFILL - Requires matlab 2015a or newer
% A = regionfill(A,A==0) -1;
% toc
Ar=imresize(A,.1,'nearest');
[C R] = meshgrid(1:size(Ar,2),1:size(Ar,1));
% pixles on outside of boundary of overlap region
B = bwboundaries(Ar~=0, 8, 'noholes');
B = cell2mat(B);
n=sub2ind(size(Ar),B(:,1),B(:,2));
warning off
F = scatteredInterpolant(C(n),R(n),double(Ar(n)));
warning on
Ar(Ar==0)=F(C(Ar==0),R(Ar==0));
Ar=imresize(Ar,size(A),'bilinear');
Ar(A==1 & Ar ~=1)=1;
Ar(A==2 & Ar ~=2)=2;
A=Ar-1;
A(A < 0) = 0;
A(A > 1) = 1;
W=single(~isnan(Zsub));
W(r(1):r(2),c(1):c(2)) = A; clear A
W(isnan(Zsub) & isnan(z)) = NaN;
% shift weights so that more of the reference layer is kept
f0=.25; % overlap fraction where ref z weight goes to zero
f1=.55; % overlap fraction where ref z weight goes to one
W=(1/(f1-f0)).*W-f0/(f1-f0);
W(W > 1) = 1;
W(W < 0) = 0;
% remove <25% edge of coverage from each in pair
Zsub(W == 0) = NaN;
Msub(W == 0) = 0;
Osub(W == 0) = 0;
z(W >= 1) = NaN;
m(W >= 1) = 0;
o(W >= 1) = 0;
%% Coregistration
% coregister this scene to the strip mosaic
[~,trans(:,i),rmse(i)] = ...
coregisterdems(Xsub(c(1):c(2)),Ysub(r(1):r(2)),...
Zsub(r(1):r(2),c(1):c(2)),...
x(c(1):c(2)),y(r(1):r(2)),...
z(r(1):r(2),c(1):c(2)),...
Msub(r(1):r(2),c(1):c(2)),...
m(r(1):r(2),c(1):c(2)));
%check for segment break
if isnan(rmse(i));
fprintf('Unable to coregister, breaking segment\n')
f=f(1:i-1);
trans = trans(:,1:i-1);
rmse = rmse(1:i-1);
break
end
% interpolation grid
xi=x - trans(2,i);
yi=y - trans(3,i);
%check uniform spacing is maintained (sometimes rounding errors)
if length(unique(diff(xi))) > 1; xi=round(xi,4); end
if length(unique(diff(yi))) > 1; yi=round(yi,4); end
% interpolate the floating data to the reference grid
zi = interp2(xi,yi,z-trans(1,i),Xsub(:)',Ysub(:),'*linear');
clear z
% interpolate the mask to the same grid
mi = interp2(xi,yi,single(m),Xsub(:)',Ysub(:),'*nearest');
mi(isnan(mi)) = 0; % convert back to uint8
mi = logical(mi);
clear m
% interpolate ortho to same grid
oi = single(o);
oi(oi==0) = NaN; % set border to NaN so wont be interpolated
oi = interp2(xi,yi,oi,Xsub(:)',Ysub(:),'*cubic');
clear o
clear Xsub Ysub
% remove border 0's introduced by nn interpolation
M3 = ~isnan(zi);
M3=imerode(M3,ones( 6 )); % border cutline
zi(~M3)=NaN;
mi(~M3)=0;
clear M3
% remove border on orthos seperately
M4= ~isnan(oi);
M4=imerode(M4,ones( 6 ));
oi(~M4)=NaN;
clear M4
% make weighted elevation grid
A= Zsub.*W + zi.*(1-W);
A( isnan(Zsub) & ~isnan(zi))= zi( isnan(Zsub) & ~isnan(zi));
A(~isnan(Zsub) & isnan(zi))=Zsub(~isnan(Zsub) & isnan(zi));
clear zi Zsub
% put strip subset back into full array
Z(r0:r1,c0:c1) = A;
clear A
% for the matchtag, just straight combination
M(r0:r1,c0:c1) = Msub | mi;
clear Msub Mi
% make weighted ortho grid
Osub = single(Osub);
Osub(Osub==0) = NaN;
A= Osub.*W + oi.*(1-W);
clear W
A( isnan(Osub) & ~isnan(oi))= oi( isnan(Osub) & ~isnan(oi));
A(~isnan(Osub) & isnan(oi))= Osub(~isnan(Osub) & isnan(oi));
clear Osub oi
A(isnan(A)) = 0; % convert back to uint16
A = uint16(A);
O(r0:r1,c0:c1) = A;
clear A
end
%crop to data
if exist('Z','var') && any(~isnan(Z(:)))
[Z,rcrop,ccrop] = cropnans(Z);
if ~isempty(rcrop);
X = X(ccrop(1):ccrop(2));
Y = Y(rcrop(1):rcrop(2));
M = M(rcrop(1):rcrop(2),ccrop(1):ccrop(2));
O = O(rcrop(1):rcrop(2),ccrop(1):ccrop(2));
Z(isnan(Z)) = -9999;
end
else
X=[]; Y=[]; Z=[]; M=[]; O=[];
end
function [x,y,z,o,m,me,md] = loaddata(demFile,matchFile,orthoFile,edgeMaskFile,dataMaskFile)
% loaddata load data files and perform basic conversions
d=readGeotiff(demFile); x=d.x; y=d.y; z=d.z; clear d
sz=size(z);
d=readGeotiff(matchFile);
szd=size(d.z);
if any(szd ~= sz);
m = interp2(d.x,d.y,single(d.z),...
x(:)',y(:),'*nearest');
m(isnan(m)) = 0; % convert back to uint16
m = logical(m);
else
m=d.z;
end
clear d
o=zeros(size(z));
if exist(orthoFile,'file')
d=readGeotiff(orthoFile);
szd=size(d.z);
if any(szd ~= sz);
d.z = single(d.z);
d.z(d.z==0) = NaN; % set border to NaN so wont be interpolated
o = interp2(d.x,d.y,d.z,...
x(:)',y(:),'*cubic');
o(isnan(o)) = 0; % convert back to uint16
o = uint16(o);
else
o=d.z;
end
clear d
end
if exist(edgeMaskFile,'file')
d=readGeotiff(edgeMaskFile);
szd=size(d.z);
if any(szd ~= sz); error('edgemaskfile wrong dimensions'); end
me=d.z;
clear d;
else
warning('No edgeMaskFile found, no mask applied')
me=ones(sz,'logical');
end
if exist(dataMaskFile,'file')
d=readGeotiff(dataMaskFile);
szd=size(d.z);
if any(szd ~= sz); error('datamaskfile wrong dimensions'); end
md=d.z;
else
warning('No dataMaskFile found, no mask applied')
md=ones(sz,'logical');
end
z(z < -100 | z == 0 | z == -NaN | isinf(z) ) = NaN;
function [x,y,z,o,m] = applyMasks(x,y,z,o,m,me,md)
z(~md) = NaN;
m(~md) = 0;
o(~me) = 0;
if any(~isnan(z(:)));
[z,rcrop,ccrop] = cropnans(z);
x = x(ccrop(1):ccrop(2));
y = y(rcrop(1):rcrop(2));
m = m(rcrop(1):rcrop(2),ccrop(1):ccrop(2));
o = o(rcrop(1):rcrop(2),ccrop(1):ccrop(2));
end
function [X,Y,Z,M,O] = regrid(X,Y,Z,M,O)
dx = X(2)-X(1);
dy = Y(2)-Y(1);
Xi = X(1) + (dx-rem(X(1)/dx,1)*dx):dx:X(end);
Yi = Y(1) - (rem(Y(1)/dy,1)*dy):dy:Y(end);
Zi = interp2(X,Y(:),Z,Xi,Yi(:),'*linear');
M = interp2(X,Y(:),single(M),Xi,Yi(:),'*nearest');
M(isnan(M)) = 0; % convert back to uint8
M = logical(M);
% interpolate ortho to same grid
O = single(O);
O(isnan(Z)) = NaN; % set border to NaN so wont be interpolated
O = interp2(X,Y(:),O,Xi,Yi(:),'*cubic');
O(isnan(O)) = 0; % convert back to uint16
O = uint16(O);
Z = Zi;
X = Xi;
Y = Yi;
function [A,r,c] = cropnans(varargin)
% cropnans crop array of bordering nans
%
% [A,r,c] = cropnans(A)
A=varargin{1};
buff=0;
if nargin == 2; buff=varargin{2}; end
r = [];
c = [];
M = ~isnan(A);
if ~any(M(:)); return; end
rowsum = sum(M) ~= 0;
colsum = sum(M,2) ~= 0;
c(1) = find(rowsum,1,'first')-buff;
c(2) = find(rowsum,1,'last')+buff;
r(1) = find(colsum,1,'first')-buff;
r(2) = find(colsum,1,'last')+buff;
if c(1) < 1; c(1)=1; end
if r(1) < 1; r(1)=1; end
if c(2) > size(A,2); c(2)=size(A,2); end
if r(2) > size(A,1); r(2)=size(A,1); end
A = A(r(1):r(2),c(1):c(2));
|
github | ihowat/setsm_postprocessing-master | DecimatePoly.m | .m | setsm_postprocessing-master/DecimatePoly.m | 7,059 | utf_8 | 59d47c972e3d1145b213349afa979c50 | function [C_out,i_rem]=DecimatePoly(C,opt)
% Reduce the complexity of a 2D simple (i.e. non-self intersecting), closed
% piecewise linear contour by specifying boundary offset tolerance.
% IMPORTANT: This function may not preserve the topology of the original
% polygon.
%
% INPUT ARGUMENTS:
% - C : N-by-2 array of polygon co-ordinates, such that the first,
% C(1,:), and last, C(end,:), points are the same.
% - opt : opt can be specified in one of two ways:
% ----------------------APPROACH #1 (default) -----------------
% - opt : opt=[B_tol 1], where B_tol is the maximum acceptible
% offset from the original boundary, B_tol must be
% expressed in the same lenth units as the co-ords in
% C. Default setting is B_tol=Emin/2, where Emin is the
% length of the shortest edge.
% ----------------------APPROACH #2----------------------------
% - opt : opt=[P_tol 2], where P_tol is the fraction of the
% total number of polygon's vertices to be retained.
% Accordingly, P_tol must be a real number on the
% interval (0,1).
%
% OUTPUT:
% - C_out : M-by-2 array of polygon coordinates.
% - i_rem : N-by-1 logical array used to indicate which vertices were
% removed during decimation.
%
% ALGORITHM:
% 1) For every vertex compute the boundary offset error.
% 2) Rank all vertics according to the error score from step 1.
% 3) Remove the vertex with the lowest error.
% 4) Recompute and accumulate the errors for the two neighbours adjacent to
% the deleted vertex and go back to step 2.
% 5) Repeat step 2 to 4 until no more vertices can be removed or the number
% of vertices has reached the desired number.
%
% AUTHOR: Anton Semechko ([email protected])
% DATE: Jan.2011
%
% Check the input args
if nargin<2, opt={}; end
opt=CheckInputArgs(C,opt);
N=size(C,1);
i_rem=false(N,1);
if N<=4,
C_out=C;
return
end
% Tolerance parameter, perimeter and area of the input polygon
[Po,Emin]=PolyPerim(C);
B_tol=Emin/2;
Ao=PolyArea(C);
No=N-1;
if ~isempty(opt), B_tol=opt(1); end
Nmin=3;
if opt(2)==2
Nmin=round((N-1)*opt(1));
if (N-1)==Nmin, return; end
if Nmin<3, Nmin=3; end
end
% Remove the (repeating) end-point
C(end,:)=[];
N=N-1;
% Compute the distance offset errors --------------------------------------
D31=circshift(C,[-1 0])-circshift(C,[1 0]);
D21=C-circshift(C,[1 0]);
dE_new2=sum(D31.^2,2); % length^2 of potential new edges
% Find the closest point to the current vertex on the new edge
t=sum(D21.*D31,2)./dE_new2;
if t<0, t(t<0)=0; end %#ok<*BDSCI>
if t>1, t(t>1)=1; end
V=circshift(C,[1 0])+bsxfun(@times,t,D31);
% Evaluate the distance^2
Err_D2=sum((V-C).^2,2);
% Initialize distance error accumulation array
DEAA=zeros(N,1);
% Begin decimation --------------------------------------------------------
idx_ret=1:N; % keep track of retained vertices
while true
% Find the vertices whose removal will satisfy the decimation criterion
idx_i=Err_D2<B_tol;
if sum(idx_i)==0 && N>Nmin && opt(2)==2
B_tol=B_tol*sqrt(1.5);
continue
end
idx_i=find(idx_i);
if isempty(idx_i) || N==Nmin, break; end
N=N-1;
% Vertex with the smallest net error
[~,i_min]=min(Err_D2(idx_i));
idx_i=idx_i(i_min);
% Update the distance error accumulation array
DEAA(idx_i)=DEAA(idx_i)+sqrt(Err_D2(idx_i));
i1=idx_i-1; if i1<1, i1=N; end
i3=idx_i+1; if i3>N, i3=1; end
DEAA(i1)=DEAA(idx_i);
DEAA(i3)=DEAA(idx_i);
% Recompute the errors for the vertices neighbouring the vertex marked
% for deletion
i1_1=i1-1; if i1_1<1, i1_1=N; end
i1_3=i3;
i3_1=i1;
i3_3=i3+1; if i3_3>N, i3_3=1; end
err_D1=RecomputeErrors(C([i1_1,i1,i1_3],:));
err_D3=RecomputeErrors(C([i3_1,i3,i3_3],:));
% Upadate the errors
Err_D2(i1)=(sqrt(err_D1)+ DEAA(i1)).^2;
Err_D2(i3)=(sqrt(err_D3)+ DEAA(i3)).^2;
% Remove the vertex
C(idx_i,:)=[];
idx_ret(idx_i)=[];
DEAA(idx_i)=[];
Err_D2(idx_i)=[];
end
C=[C;C(1,:)]; C_out=C;
i_rem(idx_ret)=true;
i_rem=~i_rem;
i_rem(end)=i_rem(1);
% Perimeter and area of the simplified polygon
P=PolyPerim(C);
A=PolyArea(C);
% Performance summary
fprintf('\t\t# of verts\t\tperimeter\t\tarea\n')
fprintf('in\t\t%-5u\t\t\t%-.2f\t\t\t%-.2f\n',No,Po,Ao)
fprintf('out\t\t%-5u\t\t\t%-.2f\t\t\t%-.2f\n',N,P,A)
fprintf('-----------------------------------------------------\n')
fprintf('change\t%-5.2f%%\t\t\t%-5.2f%%\t\t\t%-5.2f%%\n\n',(N-No)/No*100,(P-Po)/Po*100,(A-Ao)/Ao*100)
%==========================================================================
function err_D2=RecomputeErrors(V)
% Recompute the distance offset error for a small subset of polygonal
% vertices.
%
% - V : 3-by-2 array of triangle vertices, where V(2,:) is the vertex
% marked for removal.
% Compute the distance offset error ---------------------------------------
D31=V(3,:)-V(1,:);
D21=V(2,:)-V(1,:);
dE_new2=sum(D31.^2,2); % length^2 of potential new edge
% Find the closest point to the current vertex on the new edge
t=sum(D21.*D31,2)/dE_new2;
if t<0, t(t<0)=0; end
if t>1, t(t>1)=1; end
p=V(1,:)+bsxfun(@times,t,D31);
% Evaluate the distance^2
err_D2=sum((p-V(2,:)).^2);
%==========================================================================
function [P,Emin]=PolyPerim(C)
% Polygon perimeter.
dE=C(2:end,:)-C(1:(end-1),:);
dE=sqrt(sum(dE.^2,2));
P=sum(dE);
Emin=min(dE);
%==========================================================================
function A=PolyArea(C)
% Polygon area.
dx=C(2:end,1)-C(1:(end-1),1);
dy=C(2:end,2)+C(1:(end-1),2);
A=abs(sum(dx.*dy)/2);
%==========================================================================
function opt=CheckInputArgs(C,opt)
% Check the validity of the input arguments
siz=size(C);
if numel(siz)~=2 || siz(2)>siz(1) || ~isnumeric(C) || ~ismatrix(C) || ndims(C)~=2
error('First input argument must be a N-by-2 array of polygon vertices')
end
if ~isequal(C(1,:),C(end,:))
error('First and last points in C must be the same')
end
if isempty(opt), return; end
if ~isnumeric(opt) || numel(opt)~=2
error('Incorrect entry for 2nd input argument')
end
if ~(opt(2)==1 || opt(2)==2)
error('Incorrect entry for 2nd input argument. opt(2) must be set to 1 or 2.')
end
if opt(2)==1 && opt(1)<=eps
error('Incorrect entry for 2nd input argument. When opt(2)==1, opt(1) must be greater than zero.')
end
if opt(2)==2 && (opt(1)<=eps || opt(1)>=1)
error('Incorrect entry for 2nd input argument. When opt(2)==2, opt(1) must be on the interval (0,1).')
end
|
github | rajul614/ResolutionTheoremSolving-master | CS4300_PL_Resolve.m | .m | ResolutionTheoremSolving-master/CS4300_PL_Resolve.m | 1,448 | utf_8 | f202bde8ee21c01221056b1194d7fec7 | function resolvents = CS4300_PL_Resolve(clause1,clause2)
% CS4300_PL_Resolve - resolution theorem prover
% On input:
% clause1 : 1rst conjuctive clause
% clause2 : 2nd conjuctive clause
% On output:
% resolvents : results of resolve
% Call:
% resolvents = CS4300_PL_Resolve([17,-2,5],[-17,5]);
% Author:
% Rajul Ramchandani and Conan Zhang
% UU
% Fall 2016
%
resolvents = [];
num_resolvent = 1;
for c1 = 1:length(clause1)
d1 = clause1(c1);
for c2 = 1:length(clause2)
d2 = clause2(c2);
if(d1 == -d2)
v1 = [clause1(1:c1-1), clause1(c1+1:end),clause2(1:c2-1), clause2(c2+1:end)];
%v1 = Rem_Contradictions(v1);
v1 = unique(v1);
resolvents(num_resolvent).clauses = sort(v1);
num_resolvent = num_resolvent + 1;
end
end
end
resolvents = Rem_Duplicates(resolvents);
%ask prof about removing duplicates
end
function rem_contradictions = Rem_Contradictions(v1)
rem_contradictions = [];
rem_counter = 1;
for i = 1:length(v1)
for j = i+1:length(v1)
if(v1(i) == -v1(j))
v1(i) = 0;
v1(j) = 0;
end
end
end
for i = 1:length(v1)
if(v1(i) ~= 0)
rem_contradictions(rem_counter) = v1(i);
rem_counter = rem_counter + 1;
end
end
end
|
github | rajul614/ResolutionTheoremSolving-master | CS4300_RTP.m | .m | ResolutionTheoremSolving-master/CS4300_RTP.m | 2,976 | utf_8 | a79b8bf9a2c5b8869846b2cb5155784c | function Sip = CS4300_RTP(sentences,thm,vars)
% CS4300_RTP - resolution theorem prover
% On input:
% clause (CNF data structure): array of conjuctive clauses
% (i).clauses
% each clause is a list of integers (- for negated literal)
% thm (CNF datastructure): a disjunctive clause to be tested
% vars (1xn vector): list of variables (positive integers)
% On output:
% Sip (CNF data structure): results of resolution
% []: proved sentence |- thm
% not []: thm does not follow from clause
% Call: (example from Russell & Norvig, p. 252)
% DP(1).clauses = [-1,2,3,4];
% DP(2).clauses = [-2];
% DP(3).clauses = [-3];
% DP(4).clauses = [1];
% thm = [4];
% vars = [1,2,3,4];
% Sr = CS4300_RTP(DP,thm,vars);
% Author:
% Rajul Ramchandani and Conan Zhang
% UU
% Fall 2016
%
clause = sentences;
new = [];
iteration_count = 0;
for k = 1:length(thm)
clause(end+1).clauses = -thm(k);
end
initial_clause_count = length(clause)
ctable = {};
while 1
for c1 = 1:length(clause)
for c2 = c1+1:length(clause)
iteration_count = iteration_count + 1;
resolvents = CS4300_PL_Resolve(clause(c1).clauses, clause(c2).clauses);
%Uncomment to get ctable with [c1] [c2] [resolvents]
% ctable{end+1, 1} = c1;
% ctable{end, 2} = c2;
% if Contains_Empty_Clause(resolvents)
% ctable{end, 3} = [];
% elseif(~isempty(resolvents))
% ctable{end, 3} = resolvents.clauses
% end
if Contains_Empty_Clause(resolvents)
Sip = [];
%Uncomment to print ctable when done
%ctable
sentences_produced = length(clause) - initial_clause_count
iteration_count
return;
end
new = [new resolvents];
new = Rem_Duplicates(new);
%Uncomment for Table of with new for every iteration
%T = struct2table(new)
end
end
if Is_Subset(new, clause)
Sip = clause;
sentences_produced = length(clause) - initial_clause_count
iteration_count
return;
end
clause = [clause, new];
clause = Rem_Duplicates(clause);
end
end
function contains_empty = Contains_Empty_Clause(resolvents)
contains_empty = 0;
for i = 1:length(resolvents)
if isempty(resolvents(i).clauses)
contains_empty = 1;
return;
end
end
end
function is_subset = Is_Subset(new, clause)
is_subset = 0;
counter = 0;
for r1 = 1:length(new)
currentNew = new(r1);
for r2 = 1:length(clause)
currentSentence = clause(r2);
if isequal(currentNew, currentSentence)
counter = counter + 1;
end
end
end
if counter == length(new)
is_subset = 1;
end
end |
github | MengLiuPurdue/find_densest_subgraph-master | max_density.m | .m | find_densest_subgraph-master/small_graph_test/max_density.m | 653 | utf_8 | 0a737e85e2fd52f22a72a295a9c10cbc | %find the subgraph with the maximum density in an undirected graph through brutal search
%the undirected graph is represented by an adjcent matrix A
%density is the maximum density and cut is the corresponding subgraph
function [density,cut]=max_density(A)
density=0;
[n,n]=size(A);
for i=0:(2^n-1)
temp=0;
a=bitget(i,n:-1:1);
for j=1:n
for k=1:n
if a(j)*a(k)*A(j,k)~=0
temp=temp+A(j,k);
end
end
end
count=sum(a);
temp=temp/count;
if temp>density
max_cut=a;
density=temp;
end
end
j=1;
for i=1:n
if max_cut(i)==1
cut(j,1)=i;
j=j+1;
end
end
|
github | MengLiuPurdue/find_densest_subgraph-master | readSMAT.m | .m | find_densest_subgraph-master/matlab_wrapper_sparse/readSMAT.m | 2,054 | utf_8 | df9a6fc0686543129dd465f7a5fb0991 | function A = readSMAT(filename)
% readSMAT reads an indexed sparse matrix representation of a matrix
% and creates a MATLAB sparse matrix.
%
% A = readSMAT(filename)
% filename - the name of the SMAT file
% A - the MATLAB sparse matrix
%
% David Gleich
% Copyright, Stanford University, 2005-2010
if (~exist(filename,'file'))
error('readSMAT:fileNotFound', 'Unable to read file %s', filename);
end
if (exist(strcat(filename, '.info'), 'file'))
s = load(filename);
mdata = load(strcat(filename, '.info'));
ind_i = s(:,1)+1;
ind_j = s(:,2)+1;
val = s(:,3);
A = sparse(ind_i,ind_j,val, mdata(1), mdata(2));
return;
end;
[pathstr,name,ext] = fileparts(filename);
if ~isempty(strfind(ext,'.gz'))
[m n i j v] = readSMATGZ(realpath(filename));
A = sparse(i,j,v,m,n);
return;
end;
s = load(filename,'-ascii');
m = s(1,1);
n = s(1,2);
try
ind_i = s(2:length(s),1)+1;
ind_j = s(2:length(s),2)+1;
val = s(2:length(s),3);
clear s;
A = sparse(ind_i,ind_j,val, m, n);
catch
fprintf('... trying block read ...\n');
blocksize = 1000000;
curpos = 2;
blocknum = 1;
nzleft = s(1,3);
A = sparse(m,n);
while (nzleft > 0)
curblock = min(nzleft, blocksize);
fprintf('block %i (%i - %i)\n', blocknum, curpos-1, curpos+curblock-2);
curpart = curpos:(curpos+curblock-1);
ind_i = s(curpart,1)+1;
ind_j = s(curpart,2)+1;
val = s(curpart,3);
A = A + sparse(ind_i, ind_j, val, m, n);
nzleft = nzleft - curblock;
curpos = curpos + curblock;
blocknum = blocknum + 1;
end
end
function S = merge_structs(A, B)
% MERGE_STRUCTS Merge two structures.
%
% S = merge_structs(A, B) makes the structure S have all the fields from A
% and B. Conflicts are resolved by using the value in A.
%
%
% merge_structs.m
% David Gleich
%
% Revision 1.00
% 19 Octoboer 2005
%
S = A;
fn = fieldnames(B);
for ii = 1:length(fn)
if ~isfield(A, fn{ii})
S.(fn{ii}) = B.(fn{ii});
end
end |
github | MengLiuPurdue/find_densest_subgraph-master | run_densest_subgraph.m | .m | find_densest_subgraph-master/6_node_test/run_densest_subgraph.m | 3,172 | utf_8 | a5045a1820edce666c0b310b580a1100 | function [S,density,algd] = run_densest_subgraph(A)
% Write output and run the commands
% assert(issymmetric(A));
% assert(~any(diag(A)));
mydir = fileparts(mfilename('fullpath'));
mygfile = fullfile(mydir,'run_dsubgraph.smat');
myoutfile = fullfile(mydir,'run-dsubgraph.out');
writeSMAT(mygfile, A);
status = system(sprintf(...
'"%s" "%s" "%s"', fullfile(mydir, 'find_densest_subgraph'), ...
mygfile,myoutfile));
if status == 0
try
fid = fopen(myoutfile, 'r');
algd = textscan(fid, '%f', 1);
algd = algd{1};
num = textscan(fid, '%d', 1);
vals = textscan(fid, '%d', num{1});
S = vals{1}+1;
density = full(sum(sum(A(S,S)))/numel(S));
fclose(fid);
catch me
fclose(fid);
rethrow(me)
end
end
if nargout < 2
fprintf(' Output density: %f\n', algd);
fprintf(' Computed density: %f\n', density);
end
function writeSMAT(filename, A, optionsu)
% WRITESMAT writes a matrix in a sparse matrix (SMAT) form.
%
% WRITESMAT(filename, A, options)
% filename - the filename to write
% A - the matrix
%
% options.format value format (e.g. %i or %f)
% options.ut upper triangular (only print the upper triangular part)
% options.graph assume the column size is the same as the row size
%
% options.blocksize blocksize to write out extremely large matrices.
%
% David Gleich
% Copyright, 2005-2010
options = struct('format', '%f', 'ut', 'no', 'graph', 'no', ...
'onebased', 'no', 'blocksize', 1000000);
if (nargin > 2)
options = merge_structs(optionsu, options);
end;
fid = fopen(filename, 'wt');
if (strcmp(options.ut', 'yes'))
A = triu(A);
[i, j, v] = find(A);
else
[i, j, v] = find(A);
end
nz = length(i);
[m n] = size(A);
if m==1,
i = i';
j = j';
v = v';
end
if (strcmp(options.graph, 'yes'))
fprintf(fid, '%i %i\n', m, nz);
else
fprintf(fid, '%i %i %i\n', m, n, nz);
end;
fmt = sprintf('%s %s %s\\n', '%i', '%i', options.format);
if (~strcmp(options.onebased, 'yes'))
i = i-1;
j = j-1;
end;
try
fprintf(fid, fmt, [i j v]');
catch
fprintf('... trying block write ...\n');
blocksize = options.blocksize;
startblock = 1;
blocknum = 1;
nzleft = nz;
while (nzleft > 0)
curblock = min(nzleft, blocksize);
fprintf('block %i (%i - %i)\n', blocknum, startblock, startblock+curblock-1);
curpart = startblock:(startblock+curblock-1);
fprintf(fid, fmt, [i(curpart) j(curpart) v(curpart)]');
nzleft = nzleft - curblock;
startblock = startblock+curblock;
blocknum = blocknum+1;
end;
end;
%for ii=1:length(i)
% fprintf(fid, '%i %i %f\n', i(ii)-1, j(ii)-1, v(ii));
%end
fclose(fid);
function S = merge_structs(A, B)
% MERGE_STRUCTS Merge two structures.
%
% S = merge_structs(A, B) makes the structure S have all the fields from A
% and B. Conflicts are resolved by using the value in A.
%
%
% merge_structs.m
% David Gleich
%
% Revision 1.00
% 19 Octoboer 2005
%
S = A;
fn = fieldnames(B);
for ii = 1:length(fn)
if ~isfield(A, fn{ii})
S.(fn{ii}) = B.(fn{ii});
end
end
|
github | MengLiuPurdue/find_densest_subgraph-master | max_density.m | .m | find_densest_subgraph-master/6_node_test/max_density.m | 633 | utf_8 | edf1d2d157f71e56c6930b8c4fafeeb5 | %find the subgraph with the maximum density in an undirected graph through brutal search
%the undirected graph is represented by an adjcent matrix A
%density is the maximum density and cut is the corresponding subgraph
function [density,cut]=max_density(A)
density=0;
for i=0:63
temp=0;
a=bitget(i,6:-1:1);
for j=1:6
for k=1:6
if a(j)*a(k)*A(j,k)~=0
temp=temp+A(j,k);
end
end
end
count=sum(a);
temp=temp/count;
if temp>density
max_cut=a;
density=temp;
end
end
j=1;
for i=1:6
if max_cut(i)==1
cut(j,1)=i;
j=j+1;
end
end
|
github | mhturner/MHT-Rieke-analysis-master | singleEpochPlusImagingTraces.m | .m | MHT-Rieke-analysis-master/JauiModel&TreeTools/epoch-tree-gui/singleEpochPlusImagingTraces.m | 4,170 | utf_8 | 3cea9f4f1fac67a40972ad2511c061d6 | function singleEpochPlusImagingTraces(epochTree, fig, doInit)
%Show info about one Epoch at at time, under given EpochTree
% [email protected]
% 2 Feb. 2009
%MHT added imaging traces 20171025
import riekesuite.guitools.*;
if ~nargin && ~isobject(epochTree)
disp(sprintf('%s needs an EpochTree', mfilename));
return
end
if nargin < 2
disp(sprintf('%s needs a figure', mfilename));
return
end
if nargin < 3
doInit = false;
end
% init when told, or when this is not the 'current function' of the figure
figData = get(fig, 'UserData');
if doInit || ~isfield(figData, 'currentFunction') || ~strcmp(figData.currentFunction, mfilename)
% create new panel slider, info table
delete(get(fig, 'Children'));
figData.currentFunction = mfilename;
x = .02;
w = .96;
noData = {...
'number', []; ...
'date', []; ...
'isSelected', []; ...
'includeInAnalysis', []; ...
'tags', []};
figData.infoTable = uitable('Parent', fig', ...
'Units', 'normalized', ...
'Position', [x .8, w, .18], ...
'Data', noData, ...
'RowName', {}, ...
'ColumnName', [], ...
'ColumnEditable', false);
figData.panel = uipanel('Parent', fig, ...
'Units', 'normalized', ...
'Position', [x .05 w .75]);
figData.next = uicontrol('Parent', fig, ...
'Units', 'normalized', ...
'Position', [x 0 w .05], ...
'Style', 'slider', ...
'Callback', {@plotNextEpoch, figData});
set(fig, 'UserData', figData, 'ResizeFcn', {@canvasResizeFcn, figData});
canvasResizeFcn(figData.panel, [], figData);
end
% get all Epochs under the given tree
el = getTreeEpochs(epochTree);
n = el.length;
if n
set(figData.next, ...
'Enable', 'on', ...
'UserData', el, ...
'Min', 1, ...
'Max', n+eps, ...
'SliderStep', [1/n, 1/n], ...
'Value', 1);
plotNextEpoch(figData.next, [], figData);
else
delete(get(figData.panel, 'Children'));
set(figData.next, 'Enable', 'off');
end
function plotNextEpoch(slider, event, figData)
% slider control picks one Epoch
ind = round(get(slider, 'Value'));
el = get(slider, 'UserData');
ep = el.valueByIndex(ind);
% various Epoch info to table rows
infoData = get(figData.infoTable, 'Data');
infoData{1,2} = sprintf('%d of %d', ind, el.length);
infoData{2,2} = datestr(ep.startDate, 31);
infoData{3,2} = logical(ep.isSelected);
infoData{4,2} = logical(ep.includeInAnalysis);
tags = ep.keywords;
%if tags.isEmpty skip this for now
% infoData{5,2} = 'no tags';
%else
% infoData{5,2} = sprintf('%s, ',tags{:}); %how do I do this in jauimodel?
%end
set(figData.infoTable, 'Data', infoData);
set(figData.panel, 'Title', 'getting response data...');
drawnow;
% Epoch responses in subplots
temp = ep.responses.keySet;
temp.remove('Optometer');
resps = temp.toArray;
nResp = length(resps);
for ii = 1:nResp
sp = subplot(nResp+1, 1, ii, 'Parent', figData.panel);
cla(sp);
respData = riekesuite.getResponseVector(ep, resps(ii));
if ischar(respData)
% dont' break when lazyLoads disabled
ylabel(sp, respData);
else
line(1:length(respData), respData, 'Parent', sp);
ylabel(sp, resps(ii));
end
end
set(figData.panel, 'Title', 'responses:');
drawnow;
% add Imaging Traces:
sp = subplot(nResp+1, 1, nResp+1, 'Parent', figData.panel);
cla(sp);
try
ScanRes = getLineScanDataFromEpoch(ep);
catch
ScanRes = [];
end
if isempty(ScanRes)
text(0.3,0.5,'No Line Scan Data Found','Parent',sp)
else
colors = pmkmp(max(size(ScanRes.channelData,1),2));
for cc = 1:size(ScanRes.channelData,1) %for channels
line(ScanRes.frameTimes,ScanRes.channelData(cc,:,1),...
'Color',colors(cc,:),'Parent', sp);
end
end
function canvasResizeFcn(panel, event, figData)
% set infoTable column widths proportionally
oldUnits = get(figData.infoTable, 'Units');
set(figData.infoTable, 'Units', 'pixels');
tablePos = get(figData.infoTable, 'Position');
set(figData.infoTable, 'Units', oldUnits);
set(figData.infoTable, 'ColumnWidth', {.2*tablePos(3), .65*tablePos(3)});
|
github | mhturner/MHT-Rieke-analysis-master | singleEpoch.m | .m | MHT-Rieke-analysis-master/JauiModel&TreeTools/epoch-tree-gui/singleEpoch.m | 3,631 | utf_8 | 8cd875fdf9621f2baef1745d10d5c0db | function singleEpoch(epochTree, fig, doInit)
%Show info about one Epoch at at time, under given EpochTree
% [email protected]
% 2 Feb. 2009
import riekesuite.guitools.*;
if ~nargin && ~isobject(epochTree)
disp(sprintf('%s needs an EpochTree', mfilename));
return
end
if nargin < 2
disp(sprintf('%s needs a figure', mfilename));
return
end
if nargin < 3
doInit = false;
end
% init when told, or when this is not the 'current function' of the figure
figData = get(fig, 'UserData');
if doInit || ~isfield(figData, 'currentFunction') || ~strcmp(figData.currentFunction, mfilename)
% create new panel slider, info table
delete(get(fig, 'Children'));
figData.currentFunction = mfilename;
x = .02;
w = .96;
noData = {...
'number', []; ...
'date', []; ...
'isSelected', []; ...
'includeInAnalysis', []; ...
'tags', []};
figData.infoTable = uitable('Parent', fig', ...
'Units', 'normalized', ...
'Position', [x .8, w, .18], ...
'Data', noData, ...
'RowName', {}, ...
'ColumnName', [], ...
'ColumnEditable', false);
figData.panel = uipanel('Parent', fig, ...
'Units', 'normalized', ...
'Position', [x .05 w .75]);
figData.next = uicontrol('Parent', fig, ...
'Units', 'normalized', ...
'Position', [x 0 w .05], ...
'Style', 'slider', ...
'Callback', {@plotNextEpoch, figData});
set(fig, 'UserData', figData, 'ResizeFcn', {@canvasResizeFcn, figData});
canvasResizeFcn(figData.panel, [], figData);
end
% get all Epochs under the given tree
el = getTreeEpochs(epochTree);
n = el.length;
if n
set(figData.next, ...
'Enable', 'on', ...
'UserData', el, ...
'Min', 1, ...
'Max', n+eps, ...
'SliderStep', [1/n, 1/n], ...
'Value', 1);
plotNextEpoch(figData.next, [], figData);
else
delete(get(figData.panel, 'Children'));
set(figData.next, 'Enable', 'off');
end
function plotNextEpoch(slider, event, figData)
% slider control picks one Epoch
ind = round(get(slider, 'Value'));
el = get(slider, 'UserData');
ep = el.valueByIndex(ind);
% various Epoch info to table rows
infoData = get(figData.infoTable, 'Data');
infoData{1,2} = sprintf('%d of %d', ind, el.length);
infoData{2,2} = datestr(ep.startDate, 31);
infoData{3,2} = logical(ep.isSelected);
infoData{4,2} = logical(ep.includeInAnalysis);
tags = ep.keywords;
%if tags.isEmpty skip this for now
% infoData{5,2} = 'no tags';
%else
% infoData{5,2} = sprintf('%s, ',tags{:}); %how do I do this in jauimodel?
%end
set(figData.infoTable, 'Data', infoData);
set(figData.panel, 'Title', 'getting response data...');
drawnow;
% Epoch responses in subplots
temp = ep.responses.keySet;
temp.remove('Optometer');
resps = temp.toArray;
nResp = length(resps);
for ii = 1:nResp
sp = subplot(nResp, 1, ii, 'Parent', figData.panel);
cla(sp);
respData = riekesuite.getResponseVector(ep, resps(ii));
if ischar(respData)
% dont' break when lazyLoads disabled
ylabel(sp, respData);
else
line(1:length(respData), respData, 'Parent', sp);
ylabel(sp, resps(ii));
end
end
set(figData.panel, 'Title', 'responses:');
drawnow;
function canvasResizeFcn(panel, event, figData)
% set infoTable column widths proportionally
oldUnits = get(figData.infoTable, 'Units');
set(figData.infoTable, 'Units', 'pixels');
tablePos = get(figData.infoTable, 'Position');
set(figData.infoTable, 'Units', oldUnits);
set(figData.infoTable, 'ColumnWidth', {.2*tablePos(3), .65*tablePos(3)});
|
github | mhturner/MHT-Rieke-analysis-master | rotavg.m | .m | MHT-Rieke-analysis-master/Utilities/imageAnalysisTools/rotavg.m | 514 | utf_8 | d6c4c1e17260944b706084b0a20b6979 | % rotavg.m - function to compute rotational average of (square) array
% by Bruno Olshausen
%
% function f = rotavg(array)
%
% array can be of dimensions N x N x M, in which case f is of
% dimension NxM. N should be even.
%
function f = rotavg(array)
[N N M]=size(array);
[X Y]=meshgrid(-N/2:N/2-1,-N/2:N/2-1);
[theta rho]=cart2pol(X,Y);
rho=round(rho);
i=cell(N/2+1,1);
for r=0:N/2
i{r+1}=find(rho==r);
end
f=zeros(N/2+1,M);
for m=1:M
a=array(:,:,m);
for r=0:N/2
f(r+1,m)=mean(a(i{r+1}));
end
end |
github | mhturner/MHT-Rieke-analysis-master | SpikeDetector.m | .m | MHT-Rieke-analysis-master/Utilities/SpikeTrainTools/SpikeDetector.m | 7,059 | utf_8 | 3a0849383ba6e1021cb2407051fba5f2 | function [SpikeTimes, SpikeAmplitudes, RefractoryViolations] = SpikeDetector(DataMatrix,varargin)
%SpikeDetector detects spikes in an extracellular / cell attached recording
% [SpikeTimes, SpikeAmplitudes, RefractoryViolations] = SpikeDetector(dataMatrix,varargin)
% RETURNS
% SpikeTimes: In datapoints. Cell array. Or array if just one trial;
% SpikeAmplitudes: Cell array.
% RefractoryViolations: Indices of SpikeTimes that had refractory
% violations. Cell array.
% REQUIRED INPUTS
% DataMatrix: Each row is a trial
% OPTIONAL ARGUMENTS
% CheckDetection: (false) (logical) Plots clustering information for
% each trace
% SampleRate: (1e4) (Hz)
% RefractoryPeriod: (1.5e-3) (sec)
% SearchWindow; (1.2e-3) (sec) To look for rebounds. Search interval
% is (peak time +/- SearchWindow/2)
% RemoveRefractoryViolations: (true) (logical) removes refractory violations from
% spike times and spike amplitudes
% thresholdSpikeFactor: (10) (numeric, a.u.) how many noise st-devs
% above zero must spike amplitudes be? Uses mean cluster amplitude to
% detect "no spike" trials (doesn't filter out individual spikes this
% way). Be very careful of setting this too high.
%
% Clusters peak waveforms into 2 clusters using k-means. Based on three
% quantities about each spike waveform: amplitude of the peak, amlitude
% of a rebound on the right and left.
% MHT 9.23.2016 - Ported over from personal version
% MHT 1.25.2017 - Added option to remove refractory violation spike times
ip = inputParser;
ip.addRequired('DataMatrix',@ismatrix);
addParameter(ip,'CheckDetection',false,@islogical);
addParameter(ip,'SampleRate',1e4,@isnumeric);
addParameter(ip,'RefractoryPeriod',1.5E-3,@isnumeric);
addParameter(ip,'SearchWindow',1.2E-3,@isnumeric);
addParameter(ip,'RemoveRefractoryViolations',true,@islogical);
addParameter(ip,'thresholdSpikeFactor',10,@isnumeric);
ip.parse(DataMatrix,varargin{:});
DataMatrix = ip.Results.DataMatrix;
CheckDetection = ip.Results.CheckDetection;
SampleRate = ip.Results.SampleRate;
RefractoryPeriod = ip.Results.RefractoryPeriod * SampleRate; % datapoints
SearchWindow = ip.Results.SearchWindow * SampleRate; % datapoints
RemoveRefractoryViolations = ip.Results.RemoveRefractoryViolations;
thresholdSpikeFactor = ip.Results.thresholdSpikeFactor;
CutoffFrequency = 500; %Hz
DataMatrix = highPassFilter(DataMatrix,CutoffFrequency,1/SampleRate);
nTraces = size(DataMatrix,1);
SpikeTimes = cell(nTraces,1);
SpikeAmplitudes = cell(nTraces,1);
RefractoryViolations = cell(nTraces,1);
if (CheckDetection)
figHandle = figure(40);
end
for tt=1:nTraces
currentTrace = DataMatrix(tt,:);
if abs(max(currentTrace)) > abs(min(currentTrace)) % flip it over, big peaks down
currentTrace = -currentTrace;
end
% get peaks
[peakAmplitudes, peakTimes] = getPeaks(currentTrace,-1); % -1 for negative peaks
peakTimes = peakTimes(peakAmplitudes<0); % only negative deflections
peakAmplitudes = abs(peakAmplitudes(peakAmplitudes<0)); % only negative deflections
% get rebounds on either side of each peak
rebound = getRebounds(peakTimes,currentTrace,SearchWindow);
% cluster spikes
clusteringData = [peakAmplitudes', rebound.Left', rebound.Right'];
startMatrix = [median(peakAmplitudes) median(rebound.Left) median(rebound.Right);...
max(peakAmplitudes) max(rebound.Left) max(rebound.Right)];
clusteringOptions = statset('MaxIter',10000);
try %traces with no spikes sometimes throw an "empty cluster" error in kmeans
[clusterIndex, centroidAmplitudes] = kmeans(clusteringData, 2,...
'start',startMatrix,'Options',clusteringOptions);
catch err
if strcmp(err.identifier,'stats:kmeans:EmptyCluster')
%initialize clusters using random sampling instead
[clusterIndex, centroidAmplitudes] = kmeans(clusteringData,2,'start','sample','Options',clusteringOptions);
end
end
[~,spikeClusterIndex] = max(centroidAmplitudes(:,1)); %find cluster with largest peak amplitude
nonspikeClusterIndex = setdiff([1 2],spikeClusterIndex); %nonspike cluster index
spikeIndex_logical = (clusterIndex == spikeClusterIndex); %spike_ind_log is logical, length of peaks
% get spike times and amplitudes
SpikeTimes{tt} = peakTimes(spikeIndex_logical);
SpikeAmplitudes{tt} = peakAmplitudes(spikeIndex_logical);
nonspikeAmplitudes = peakAmplitudes(~spikeIndex_logical);
%check for no spikes trace
%how many st-devs greater is spike peak than noise peak?
sigF = (mean(SpikeAmplitudes{tt}) - mean(nonspikeAmplitudes)) / std(nonspikeAmplitudes);
if sigF < thresholdSpikeFactor; %no spikes
SpikeTimes{tt} = [];
SpikeAmplitudes{tt} = [];
RefractoryViolations{tt} = [];
disp(['Trial ' num2str(tt) ': no spikes. SF = ',num2str(sigF)]);
% figHandle = figure(40);
% plotClusteringData();
if (CheckDetection)
plotClusteringData();
end
continue
end
% check for refractory violations
RefractoryViolations{tt} = find(diff(SpikeTimes{tt}) < RefractoryPeriod) + 1;
ref_violations = length(RefractoryViolations{tt});
if ref_violations > 0
% % figHandle = figure(40);
% % plotClusteringData()
if (RemoveRefractoryViolations)
disp(['Trial ' num2str(tt) ': ' num2str(ref_violations) ' refractory violations removed']);
else
disp(['Trial ' num2str(tt) ': ' num2str(ref_violations) ' refractory violations remain']);
end
end
if (CheckDetection)
plotClusteringData()
end
end
if (RemoveRefractoryViolations)
for tt = 1:length(SpikeTimes)
SpikeTimes{tt}(RefractoryViolations{tt}) = [];
SpikeAmplitudes{tt}(RefractoryViolations{tt}) = [];
end
end
if length(SpikeTimes) == 1 %return vector not cell array if only 1 trial
SpikeTimes = SpikeTimes{1};
SpikeAmplitudes = SpikeAmplitudes{1};
RefractoryViolations = RefractoryViolations{1};
end
function plotClusteringData()
figure(figHandle)
subplot(1,2,1); hold on;
plot3(peakAmplitudes(clusterIndex==spikeClusterIndex),...
rebound.Left(clusterIndex==spikeClusterIndex),...
rebound.Right(clusterIndex==spikeClusterIndex),'ro')
plot3(peakAmplitudes(clusterIndex==nonspikeClusterIndex),...
rebound.Left(clusterIndex==nonspikeClusterIndex),...
rebound.Right(clusterIndex==nonspikeClusterIndex),'ko')
xlabel('Peak Amplitude'); ylabel('L rebound'); zlabel('R rebound')
view([8 36])
subplot(1,2,2)
plot(currentTrace,'k'); hold on;
plot(SpikeTimes{tt}, ...
currentTrace(SpikeTimes{tt}),'rx')
plot(SpikeTimes{tt}(RefractoryViolations{tt}), ...
currentTrace(SpikeTimes{tt}(RefractoryViolations{tt})),'go')
title(['SpikeFactor = ', num2str(sigF)])
drawnow;
pause(); clf;
end
end
|
github | mhturner/MHT-Rieke-analysis-master | fitCRF_cumGauss.m | .m | MHT-Rieke-analysis-master/Utilities/Curves&Stuff/fitCRF_cumGauss.m | 1,244 | utf_8 | e4e4e2699a7107896e9fc06386856689 | function res = fitCRF_cumGauss(contrast,response,params0)
% res = fitCRF_cumGauss(contrast,response,params0)
% Fitting wrapper for CRFcumGauss
LB = [0, -Inf, -Inf, -Inf]; UB = [Inf Inf Inf Inf];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',1000*length(LB),'Display','off');
[params, ~, ~]=lsqnonlin(@CRF_err,params0,LB,UB,fitOptions,contrast,response);
alphaScale = params(1);
betaSens = params(2);
gammaXoff = params(3);
epsilonYoff = params(4);
predResp = CRFcumGauss(contrast,alphaScale,betaSens,gammaXoff,epsilonYoff);
ssErr=sum((response-predResp).^2); %sum of squares of residual
ssTot=sum((response-mean(response)).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alphaScale=params(1);
res.betaSens=params(2);
res.gammaXoff=params(3);
res.epsilonYoff = params(4);
res.rSquared=rSquared;
end
function err = CRF_err(params,contrast,response)
%error fxn for fitting CRF fxn with contrast spots...
alphaScale = params(1);
betaSens = params(2);
gammaXoff = params(3);
epsilonYoff = params(4);
fit = CRFcumGauss(contrast,alphaScale,betaSens,gammaXoff,epsilonYoff);
err = (fit - response);
end |
github | mhturner/MHT-Rieke-analysis-master | fitSpikeInputOutput.m | .m | MHT-Rieke-analysis-master/Utilities/Curves&Stuff/fitSpikeInputOutput.m | 1,080 | utf_8 | afeab1d724cfd7bf3e8aaa32461ac18c | function res = fitSpikeInputOutput(inputs,response,params0)
% res = fitSpikeInputOutput(inputs,response,params0)
% Fitting wrapper for SpikeOutput_cumGauss
LB = [0, -Inf, -Inf]; UB = [Inf Inf Inf];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB));
[params, ~, ~]=lsqnonlin(@errFun,params0,LB,UB,fitOptions,inputs,response);
alphaScale = params(1);
betaSens = params(2);
gammaXoff = params(3);
predResp = SpikeOutput_cumGauss(inputs,alphaScale,betaSens,gammaXoff);
ssErr=sum((response-predResp).^2); %sum of squares of residual
ssTot=sum((response-mean(response)).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alphaScale=params(1);
res.betaSens=params(2);
res.gammaXoff=params(3);
res.rSquared=rSquared;
end
function err = errFun(params,inputs,response)
%error fxn
alphaScale = params(1);
betaSens = params(2);
gammaXoff = params(3);
fit = SpikeOutput_cumGauss(inputs,alphaScale,betaSens,gammaXoff);
err = (fit - response);
end |
github | mhturner/MHT-Rieke-analysis-master | fitCRF_sigmoid.m | .m | MHT-Rieke-analysis-master/Utilities/Curves&Stuff/fitCRF_sigmoid.m | 1,096 | utf_8 | 563daf5d03284142d39a95ef38be209c | function res = fitCRF_sigmoid(contrast,response,params0)
% res = fitCRF_sigmoid(contrast,response,params0)
% Fitting wrapper for sigmoidCRF
LB = [0, -Inf 0 -Inf]; UB = [Inf Inf Inf Inf];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[params, ~, ~]=lsqnonlin(@CRF_err,params0,LB,UB,fitOptions,contrast,response);
k = params(1);
c0 = params(2);
amp = params(3);
yOff = params(4);
predResp = sigmoidCRF(contrast,k,c0,amp,yOff);
ssErr=sum((response-predResp).^2); %sum of squares of residual
ssTot=sum((response-mean(response)).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.k=params(1);
res.c0=params(2);
res.amp=params(3);
res.yOff=params(4);
res.rSquared=rSquared;
end
function err = CRF_err(params,contrast,response)
%error fxn for fitting CRF fxn with contrast spots...
k = params(1);
c0 = params(2);
amp = params(3);
yOff = params(4);
fit = sigmoidCRF(contrast,k,c0,amp,yOff);
err = (fit - response);
end |
github | mhturner/MHT-Rieke-analysis-master | freezeColors.m | .m | MHT-Rieke-analysis-master/Utilities/PlotTools/freezeColors.m | 9,753 | utf_8 | 611c1ec5ba6c9a145252ce43179845dd | function freezeColors(varargin)
% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3)
%
% Problem: There is only one colormap per figure. This function provides
% an easy solution when plots using different colomaps are desired
% in the same figure.
%
% freezeColors freezes the colors of graphics objects in the current axis so
% that subsequent changes to the colormap (or caxis) will not change the
% colors of these objects. freezeColors works on any graphics object
% with CData in indexed-color mode: surfaces, images, scattergroups,
% bargroups, patches, etc. It works by converting CData to true-color rgb
% based on the colormap active at the time freezeColors is called.
%
% The original indexed color data is saved, and can be restored using
% unfreezeColors, making the plot once again subject to the colormap and
% caxis.
%
%
% Usage:
% freezeColors applies to all objects in current axis (gca),
% freezeColors(axh) same, but works on axis axh.
%
% Example:
% subplot(2,1,1); imagesc(X); colormap hot; freezeColors
% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
%
% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can
% no longer be done with freezeColors. Instead, please
% use the function CBFREEZE by Carlos Adrian Vargas Aguilera
% that can be downloaded from the MATLAB File Exchange
% (http://www.mathworks.com/matlabcentral/fileexchange/24371)
%
% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
%
% For additional examples, see test/test_main.m
%
% Side effect on render mode: freezeColors does not work with the painters
% renderer, because Matlab doesn't support rgb color data in
% painters mode. If the current renderer is painters, freezeColors
% changes it to zbuffer. This may have unexpected effects on other aspects
% of your plots.
%
% See also unfreezeColors, freezeColors_pub.html, cbfreeze.
%
%
% John Iversen ([email protected]) 3/23/05
%
% Changes:
% JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata
% JRI 9/1/06 should now handle all objects with cdata: images, surfaces,
% scatterplots. (v 2.1)
% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded)
% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3)
% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf)
% JRI 4/7/10 Change documentation for colorbars
% Hidden option for NaN colors:
% Missing data are often represented by NaN in the indexed color
% data, which renders transparently. This transparency will be preserved
% when freezing colors. If instead you wish such gaps to be filled with
% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g.
% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]),
% where [r g b] is a color vector. This works on images & pcolor, but not on
% surfaces.
% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes
% attributed in the code.
% Free for all uses, but please retain the following:
% Original Author:
% John Iversen, 2005-10
% [email protected]
appdatacode = 'JRI__freezeColorsData';
[h, nancolor] = checkArgs(varargin);
%gather all children with scaled or indexed CData
cdatah = getCDataHandles(h);
%current colormap
cmap = colormap;
nColors = size(cmap,1);
cax = caxis;
% convert object color indexes into colormap to true-color data using
% current colormap
for hh = cdatah',
g = get(hh);
%preserve parent axis clim
parentAx = getParentAxes(hh);
originalClim = get(parentAx, 'clim');
% Note: Special handling of patches: For some reason, setting
% cdata on patches created by bar() yields an error,
% so instead we'll set facevertexcdata instead for patches.
if ~strcmp(g.Type,'patch'),
cdata = g.CData;
else
cdata = g.FaceVertexCData;
end
%get cdata mapping (most objects (except scattergroup) have it)
if isfield(g,'CDataMapping'),
scalemode = g.CDataMapping;
else
scalemode = 'scaled';
end
%save original indexed data for use with unfreezeColors
siz = size(cdata);
setappdata(hh, appdatacode, {cdata scalemode});
%convert cdata to indexes into colormap
if strcmp(scalemode,'scaled'),
%4/19/06 JRI, Accommodate scaled display of integer cdata:
% in MATLAB, uint * double = uint, so must coerce cdata to double
% Thanks to O Yamashita for pointing this need out
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);
else %direct mapping
idx = cdata;
%10/8/09 in case direct data is non-int (e.g. image;freezeColors)
% (Floor mimics how matlab converts data into colormap index.)
% Thanks to D Armyr for the catch
idx = floor(idx);
end
%clamp to [1, nColors]
idx(idx<1) = 1;
idx(idx>nColors) = nColors;
%handle nans in idx
nanmask = isnan(idx);
idx(nanmask)=1; %temporarily replace w/ a valid colormap index
%make true-color data--using current colormap
realcolor = zeros(siz);
for i = 1:3,
c = cmap(idx,i);
c = reshape(c,siz);
c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified)
realcolor(:,:,i) = c;
end
%apply new true-color color data
%true-color is not supported in painters renderer, so switch out of that
if strcmp(get(gcf,'renderer'), 'painters'),
set(gcf,'renderer','zbuffer');
end
%replace original CData with true-color data
if ~strcmp(g.Type,'patch'),
set(hh,'CData',realcolor);
else
set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
end
%restore clim (so colorbar will show correct limits)
if ~isempty(parentAx),
set(parentAx,'clim',originalClim)
end
end %loop on indexed-color objects
% ============================================================================ %
% Local functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getCDataHandles -- get handles of all descendents with indexed CData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hout = getCDataHandles(h)
% getCDataHandles Find all objects with indexed CData
%recursively descend object tree, finding objects with indexed CData
% An exception: don't include children of objects that themselves have CData:
% for example, scattergroups are non-standard hggroups, with CData. Changing
% such a group's CData automatically changes the CData of its children,
% (as well as the children's handles), so there's no need to act on them.
narginchk(1,1)
hout = [];
if isempty(h),return;end
ch = get(h,'children');
for hh = ch'
g = get(hh);
if isfield(g,'CData'), %does object have CData?
%is it indexed/scaled?
if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,
hout = [hout; hh]; %#ok<AGROW> %yes, add to list
end
else %no CData, see if object has any interesting children
hout = [hout; getCDataHandles(hh)]; %#ok<AGROW>
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getParentAxes -- return handle of axes object to which a given object belongs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hAx = getParentAxes(h)
% getParentAxes Return enclosing axes of a given object (could be self)
narginchk(1,1)
%object itself may be an axis
if strcmp(get(h,'type'),'axes'),
hAx = h;
return
end
parent = get(h,'parent');
if (strcmp(get(parent,'type'), 'axes')),
hAx = parent;
else
hAx = getParentAxes(parent);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% checkArgs -- Validate input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, nancolor] = checkArgs(args)
% checkArgs Validate input arguments to freezeColors
nargs = length(args);
narginchk(0,3)
%grab handle from first argument if we have an odd number of arguments
if mod(nargs,2),
h = args{1};
if ~ishandle(h),
error('JRI:freezeColors:checkArgs:invalidHandle',...
'The first argument must be a valid graphics handle (to an axis)')
end
% 4/2010 check if object to be frozen is a colorbar
if strcmp(get(h,'Tag'),'Colorbar'),
if ~exist('cbfreeze.m'),
warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
['You seem to be attempting to freeze a colorbar. This no longer'...
'works. Please read the help for freezeColors for the solution.'])
else
cbfreeze(h);
return
end
end
args{1} = [];
nargs = nargs-1;
else
h = gca;
end
%set nancolor if that option was specified
nancolor = [nan nan nan];
if nargs == 2,
if strcmpi(args{end-1},'nancolor'),
nancolor = args{end};
if ~all(size(nancolor)==[1 3]),
error('JRI:freezeColors:checkArgs:badColorArgument',...
'nancolor must be [r g b] vector');
end
nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0;
else
error('JRI:freezeColors:checkArgs:unrecognizedOption',...
'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1})
end
end
|
github | mhturner/MHT-Rieke-analysis-master | getCellInfoFromEpochList.m | .m | MHT-Rieke-analysis-master/EpochListAnalysisFunctions/getCellInfoFromEpochList.m | 1,808 | utf_8 | cf9215f0e983f57a668c54fa0eeaec5d | function cellInfo = getCellInfoFromEpochList(epochList)
% res = getCellInfoFromEpochList(epochList)
% MHT 5/17/16
ip = inputParser;
ip.addRequired('epochList',@(x)isa(x,'edu.washington.rieke.symphony.generic.GenericEpochList'));
ip.parse(epochList);
epochList = ip.Results.epochList;
firstCellID = char(epochList.elements(1).cell.label);
for epochIndex = 1:epochList.length
thisCellID = char(epochList.elements(epochIndex).cell.label);
if ~strcmp(firstCellID,thisCellID)
error('Mulitple cells included in this epochList')
end
end
cellID = char(epochList.firstValue.cell.label);
if epochList.firstValue.protocolSettings.keySet.contains('source:type')
cellType = epochList.firstValue.protocolSettings('source:type');
si = strfind(cellType,'\');
if isempty(si)
else %sub-class (e.g. "RGC\ ON-parasol")
cellType = cellType(si+1:end);
si = strfind(cellType,'-');
cellType(si) = [];
end
if or(strcmp(cellType,'unknown'), isempty(cellType))
keywords = char(epochList.keywords);
cellType = checkAgainstKeywords(keywords);
end
else
cellKeywords = char(epochList.keywords);
cellType = checkAgainstKeywords(cellKeywords);
end
cellInfo.cellID = cellID;
cellInfo.cellType = cellType;
function res = checkAgainstKeywords(keywords)
if ~isempty(strfind(keywords,'ONparasol'))
res = char('ONparasol');
elseif ~isempty(strfind(keywords,'OFFparasol'))
res = char('OFFparasol');
elseif ~isempty(strfind(keywords,'ONmidget'))
res = char('ONmidget');
elseif ~isempty(strfind(keywords,'OFFmidget'))
res = char('OFFmidget');
elseif ~isempty(strfind(keywords,'horizontal'))
res = char('horizontal');
else
res = 'noCellTypeTag';
end
end
end |
github | mhturner/MHT-Rieke-analysis-master | fitNormcdfNonlinearity.m | .m | MHT-Rieke-analysis-master/Modeling/CSmodels/fitNormcdfNonlinearity.m | 972 | utf_8 | d0891f99f64656159e191abc8c560459 | function res = fitNormcdfNonlinearity(x,response,params0)
%res is params for fxn normcdfNonlinearity
%params is [alpha, beta, gamma, epsilon]
% % params0=[max(resp), mean(diff(resp)), 0, 0]';
LB = [-Inf -Inf -Inf -Inf]; UB = [Inf Inf Inf max(response(:))];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[params, ~, residual]=lsqnonlin(@modelErrorFxn,params0,LB,UB,fitOptions,x,response);
ssErr=sum(residual.^2); %sum of squares of residual
ssTot=sum((response(:)-mean(response(:))).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alpha=params(1);
res.beta=params(2);
res.gamma=params(3);
res.epsilon=params(4);
res.rSquared=rSquared;
end
function err = modelErrorFxn(params,x,response)
%error fxn for fitting summed NLinearity function
alpha = params(1);
beta = params(2);
gamma = params(3);
epsilon = params(4);
fit = normcdfNonlinearity(x,alpha,beta,gamma,epsilon);
err = fit - response;
end |
github | mhturner/MHT-Rieke-analysis-master | fitCSModel_SharedNL.m | .m | MHT-Rieke-analysis-master/Modeling/CSmodels/fitCSModel_SharedNL.m | 1,342 | utf_8 | 9e876de9c0cee9c52c7e70d87c160858 | function res = fitCSModel_SharedNL(x,y,z_data,params0)
%fits summed nonlinearity, r = f(aX + Y)
%res is params for fxn summedNLin
%params is [a, alpha, beta, gamma, epsilon]
% % params0=[2, max(z_data), mean(diff(z_data))/mean(diff(x+y)), 0, 0]';
LB = [0 -Inf -Inf -Inf -Inf]; UB = [Inf Inf Inf Inf max(z_data(:))];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[params, ~, residual]=lsqnonlin(@modelErrorFxn,params0,LB,UB,fitOptions,x,y,z_data);
ssErr=sum(residual.^2); %sum of squares of residual
ssTot=nansum((z_data(:)-nanmean(z_data(:))).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.a=params(1);
res.alpha=params(2);
res.beta=params(3);
res.gamma=params(4);
res.epsilon=params(5);
res.rSquared=rSquared;
end
function err = modelErrorFxn(params,x,y,response)
%error fxn for fitting summed NLinearity function
a = params(1);
alpha = params(2);
beta = params(3);
gamma = params(4);
epsilon = params(5);
%reshape x,y and response to arrays
[X1,X2] = meshgrid(x',y');
response=reshape(response,[1, size(response,1)*size(response,2)]);
% take out any NaNs in z data, don't fit with those points
fitInds = find(~isnan(response));
response = response(fitInds);
fit = CSModel_SharedNL(X1(fitInds),X2(fitInds),a,alpha,beta,gamma,epsilon);
err = fit - response;
end |
github | mhturner/MHT-Rieke-analysis-master | fitNLinearity_2D.m | .m | MHT-Rieke-analysis-master/Modeling/CSmodels/fitNLinearity_2D.m | 1,628 | utf_8 | 52a9f02cbd7631ed449309d0728696e9 | function res = fitNLinearity_2D(x,y,z_data,beta0)
%fits 2D nonlinearity with smooth surface which is a modified bivariate
%cumulative normal distribution
% alpha*C(mu,sigma)+epsilon
% where C is mvncdf() fxn
%x and y define axes 1 and 2 (bins centers, basically)
%z_data is an x by y matrix of response values
%beta is [alpha mu1 mu2 std1 std2 corr12 epsilon]
LB = [max(z_data(:)) min(x) min(y) 0 0 -1 -Inf]; UB = [Inf max(x) max(y) Inf Inf 1 0];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[beta, ~, residual]=lsqnonlin(@BivarCumNorm_err,beta0,LB,UB,fitOptions,x,y,z_data);
ssErr=sum(residual.^2); %sum of squares of residual
ssTot=nansum((z_data(:)-nanmean(z_data(:))).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alpha=beta(1);
res.mu=[beta(2) beta(3)];
res.sigma=[beta(4)^2 beta(6)*beta(4)*beta(5);beta(6)*beta(4)*beta(5) beta(5)^2];
res.epsilon=beta(7);
res.rSquared=rSquared;
end
function err = BivarCumNorm_err(beta,x,y,response)
%error fxn for fitting Bivariate Cumulative Normal surface to 2D
%nonlinearity
alpha=beta(1);
mu=[beta(2) beta(3)];
sigma1=beta(4); sigma2=beta(5); corr12=beta(6);
epsilon=beta(7);
sigma=[sigma1^2 corr12*sigma1*sigma2;corr12*sigma1*sigma2 sigma2^2];
%reshape x,y and response to arrays
[X1,X2] = meshgrid(x',y');
response=reshape(response,[size(response,1)*size(response,2),1]);
% take out any NaNs in z data, don't fit with those points
fitInds = find(~isnan(response));
response = response(fitInds);
fit = JointNLin_mvcn(X1(fitInds)',X2(fitInds)',alpha,mu,sigma,epsilon);
err = fit - response;
end |
github | mhturner/MHT-Rieke-analysis-master | fitCSModel_ThreeNL.m | .m | MHT-Rieke-analysis-master/Modeling/CSmodels/fitCSModel_ThreeNL.m | 2,086 | utf_8 | 9c411b5c3487657c8d79a661de2f4f6f | function res = fitCSModel_ThreeNL(C,S,response,params0)
%Takes in binned generator signals for Center and Surround, along with
%corresponding response - same input as fitting joint model
%fits thee-NL center-surround model: R = nShared[nC(hC*C) + nS(hS*S)]
%where nC, nS, and nShared are modified cumulative gaussian NLinearities
%res is params for fxn CSModel_ThreeNL
%params is [alphaC, betaC, gammaC,...
% alphaS, betaS, gammaS,...
% alphaShared, betaShared, gammaShared,...
% epsilon]
% params0=[max(z_data), mean(diff(z_data))/mean(diff(C)), 0, max(z_data),
% mean(diff(z_data))/mean(diff(S)), 0, 0]';
LB = [-1 -Inf -1 -1 -Inf -1 -Inf -Inf -Inf -Inf];
UB = [1 Inf 1 1 Inf 1 Inf Inf Inf Inf];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[params, ~, residual]=lsqnonlin(@modelErrorFxn,params0,LB,UB,fitOptions,C,S,response);
ssErr=sum(residual.^2); %sum of squares of residual
ssTot=nansum((response(:)-nanmean(response(:))).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alphaC=params(1);
res.betaC=params(2);
res.gammaC=params(3);
res.alphaS=params(4);
res.betaS=params(5);
res.gammaS=params(6);
res.alphaShared=params(7);
res.betaShared=params(8);
res.gammaShared=params(9);
res.epsilon=params(10);
res.rSquared=rSquared;
end
function err = modelErrorFxn(params,x,y,response)
%error fxn for fitting summed NLinearity function
alphaC = params(1);
betaC = params(2);
gammaC = params(3);
alphaS = params(4);
betaS = params(5);
gammaS = params(6);
alphaShared = params(7);
betaShared = params(8);
gammaShared = params(9);
epsilon = params(10);
%reshape x,y and response to arrays
[X1,X2] = meshgrid(x',y');
response=reshape(response,[1, size(response,1)*size(response,2)]);
% take out any NaNs in z data, don't fit with those points
fitInds = find(~isnan(response));
response = response(fitInds);
fit = CSModel_ThreeNL(X1(fitInds),X2(fitInds),...
alphaC,betaC,gammaC,alphaS,betaS,gammaS,alphaShared,betaShared,gammaShared,epsilon);
err = fit - response;
end
|
github | mhturner/MHT-Rieke-analysis-master | fitCSModel_IndependentNL.m | .m | MHT-Rieke-analysis-master/Modeling/CSmodels/fitCSModel_IndependentNL.m | 1,794 | utf_8 | f423a43fd62fca9366df40b55b3cb726 | function res = fitCSModel_IndependentNL(C,S,response,params0)
%Takes in binned generator signals for Center and Surround, along with
%corresponding response - same input as fitting joint model
%fits independent center-surround model: R = nC(hC*C) + nS(hS*S)
%where nC and nS are modified cumulative gaussian NLinearities
%res is params for fxn indCSmodel
%params is [alphaC, betaC, gammaC,...
% alphaS, betaS, gammaS, epsilon]
% params0=[max(z_data), mean(diff(z_data))/mean(diff(C)), 0, max(z_data),
% mean(diff(z_data))/mean(diff(S)), 0, 0]';
LB = [-Inf -Inf -Inf -Inf -Inf -Inf -Inf];
UB = [Inf Inf Inf Inf Inf Inf Inf];
fitOptions = optimset('MaxIter',1500,'MaxFunEvals',600*length(LB),'Display','off');
[params, ~, residual]=lsqnonlin(@modelErrorFxn,params0,LB,UB,fitOptions,C,S,response);
ssErr=sum(residual.^2); %sum of squares of residual
ssTot=nansum((response(:)-nanmean(response(:))).^2); %total sum of squares
rSquared=1-ssErr/ssTot; %coefficient of determination
res.alphaC=params(1);
res.betaC=params(2);
res.gammaC=params(3);
res.alphaS=params(4);
res.betaS=params(5);
res.gammaS=params(6);
res.epsilon=params(7);
res.rSquared=rSquared;
end
function err = modelErrorFxn(params,x,y,response)
%error fxn for fitting summed NLinearity function
alphaC = params(1);
betaC = params(2);
gammaC = params(3);
alphaS = params(4);
betaS = params(5);
gammaS = params(6);
epsilon = params(7);
%reshape x,y and response to arrays
[X1,X2] = meshgrid(x',y');
response=reshape(response,[1, size(response,1)*size(response,2)]);
% take out any NaNs in z data, don't fit with those points
fitInds = find(~isnan(response));
response = response(fitInds);
fit = CSModel_IndependentNL(X1(fitInds),X2(fitInds),alphaC,betaC,gammaC,alphaS,betaS,gammaS,epsilon);
err = fit - response;
end
|
github | rohitrango/CS251-master | backward_solve_3.m | .m | CS251-master/lab4/inlab/cs251_group37/lab01_group37_final/backward_solve_3.m | 562 | utf_8 | d115b4d0d808cf01e9b6bbd899102689 | %Function for backward solving 3*3 matrix
function y = backward_solve_3(x)
b = x'(:); % Convert input matrix to a vector
load Apush; % Load the matrix which shows the lights toggled on pressing a specific button.
AdjA = round(det(A)*inv(A)); % Calculating the adjoint of the above matrix
z = mod(-AdjA*b,2); % Solving the equation (b + Ax) % 2 = 0 for x using modular arithmetics
% x = (-AdjA*b) % 2
y = reshape(z,3,3)'; % Coverting vector to a 3*3 matrix showing the buttons to be pressed for lights out
endfunction
|
github | rohitrango/CS251-master | backward_solve.m | .m | CS251-master/lab4/inlab/cs251_group37/lab01_group37_final/backward_solve.m | 1,988 | utf_8 | 9983b121aff2924a4fa35ad0460d39cd | % function res = backward_solve(x)
% b = x(:);
% m = size(x,1);
% n = size(x,2);
% A = zeros(m*n);
% % generating the matrix A, when boxes are numbered vertically
% %%% NOTE: we have a faster version to calculate A, using no for loop. Written explanation is difficult.
% %%% But we can explain verbally. It is attached as a comment below.
% for ai = 1:m*n
% if(ai>1 && mod(ai,m)!=1) %checks if it is not boundary cases
% A(ai,ai-1) = 1; %i toggles i-1
% endif
% if(ai<m*n && mod(ai,m)!=0) %checks if it is not boundary cases
% A(ai,ai+1) = 1; %i toggles i+1
% endif
% if(ai>m) %checks if it is not boundary cases
% A(ai,ai-m) = 1; %i toggles i-m
% endif
% if(ai<=m*n-m) %checks if it is not boundary cases
% A(ai,ai+m) = 1; %i toggles i+m
% endif
% endfor
% A = A + eye(m*n); %i toggles i
% adjA = round(det(A)*inv(A)); % compute adjoint A
% res = mod(adjA*b,2); % solve the equation
% res = reshape(res,m,n); % reshape to appropriate size
% endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% FASTER VERSION:-
function res = backward_solve(x)
b = x(:);
m = size(x,1);
n = size(x,2);
A = zeros(m*n);
% generating the matrix A
A = findFactor(size(x'));
% A(i,i) = 1 for all i
adjA = round(det(A)*inv(A)); % compute adjoint A
res = mod(adjA*b,2); % solve the equation
res = reshape(res,m,n); % reshape to appropriate size
endfunction
%% file findFactor.m :-
% function res = findFactor(size)
% m = size(1);
% n = size(2);
% ID = eye(m*n);
% res = ID;
% ID(n:n:m*n,n:n:m*n) = 0;
% res(m*n+1 : (m*n)^2) += ID(1 : m*n*(m*n-1));
% ID(n:n:m*n,n:n:m*n) = eye(m);
% ID(n+1:n:m*n,n+1:n:m*n)=0;
% res(1 : m*n*(m*n-1)) += ID(m*n+1 : (m*n)^2);
% ID(n+1:n:m*n,n+1:n:m*n)= eye(m-1);
% res(m*n^2+1 : (m*n)^2) += ID(1 : m*n^2*(m-1));
% res(1 : m*n^2*(m-1)) += ID(m*n^2+1 : (m*n)^2);
% endfunction;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github | rohitrango/CS251-master | backward_solve_3.m | .m | CS251-master/lab1/Outlab Final Submission/backward_solve_3.m | 562 | utf_8 | d115b4d0d808cf01e9b6bbd899102689 | %Function for backward solving 3*3 matrix
function y = backward_solve_3(x)
b = x'(:); % Convert input matrix to a vector
load Apush; % Load the matrix which shows the lights toggled on pressing a specific button.
AdjA = round(det(A)*inv(A)); % Calculating the adjoint of the above matrix
z = mod(-AdjA*b,2); % Solving the equation (b + Ax) % 2 = 0 for x using modular arithmetics
% x = (-AdjA*b) % 2
y = reshape(z,3,3)'; % Coverting vector to a 3*3 matrix showing the buttons to be pressed for lights out
endfunction
|
github | rohitrango/CS251-master | backward_solve.m | .m | CS251-master/lab1/Outlab Final Submission/backward_solve.m | 1,988 | utf_8 | 9983b121aff2924a4fa35ad0460d39cd | % function res = backward_solve(x)
% b = x(:);
% m = size(x,1);
% n = size(x,2);
% A = zeros(m*n);
% % generating the matrix A, when boxes are numbered vertically
% %%% NOTE: we have a faster version to calculate A, using no for loop. Written explanation is difficult.
% %%% But we can explain verbally. It is attached as a comment below.
% for ai = 1:m*n
% if(ai>1 && mod(ai,m)!=1) %checks if it is not boundary cases
% A(ai,ai-1) = 1; %i toggles i-1
% endif
% if(ai<m*n && mod(ai,m)!=0) %checks if it is not boundary cases
% A(ai,ai+1) = 1; %i toggles i+1
% endif
% if(ai>m) %checks if it is not boundary cases
% A(ai,ai-m) = 1; %i toggles i-m
% endif
% if(ai<=m*n-m) %checks if it is not boundary cases
% A(ai,ai+m) = 1; %i toggles i+m
% endif
% endfor
% A = A + eye(m*n); %i toggles i
% adjA = round(det(A)*inv(A)); % compute adjoint A
% res = mod(adjA*b,2); % solve the equation
% res = reshape(res,m,n); % reshape to appropriate size
% endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% FASTER VERSION:-
function res = backward_solve(x)
b = x(:);
m = size(x,1);
n = size(x,2);
A = zeros(m*n);
% generating the matrix A
A = findFactor(size(x'));
% A(i,i) = 1 for all i
adjA = round(det(A)*inv(A)); % compute adjoint A
res = mod(adjA*b,2); % solve the equation
res = reshape(res,m,n); % reshape to appropriate size
endfunction
%% file findFactor.m :-
% function res = findFactor(size)
% m = size(1);
% n = size(2);
% ID = eye(m*n);
% res = ID;
% ID(n:n:m*n,n:n:m*n) = 0;
% res(m*n+1 : (m*n)^2) += ID(1 : m*n*(m*n-1));
% ID(n:n:m*n,n:n:m*n) = eye(m);
% ID(n+1:n:m*n,n+1:n:m*n)=0;
% res(1 : m*n*(m*n-1)) += ID(m*n+1 : (m*n)^2);
% ID(n+1:n:m*n,n+1:n:m*n)= eye(m-1);
% res(m*n^2+1 : (m*n)^2) += ID(1 : m*n^2*(m-1));
% res(1 : m*n^2*(m-1)) += ID(m*n^2+1 : (m*n)^2);
% endfunction;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.