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
aamiranis/sampling_theory-master
sgwt_demo1.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/demo/sgwt_demo1.m
4,442
utf_8
4884997e211ca4ec15e9fbd0e822a790
% sgwt_demo1 : SGWT for swiss roll data set % % This demo builds the SGWT for the swiss roll synthetic data set. It % computes a set of scales adapted to the computed upper bound on the % spectrum of the graph Laplacian, and displays the scaling function and % the scaled wavlet kernels, as well as the corresponding frame bounds. It % then computes the wavelets centered on a single vertex, and displays % them. This essentally reproduces figure 3 from % Hammond,Vangergheynst, Gribonval 2010. % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. % Create swiss roll point cloud function sgwt_demo1 close all fprintf('Welcome to SGWT demo #1\n'); npoints=500; fprintf('Creating Swiss Roll point cloud with %g points\n',npoints); dataparams=struct('n',npoints,'dataset',-1','noise',0,'state',0); r=create_synthetic_dataset(dataparams); x=rescale_center(r.x); fprintf('Computing edge weights and graph Laplacian\n'); % Compute Weighted graph adjacency matrix, and graph Laplacian d=distanz(x); s=.1; A=exp(-d.^2/(2*s^2)); L=full(sgwt_laplacian(A)); fprintf('Measuring largest eigenvalue, lmax = '); %% Design filters for transform Nscales=4; lmax=sgwt_rough_lmax(L); fprintf('%g\n',lmax); fprintf('Designing transform in spectral domain\n'); designtype='abspline3'; %designtype='mexican_hat'; %designtype='meyer'; %designtype='simple_tf'; [g,t]=sgwt_filter_design(lmax,Nscales,'designtype',designtype); arange=[0 lmax]; %% Display filter design in spectral domain figure sgwt_view_design(g,t,arange); ylim([0 3]) set(gcf,'position',[0 780,600,300]) %% Chebyshev polynomial approximation m=50; % order of polynomial approximation fprintf('Computing Chebyshev polynomials of order %g for fast transform \n',m); for k=1:numel(g) c{k}=sgwt_cheby_coeff(g{k},m,m+1,arange); end %% compute transform of delta at one vertex jcenter=32; % vertex to center wavelets to be shown fprintf('Computing forward transform of delta at vertex %g\n',jcenter); N=size(L,1); d=sgwt_delta(N,jcenter); % forward transform, using chebyshev approximation wpall=sgwt_cheby_op(d,L,c,arange); fprintf('Displaying wavelets\n'); if (exist('OCTAVE_VERSION','builtin')~=0) % settings for octave msize=5; plotchar='s'; else % settings for native matlab msize=100; plotchar='.'; end cp=[-1.4,-16.9,3.4]; % camera position %% Visualize result % show original point ws=300; figure; xp=0; yp=ws+100; set(gcf,'position',[xp,yp,ws-10,ws+10]); scatter3(x(1,:),x(2,:),x(3,:),msize,d,plotchar); set(gcf,'Colormap',[.5 .5 .5;1 0 0]); clean_axes(cp); title(sprintf('Vertex %g',jcenter)); % show wavelets for n=1:Nscales+1 wp=wpall{n}; figure xp=mod(n,3)*(ws+10); yp=(1-floor((n)/3))*(ws+100); set(gcf,'position',[xp,yp,ws-10,ws+10]); scatter3(x(1,:),x(2,:),x(3,:),msize,wp,plotchar); colormap jet caxis([-1 1]*max(abs(wp))); clean_axes(cp); hcb=colorbar('location','north'); cxt=get(hcb,'Xtick'); cxt=[cxt(1),0,cxt(end)]; set(hcb,'Xtick',cxt); cpos=get(hcb,'Position'); cpos(4)=.02; % make colorbar thinner set(hcb,'Position',cpos); set(hcb,'Position',[.25 .91 .6 .02]); if n==1 title('Scaling function'); else title(sprintf('Wavelet at scale j=%g, t_j = %0.2f',n-1,t((n-1)))); end end function clean_axes(cp) xlim([-1 1]);ylim([-1 1]);zlim([-1 1]); set(gca,'Xtick',[-1 0 1]); set(gca,'Ytick',[-1 0 1]); set(gca,'Ztick',[-1 0 1]); axis square set(gca,'CameraPosition',cp); % rescale_center % center input data at origin, then rescale so that all coordinates % are between -1 and 1 % % x should be dxN function r=rescale_center(x) N=size(x,2); d=size(x,1); x=x-repmat(mean(x,2),[1,N]); c=max(abs(x(:))); r=x/c;
github
aamiranis/sampling_theory-master
sgwt_soft_threshold.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/utils/sgwt_soft_threshold.m
1,117
utf_8
2c60d2416dbd759097345f610f622d03
% sgwt_soft_threshold : Soft thresholding operator % % x_t = bpdq_soft_threshold(x,tgamma) % % Applies soft thresholding to each component of x % % Inputs: % x - input signal % tgamma - threshold % % Outputs: % x_t - soft thresholded result % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function x_t = sgwt_soft_threshold(x,tgamma) tmp=abs(x)-tgamma; x_t = sign(x).*tmp.*(tmp>0);
github
aamiranis/sampling_theory-master
argselectCheck.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/utils/argselectCheck.m
2,050
utf_8
13096e9ec4f9fc475fb154c322cc7352
% argselectCheck : Check if control parameters are valid % % function argselectCheck(control_params,varargin_in) % % Inputs: % control_params and varargin_in are both cell arrays % that are lists of pairs 'name1',value1,'name2',value2,... % % This function checks that every name in varargin_in is one of the names % in control_params. It will generate an error if not, otherwise it will % do nothing % % This is used at beginning of function to simulate keyword argument % passing. Typical usage is % % argselectAssign(control_params); % argselectCheck(control_params,varargin); % argselectAssign(varargin); % % where control_params is a cell list of variable,value pairs containing % the default parameter values. % % See also argselectAssign % % Author : David K. Hammond, EPFL LTS2 % Date : December, 2007 % Project : common utilities % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function argselectCheck(control_params,varargin_in) [param_names{1:(length(control_params)/2)}]=control_params{1:2:end}; % check that passed in control parameters are valid for j=1:2:length(varargin_in) if(isempty(strmatch(varargin_in{j},param_names))) error(['Invalid control parameter : ',varargin_in{j},... ' Valid options are',sprintf('\n'),... sprintf('%s \n',param_names{:})]); end end
github
aamiranis/sampling_theory-master
argselectAssign.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/utils/argselectAssign.m
1,706
utf_8
a225f6b476ca9762053f486bc6a2f8b9
% argselectAssign : Assign variables in calling workspace % % function argselectAssign(variable_value_pairs) % % Inputs : % variable_value_pairs is a cell list of form % 'variable1',value1,'variable2',value2,... % This function assigns variable1=value1 ... etc in the *callers* workspace % % This is used at beginning of function to simulate keyword argument % passing. Typical usage is % % argselectAssign(control_params); % argselectCheck(control_params,varargin); % argselectAssign(varargin); % % where control_params is a cell list of variable,value pairs containing % the default parameter values. % % See also argselectCheck % % Author : David K. Hammond, EPFL LTS2 % Date : December, 2007 % Project : common utilities % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function argselectAssign(variable_value_pairs) for j =1:2:length(variable_value_pairs) pname=variable_value_pairs{j}; pval=variable_value_pairs{j+1}; assignin('caller',pname,pval); end
github
aamiranis/sampling_theory-master
vec.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/utils/vec.m
857
utf_8
b795ffb5f2186f33aaa81ef7daa3cac5
% vec : vectorize input % % r=vec(x) % % returns r=x(:); % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=vec(x) r=x(:);
github
aamiranis/sampling_theory-master
sgwt_show_im.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/utils/sgwt_show_im.m
1,806
utf_8
f0aa589e604cc94d1e07c64a3eb27723
% sgwt_show_im : Display image, with correct pixel zoom % % sgwt_show_im(im,range,zoom) % % Inputs : % im - 2-d image % range - 2 element vector giving display color map range, % range(1) maps to black, range(2) maps to white % If range not given, or empty matrix given for range, then % the default is to set it to the minimum and maximum of input image. % zoom - # of screen pixels taken by single image pixel. Default is 1 % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function sgwt_show_im(im,range,zoom) if nargin<3 zoom=1; end if ( nargin<2 || isempty(range) ) range(1)=min(im(:)); range(2)=max(im(:)); end nshades=256; d_im = ( im-range(1) ) *(nshades-1) /(range(2)-range(1)); dsize=size(im)*zoom; % size in pixels to show on screen image( d_im ); colormap(gray(nshades)); ax=gca; oldunits=get(ax,'Units'); set(ax,'Units','pixels'); pos = get(ax,'Position'); axis('off'); ctr = pos(1:2)+pos(3:4)/2; set(ax,'Position',[floor(ctr-dsize/2)+0.5, dsize] ); axis('equal'); % restore units set(ax,'Units',oldunits);
github
tmquan/PVR-master
resize.m
.m
PVR-master/resize.m
6,573
utf_8
fc6ab29e1a4106ddb03733c0b1048169
function x = resize(x,newsiz) %RESIZE Resize any arrays and images. % Y = RESIZE(X,NEWSIZE) resizes input array X using a DCT (discrete % cosine transform) method. X can be any array of any size. Output Y is % of size NEWSIZE. % % Input and output formats: Y has the same class as X. % % Note: % ---- % If you want to multiply the size of an RGB image by a factor N, use the % following syntax: RESIZE(I,size(I).*[N N 1]) % % Examples: % -------- % % Resize a signal % % original signal % x = linspace(0,10,300); % y = sin(x.^3/100).^2 + 0.05*randn(size(x)); % % resized signal % yr = resize(y,[1 1000]); % plot(linspace(0,10,1000),yr) % % % Upsample and downsample a B&W picture % % original image % I = imread('tire.tif'); % % upsampled image % J = resize(I,size(I)*2); % % downsampled image % K = resize(I,size(I)/2); % % pictures % figure,imshow(I),figure,imshow(J),figure,imshow(K) % % % Upsample and stretch a 3-D scalar array % load wind % spd = sqrt(u.^2 + v.^2 + w.^2); % wind speed % upsspd = resize(spd,[64 64 64]); % upsampled speed % slice(upsspd,32,32,32); % colormap(jet) % shading interp, daspect(size(upsspd)./size(spd)) % view(30,40), axis(volumebounds(upsspd)) % % % Upsample and stretch an RGB image % I = imread('onion.png'); % J = resize(I,size(I).*[2 2 1]); % K = resize(I,size(I).*[1/2 2 1]); % figure,imshow(I),figure,imshow(J),figure,imshow(K) % % See also UPSAMPLE, RESAMPLE, IMRESIZE, DCTN, IDCTN % % -- Damien Garcia -- 2009/11, revised 2010/11 % website: <a % href="matlab:web('http://www.biomecardio.com')">www.BiomeCardio.com</a> error(nargchk(2,2,nargin)); siz = size(x); N = prod(siz); % Do nothing if size is unchanged if isequal(siz,newsiz), return, end % Do nothing if input is empty if isempty(x), return, end % Check size arguments assert(isequal(length(siz),length(newsiz)),... 'Number of dimensions must not change.') newsiz = round(newsiz); assert(all(newsiz>0),'Size arguments must be >0.') class0 = class(x); is01 = islogical(x); % Deal with NaNs if any I = isnan(x); if any(I(:)) % replace NaNs by nearest neighbors [~,L] = bwdist(~I); x(I) = x(L(I)); % resize x = resize(x,newsiz); I = resize(I,newsiz); % reintroduce NaN x(I) = NaN; return end % DCT transform x = dctn(x); % Crop the DCT coefficients for k = 1:ndims(x) siz(k) = min(newsiz(k),siz(k)); x(siz(k)+1:end,:) = []; x = reshape(x,circshift(siz,[0 1-k])); x = shiftdim(x,1); end % Pad the DCT coefficients with zeros x = padarray(x,max(newsiz-siz,zeros(size(siz))),0,'post'); % inverse DCT transform x = idctn(x)*sqrt(prod(newsiz)/N); % Back to the previous class if is01, x = round(x); end x = cast(x,class0); end %% DCTN function y = dctn(y) %DCTN N-D discrete cosine transform. % Y = DCTN(X) returns the discrete cosine transform of X. The array Y is % the same size as X and contains the discrete cosine transform % coefficients. This transform can be inverted using IDCTN. % % Reference % --------- % Narasimha M. et al, On the computation of the discrete cosine % transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. % % Example % ------- % RGB = imread('autumn.tif'); % I = rgb2gray(RGB); % J = dctn(I); % imshow(log(abs(J)),[]), colormap(jet), colorbar % % The commands below set values less than magnitude 10 in the DCT matrix % to zero, then reconstruct the image using the inverse DCT. % % J(abs(J)<10) = 0; % K = idctn(J); % figure, imshow(I) % figure, imshow(K,[0 255]) % % -- Damien Garcia -- 2008/06, revised 2011/11 % -- www.BiomeCardio.com -- y = double(y); sizy = size(y); y = squeeze(y); dimy = ndims(y); % Some modifications are required if Y is a vector if isvector(y) dimy = 1; if size(y,1)==1, y = y.'; end end % Weighting vectors w = cell(1,dimy); for dim = 1:dimy n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); w{dim} = exp(1i*(0:n-1)'*pi/2/n); end % --- DCT algorithm --- if ~isreal(y) y = complex(dctn(real(y)),dctn(imag(y))); else for dim = 1:dimy siz = size(y); n = siz(1); y = y([1:2:n 2*floor(n/2):-2:2],:); y = reshape(y,n,[]); y = y*sqrt(2*n); y = ifft(y,[],1); y = bsxfun(@times,y,w{dim}); y = real(y); y(1,:) = y(1,:)/sqrt(2); y = reshape(y,siz); y = shiftdim(y,1); end end y = reshape(y,sizy); end %% IDCTN function y = idctn(y) %IDCTN N-D inverse discrete cosine transform. % X = IDCTN(Y) inverts the N-D DCT transform, returning the original % array if Y was obtained using Y = DCTN(X). % % Reference % --------- % Narasimha M. et al, On the computation of the discrete cosine % transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. % % Example % ------- % RGB = imread('autumn.tif'); % I = rgb2gray(RGB); % J = dctn(I); % imshow(log(abs(J)),[]), colormap(jet), colorbar % % The commands below set values less than magnitude 10 in the DCT matrix % to zero, then reconstruct the image using the inverse DCT. % % J(abs(J)<10) = 0; % K = idctn(J); % figure, imshow(I) % figure, imshow(K,[0 255]) % % See also DCTN, IDSTN, IDCT, IDCT2, IDCT3. % % -- Damien Garcia -- 2009/04, revised 2011/11 % -- www.BiomeCardio.com -- y = double(y); sizy = size(y); y = squeeze(y); dimy = ndims(y); % Some modifications are required if Y is a vector if isvector(y) dimy = 1; if size(y,1)==1 y = y.'; end end % Weighing vectors w = cell(1,dimy); for dim = 1:dimy n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); w{dim} = exp(1i*(0:n-1)'*pi/2/n); end % --- IDCT algorithm --- if ~isreal(y) y = complex(idctn(real(y)),idctn(imag(y))); else for dim = 1:dimy siz = size(y); n = siz(1); y = reshape(y,n,[]); y = bsxfun(@times,y,w{dim}); y(1,:) = y(1,:)/sqrt(2); y = ifft(y,[],1); y = real(y*sqrt(2*n)); I = (1:n)*0.5+0.5; I(2:2:end) = n-I(1:2:end-1)+1; y = y(I,:); y = reshape(y,siz); y = shiftdim(y,1); end end y = reshape(y,sizy); end
github
tmquan/PVR-master
vec.m
.m
PVR-master/vec.m
42
utf_8
8909a59f67f977a13b68984a04173168
function u = vec(v) u = v(:); return
github
pauloabelha/gazebo_tasks-master
GenerateBoxSDF.m
.m
gazebo_tasks-master/GenerateBoxSDF.m
6,266
utf_8
247027bd44b2954c039f37434208aca7
% By Paulo Abelha % % Generates a parametrizable rectangular box for Gazebo % I use it to generate the box that holds the grains for my % 'scooping_grains' task % This was very useful when I was extensively % experimenting with different boxes % % task_folder is the folder with the .world, tool(s) and task code % (e.g. '~/.gazebo/gazebo_models/scooping_grains/') % box_name - the name to put in the sdf (be creative!) % % bottom_pose - 1x3 array with the x,y,z pose of the box centre % width (as in gazebo's y axis) % length (as in gazebo's x axis) % height (I leave it as an exercise to guess this variable) % thickness (thickness of each wall) % description (last chance to be creative) function GenerateBoxSDF( task_folder, box_name, bottom_pose, width, length, height, thickness, description ) sdf_version = '1.6'; author_name = 'Paulo Abelha'; author_email = '[email protected]'; if ~exist('description','var') description = ''; end system(['mkdir ' task_folder box_name]); GenerateModelConfigFile([task_folder box_name], sdf_version, box_name, author_name, author_email, description); filepath = [task_folder box_name '/' box_name '.sdf']; fid = fopen(filepath,'w+'); fprintf(fid,'<?xml version=''1.0''?>'); fprintf(fid,'\n'); fprintf(fid,['<sdf version=''' sdf_version '''>']); fprintf(fid,'\n'); fprintf(fid,['\t<model name=''' box_name '''>']); fprintf(fid,'\n'); fprintf(fid,['\t<pose>' num2str(bottom_pose(1)) ' ' num2str(bottom_pose(2)) ' ' num2str(bottom_pose(3)) ' 0 0 0 </pose>']); fprintf(fid,'\n'); fprintf(fid,'\t<static>true</static>'); fprintf(fid,'\n'); fprintf(fid,'\n'); pos_0 = [0 0 thickness/2]; size_0 = [length, width, thickness]; GenerateLinkTag(fid, [box_name '_' num2str(0)], pos_0, size_0, 2000, 2000, 'WoodFloor'); fprintf(fid,'\n'); fprintf(fid,'\n'); pos_1 = [(-length/2)+thickness/2, 0, thickness + (height/2)]; size_1 = [thickness, width - (2*thickness), height]; GenerateLinkTag(fid, [box_name '_' num2str(1)], pos_1, size_1, 2000, 2000, 'WoodFloor'); fprintf(fid,'\n'); fprintf(fid,'\n'); pos_2 = pos_1; pos_2(1) = -pos_1(1); size_2 = size_1; GenerateLinkTag(fid, [box_name '_' num2str(2)], pos_2, size_2, 2000, 2000, 'WoodFloor'); fprintf(fid,'\n'); fprintf(fid,'\n'); pos_3 = [0, (-width/2)+thickness/2, thickness + (height/2)]; size_3 = [length, thickness, height]; GenerateLinkTag(fid, [box_name '_' num2str(3)], pos_3, size_3, 2000, 2000, 'WoodFloor'); fprintf(fid,'\n'); fprintf(fid,'\n'); pos_4 = pos_3; pos_4(2) = -pos_3(2); size_4 = size_3; GenerateLinkTag(fid, [box_name '_' num2str(4)], pos_4, size_4, 2000, 2000, 'WoodFloor'); fprintf(fid,'\n'); fprintf(fid,'\n'); fprintf(fid,'\t</model>'); fprintf(fid,'\n'); fprintf(fid,'</sdf>'); fclose(fid); end function GenerateGeometryTag(fid, size) fprintf(fid,'\t\t<geometry>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t<box>'); fprintf(fid,'\n'); fprintf(fid,['\t\t\t\t<size>' num2str(size(1)) ' ' num2str(size(2)) ' ' num2str(size(3)) '</size>']); fprintf(fid,'\n'); fprintf(fid,'\t\t\t</box>'); fprintf(fid,'\n'); fprintf(fid,'\t\t</geometry>'); end function GenerateSurfaceTag(fid, mu, mu2) fprintf(fid,'\t\t<surface>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t<friction>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t\t<ode>'); fprintf(fid,'\n'); fprintf(fid,['\t\t\t\t\t<mu>' num2str(mu) '</mu>']); fprintf(fid,'\n'); fprintf(fid,['\t\t\t\t\t<mu2>' num2str(mu2) '</mu2>']); fprintf(fid,'\n'); fprintf(fid,'\t\t\t\t</ode>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t</friction>'); fprintf(fid,'\n'); fprintf(fid,'\t\t</surface>'); end function GenerateMaterialTag(fid, material) fprintf(fid,'\t\t<material>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t<script>'); fprintf(fid,'\n'); fprintf(fid,'\t\t\t\t<uri>file://media/materials/scripts/gazebo.material</uri>'); fprintf(fid,'\n'); fprintf(fid,['\t\t\t\t<name>Gazebo/' material '</name>']); fprintf(fid,'\n'); fprintf(fid,'\t\t\t</script>'); fprintf(fid,'\n'); fprintf(fid,'\t\t</material>'); end function GenerateLinkTag(fid, name, pose, size, mu1, mu2, material) fprintf(fid,['\t<link name=''' name '''>']); fprintf(fid,'\n'); fprintf(fid,['\t\t<pose>' num2str(pose(1)) ' ' num2str(pose(2)) ' ' num2str(pose(3)) ' 0 0 0 </pose>']); fprintf(fid,'\n'); coliision_name = [name '_coliision']; fprintf(fid,['\t\t<collision name=''' coliision_name '''>']); fprintf(fid,'\n'); GenerateGeometryTag(fid, size); fprintf(fid,'\n'); GenerateSurfaceTag(fid, mu1, mu2); fprintf(fid,'\n'); fprintf(fid,'\t\t</collision>'); fprintf(fid,'\n'); fprintf(fid,'\n'); visual_name = [name '_visual']; fprintf(fid,['\t\t<visual name=''' visual_name '''>']); fprintf(fid,'\n'); GenerateGeometryTag(fid, size); fprintf(fid,'\n'); GenerateMaterialTag(fid, material); fprintf(fid,'\n'); fprintf(fid,'\t\t</visual>'); fprintf(fid,'\t</link>'); end function GenerateModelConfigFile(root_folder, sdf_version, name, author_name, author_email, description) filepath = [root_folder '/model.config']; fid = fopen(filepath,'w+'); fprintf(fid,'<?xml version=''1.0''?>'); fprintf(fid,'\n'); fprintf(fid,['\t<model>']); fprintf(fid,'\n'); fprintf(fid,['\t\t<name>' name '</name>']); fprintf(fid,'\n'); fprintf(fid,['\t\t<sdf version=''' sdf_version '''>' name '.sdf</sdf>']); fprintf(fid,'\n'); fprintf(fid,['\t\t<author>']); fprintf(fid,'\n'); fprintf(fid,['\t\t\t<name>' author_name '</name>']); fprintf(fid,'\n'); fprintf(fid,['\t\t\t<email>' author_email '</email>']); fprintf(fid,'\n'); fprintf(fid,['\t\t</author>']); fprintf(fid,'\n'); fprintf(fid,['\t\t<description>']); fprintf(fid,'\n'); fprintf(fid,['\t\t\t' description]); fprintf(fid,'\n'); fprintf(fid,['\t\t</description>']); fprintf(fid,'\n'); fprintf(fid,['\t</model>']); end
github
Rahmeen14/Chall-Vihaan-master
MeanVariance.m
.m
Chall-Vihaan-master/routes/codes/MeanVariance.m
1,364
utf_8
8b23466de4e94d6052135ba671cde88f
## Copyright (C) 2017 Shreya ## ## 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 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} MeanVariance (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: Shreya <Shreya@SARTHAK-LAPTOP> ## Created: 2017-10-28 % X is a 15x4 matrix_type % It stores amount, location pincode, time and merchant pincode function [mu, sigma] = MeanVariance (X) mu = zeros(4,1); sigma = zeros (4,1); for i = 1:4 for j = 1:15 mu(i,1) = mu(i,1) + X(j,i); endfor mu(i,1)= mu(i,1)/15; %disp("Mean"); %disp(mu(i,1)); endfor for i = 1:4 for j = 1:15 sigma(i,1) = sigma(i,1) + (X(j,i) - mu(i,1))^2; endfor sigma(i,1)= sigma(i,1)/15; %disp("i"); %disp(i); %disp(sigma); endfor endfunction
github
Rahmeen14/Chall-Vihaan-master
probability.m
.m
Chall-Vihaan-master/routes/codes/probability.m
1,015
utf_8
a28db31f8c29e452e555c6e50edd8c41
## Copyright (C) 2017 Shreya ## ## 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 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} probability (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: Shreya <Shreya@SARTHAK-LAPTOP> ## Created: 2017-10-28 function p = probability (x, mu, var) p = (0.399/(var^(0.5)))*exponential(-(((x- mu)^2)/(2*var))); %disp("p"); %disp(p); endfunction
github
Rahmeen14/Chall-Vihaan-master
main.m
.m
Chall-Vihaan-master/routes/codes/main.m
1,710
utf_8
1f7ebc3c7c60fd3954acb86f1669cac3
## Copyright (C) 2017 Shreya ## ## 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 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} main (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: Shreya <Shreya@SARTHAK-LAPTOP> ## Created: 2017-10-28 function n = main(fileName,amount, locPin, time, merchPin) %function n = main(g) %disp(amount) %disp(locPin) %disp(time) %disp(merchPin) amount=double(amount); locPin=double(locPin); time=double(time); merchPin=double(merchPin); X = csvread(fileName); %X = csvread('sarthak.txt'); Y = zeros(15,4); for i=1:15 for j =1:4 Y(i,j) = X(i,j+2); endfor endfor [mu, sigma] = MeanVariance(Y); Z = [amount, locPin, time, merchPin]; %Z=[60000,110017,12,110017]; ans = predictNature(Z, mu, sigma); flag = 1; for i=1:4 if (ans(i,1)==1) flag =0; endif endfor if (flag==1) fprintf("You can Proceed with your transaction."); else fprintf("Based on your history,this transaction doesn't confirm to your history,Please confirm your identity."); endif n=1; endfunction
github
Rahmeen14/Chall-Vihaan-master
predictNature.m
.m
Chall-Vihaan-master/routes/codes/predictNature.m
1,438
utf_8
0f5d425211ad4bf375290e74adbc88bc
## Copyright (C) 2017 Shreya ## ## 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 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} predictNature (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: Shreya <Shreya@SARTHAK-LAPTOP> ## Created: 2017-10-28 % X is a new single data input (horizontal) from node.js that i am gng to calculate % the probability for function prediction = predictNature (X, mu, sigma) prediction = ones(4,1); for i =1:4 prediction(i,1) = prediction(i,1) * probability(X(1,i),mu(i,1), sigma(i,1)); endfor for i = 1:4 if(i!=3) if (prediction(i,1)<0.0000001) prediction(i,1) =1; else prediction(i,1) = 0; endif else if (prediction(i,1)<0.02) prediction(i,1) =1; else prediction(i,1) = 0; endif endif endfor endfunction
github
Rahmeen14/Chall-Vihaan-master
exponential.m
.m
Chall-Vihaan-master/routes/codes/exponential.m
941
utf_8
5da284170d8f5071a07b143da331d909
## Copyright (C) 2017 Shreya ## ## 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 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} exponential (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: Shreya <Shreya@SARTHAK-LAPTOP> ## Created: 2017-10-28 function ans = exponential (x) ans = (2.718)^x; endfunction
github
FanmingL/independent-analysis-master
my_RealTimeIVA.m
.m
independent-analysis-master/iva_matlab/my_RealTimeIVA.m
5,722
utf_8
5e3bd938e17b5a4c18e57b9e1f3d07c3
%initialization %it spends aboud 0.36 seconds to initialize %//1 matlab clear clear; close all; %//2 initialize some coeffs according to the paper fft_length = 256; %unit is sample window_length = fft_length; %unit is sample shift_size = 64; %unit is sample beta = 0.5; %smoothing factor reverbration_time = 250; %unit is ms windows = hanning(fft_length); %hanning window expect_sample_rate = 8000; %8kHz sample rate yita = 1.0; %gridant desent coeff start_simulate_point= 200000; %point start used to simulate simulation_length = 40000; %length used to simulate, unit is ms c = 344; % Sound velocity(m/s) reciver_position1 = [ 2.0 2.0 2.4 ]; % Receiver position[ x y z ](m) source_position1 = [ 2.0 2.4 2.0 ]; % Source position[ x y z ](m) reciver_position2 = [ 2.0 2.0 1.9 ]; % Receiver position[ x y z ](m) source_position2 = [ 2.0 1.6 2.7 ]; % Source position[ x y z ](m) room_size = [ 5.0 4.0 6.0 ]; % Room dimensions[ x y z ](m) number_of_samples = reverbration_time/1000 ... * expect_sample_rate; % Number of samples %//3 read audio from files and resample to expect sample rate [source1,fs1] = audioread('female_record.wav'); [source2,fs2] = audioread('male_record.wav'); source1 = resample(source1,expect_sample_rate,fs1); source2 = resample(source2,expect_sample_rate,fs2); source1 = source1(start_simulate_point:floor(start_simulate_point+... simulation_length/1000*expect_sample_rate),1); source2 = source2(start_simulate_point:floor(start_simulate_point+... simulation_length/1000*expect_sample_rate),1); %//4 generate the reverbration audio impulse11 = rir_generator(c,expect_sample_rate,reciver_position1,source_position1,... room_size,reverbration_time/1000,number_of_samples ) ; impulse12 = rir_generator(c,expect_sample_rate,reciver_position2,source_position1,... room_size,reverbration_time/1000,number_of_samples ) ; impulse21 = rir_generator(c,expect_sample_rate,reciver_position1,source_position2,... room_size,reverbration_time/1000,number_of_samples ) ; impulse22 = rir_generator(c,expect_sample_rate,reciver_position2,source_position2,... room_size,reverbration_time/1000,number_of_samples ) ; observation1=conv(source1,impulse11)+conv(source2,impulse21); observation2=conv(source1,impulse12)+conv(source2,impulse22); contrast_plot(source1,source2,expect_sample_rate,'source'); contrast_plot(observation1,observation2,expect_sample_rate,'observation'); %//5 initialize demixing matrix G = zeros(2,2,fft_length); for i=1:fft_length G(1,1,i)=1;G(2,2,i)=1; end ksi = ones(fft_length,1); phi = ones(fft_length,2); R = zeros(2,2,fft_length); audio_estimate = zeros(fft_length,2); number_of_overlap = floor(fft_length/shift_size)+1; estimate_out1 = zeros(length(observation1),1); estimate_out2 = zeros(length(observation2),1); norm_coeff = zeros(2,2,fft_length); tic; %//6 iteration for n = 1:(floor((length(observation1)-window_length)/shift_size)) % at Nth times audio_cut1 = observation1((n-1)*shift_size+1:(n-1)*shift_size+window_length).*windows; audio_cut2 = observation2((n-1)*shift_size+1:(n-1)*shift_size+window_length).*windows; audio_cut1_fft = fft(audio_cut1); audio_cut2_fft = fft(audio_cut2); audio_cut_fft = [audio_cut1_fft, audio_cut2_fft]; for k = 1:floor(fft_length/2+1) audio_estimate(k,:) = (G(:,:,k)* (audio_cut_fft(k,:)).').'; norm_coeff(:,:,k) = diag(diag(inv(G(:,:,k)))); end for k = floor(fft_length/2+1)+1:fft_length audio_estimate(k,:) = conj(audio_estimate(fft_length-k+2,:)); end phi = audio_estimate ./ (sqrt(diag((audio_estimate)'*(audio_estimate)))'); for k = 1:floor(fft_length/2+1) R(:,:,k) = (audio_estimate(k,:)'*phi(k,:)).'; gradient_k = (diag(diag(R(:,:,k)))-R(:,:,k))*G(:,:,k); G(:,:,k) = G(:,:,k) + yita/sqrt(ksi(k))*gradient_k; ksi(k) = beta * ksi(k) + (1-beta) * (audio_cut_fft(k,:)*audio_cut_fft(k,:)')/2; audio_estimate(k,:) = audio_estimate(k,:) * norm_coeff(:,:,k); end for k = floor(fft_length/2+1)+1:fft_length audio_estimate(k,:) = conj(audio_estimate(fft_length-k+2,:)); end estimate_out1((n-1)*shift_size+1:(n-1)*shift_size+window_length)=... ifft(audio_estimate(:,1))+estimate_out1((n-1)*shift_size... +1:(n-1)*shift_size+window_length); estimate_out2((n-1)*shift_size+1:(n-1)*shift_size+window_length)=... ifft(audio_estimate(:,2))+estimate_out2((n-1)*shift_size... +1:(n-1)*shift_size+window_length); end toc estimate_out1 = estimate_out1/max(abs(estimate_out1)); estimate_out2 = estimate_out2/max(abs(estimate_out2)); contrast_plot(estimate_out1,estimate_out2,expect_sample_rate,'separated'); function contrast_plot(x,y,fs,title_str) figure; subplot(2,1,1); plot((1:length(x))/fs,x,'b'); xlabel('time(s)'); ylabel('relative sound intensity'); title([title_str,'1']); subplot(2,1,2); plot((1:length(y))/fs,y,'b'); title([title_str,'2']); xlabel('time(s)'); ylabel('relative sound intensity'); pause(0); end
github
FanmingL/independent-analysis-master
my_RealTimeIVA_GMM.m
.m
independent-analysis-master/iva_matlab/my_RealTimeIVA_GMM.m
8,995
utf_8
17b3add0f5b9b511801d4f3eeffe8ee0
%initialization %it spends aboud 0.36 seconds to initialize %//1 matlab clear clear; close all; load('GMM_SYS_4.mat') %//2 initialize some coeffs according to the paper gamma_whiten = 0.0025; lambda = 0.95; Ns = 4; fft_length = 512; %unit is sample window_length = fft_length; %unit is sample shift_size = 256; %unit is sample reverbration_time = 250; %unit is ms windows = hanning(fft_length); %hanning window expect_sample_rate = 8000; %8kHz sample rate start_simulate_point= 200000; %point start used to simulate simulation_length = 50000; %length used to simulate, unit is ms c = 344; % Sound velocity(m/s) reciver_position1 = [ 2.0 2.0 2.4 ]; % Receiver position[ x y z ](m) source_position1 = [ 2.0 2.4 2.0 ]; % Source position[ x y z ](m) reciver_position2 = [ 2.0 2.0 1.9 ]; % Receiver position[ x y z ](m) source_position2 = [ 2.0 1.6 2.7 ]; % Source position[ x y z ](m) room_size = [ 5.0 4.0 6.0 ]; % Room dimensions[ x y z ](m) number_of_samples = reverbration_time/1000 ... * expect_sample_rate; % Number of samples %//3 read audio from files and resample to expect sample rate [source1,fs1] = audioread('female_record.wav'); [source2,fs2] = audioread('male_record.wav'); source1 = resample(source1,expect_sample_rate,fs1); source2 = resample(source2,expect_sample_rate,fs2); source1 = source1(start_simulate_point:floor(start_simulate_point+... simulation_length/1000*expect_sample_rate),1); source2 = source2(start_simulate_point:floor(start_simulate_point+... simulation_length/1000*expect_sample_rate),1); %//4 generate the reverbration audio impulse11 = rir_generator(c,expect_sample_rate,reciver_position1,source_position1,... room_size,reverbration_time/1000,number_of_samples ) ; impulse12 = rir_generator(c,expect_sample_rate,reciver_position2,source_position1,... room_size,reverbration_time/1000,number_of_samples ) ; impulse21 = rir_generator(c,expect_sample_rate,reciver_position1,source_position2,... room_size,reverbration_time/1000,number_of_samples ) ; impulse22 = rir_generator(c,expect_sample_rate,reciver_position2,source_position2,... room_size,reverbration_time/1000,number_of_samples ) ; observation1=conv(source1,impulse11)+conv(source2,impulse21); observation2=conv(source1,impulse12)+conv(source2,impulse22); contrast_plot(source1,source2,expect_sample_rate,'source'); contrast_plot(observation1,observation2,expect_sample_rate,'observation'); %//5 initialize demixing matrix W = zeros(2,2,fft_length); for i=1:fft_length W(1,1,i)=1;W(2,2,i)=1; end gaussian_s1 = 1:Ns; gaussian_s2 = 1:Ns; gaussian_st = meshgrid(gaussian_s1,gaussian_s2); gassian_v1 = 1./Sigma_1; gassian_v2 = 1./Sigma_2; p_s1 = Phi1_mean; p_s2 = Phi2_mean; p_st = ones(size(gaussian_st))/Ns/Ns; q_s1 = ones(1,Ns)/Ns; q_s2 = ones(1,Ns)/Ns; q_st = meshgrid(q_s1,q_s2); step1_tmp = zeros(size(q_st)); V = W; %whitening matrix I = [1,0;0,1]; %unit matrix M = zeros(size(W)); beta = zeros(1,fft_length); audio_estimate = zeros(fft_length,2); audio_estimate_trans= audio_estimate.'; estimate_out1 = zeros(length(observation1),1); estimate_out2 = zeros(length(observation2),1); m_1r = q_s1; m_1r_old = zeros(1,Ns); m_2r = q_s2; m_2r_old = zeros(1,Ns); signal_whitened = zeros(2,fft_length); akbk_star = zeros(2,1,fft_length); test_whitening = zeros(2,floor(length(observation1)/window_length)+10); tic; %//6 iterator for n = 1:(floor((length(observation1)-window_length)/shift_size)) % at Nth times audio_cut1 = observation1((n-1)*shift_size+1:(n-1)*shift_size+window_length).*windows; audio_cut2 = observation2((n-1)*shift_size+1:(n-1)*shift_size+window_length).*windows; audio_cut1_fft = fft(audio_cut1); audio_cut2_fft = fft(audio_cut2); audio_cut_fft = [audio_cut1_fft, audio_cut2_fft].'; %online whitening for k = 1:floor(fft_length/2+1) signal_whitened(:,k) = audio_cut_fft(:,k); %signal_whitened(:,k) = V(:,:,k)*audio_cut_fft(:,k); %V(:,:,k) = V(:,:,k)+gamma_whiten*(I-signal_whitened(:,k)*signal_whitened(:,k)')*V(:,:,k); end %record some samples to test whitening efficiency test_whitening(:,n) = signal_whitened(:,40); %E-Step for index_s1=1:Ns for index_s2=1:Ns product_frequency = 0; for k=1:floor(fft_length/2+1) product_frequency = product_frequency+(multi_guassian_calculate(signal_whitened(:,k),W(:,:,k)'... *diag([gassian_v1(k,index_s1),gassian_v2(k,index_s2)])*W(:,:,k))); if (isnan(product_frequency)||isinf(product_frequency)) fprintf('1') return; end end q_st(index_s1,index_s2)=log(p_s1(index_s1)*p_s2(index_s2))+product_frequency; if (find(isnan(q_st))) fprintf('2'); return; end end end q_st = q_st-max(max(q_st)); q_st = exp(q_st)/sum(sum(exp(q_st))); if (find(isnan(q_st))) fprintf('5'); return; end %M-Step q_s1 = sum(q_st,2).'; q_s2 = sum(q_st,1); m_1r_old = m_1r; m_2r_old = m_2r; m_1r = lambda * m_1r + q_s1; m_2r = lambda * m_2r + q_s2; % p_s1 = m_1r; % p_s2 = m_2r; % % p_s1=p_s1/sum(p_s1); % p_s2=p_s2/sum(p_s2); for k = 1:floor(fft_length/2+1) for index_s1=1:Ns for index_s2=1:Ns step1_tmp(index_s1,index_s2)=... (gassian_v1(k,index_s1)-gassian_v2(k,index_s2))*q_st(index_s1,index_s2); end end M(:,:,k) = lambda*M(:,:,k)+sum(sum(step1_tmp))*signal_whitened(:,k)*signal_whitened(:,k)'; beta(k) = (M(1,1,k)+M(2,2,k))/2-sqrt(((M(1,1,k)-M(2,2,k))^2)/4+abs(M(1,2,k))^2); if (find(isnan(beta))) fprintf('4'); return; end akbk_star(:,:,k) = 1/sqrt(1+((beta(k)-M(1,1,k))/M(1,2,k))^2)*[1;(beta(k)-M(1,1,k))/M(1,2,k)]; tmp_a=akbk_star(1,1,k)'; tmp_b=akbk_star(2,1,k)'; W(:,:,k) = [tmp_a,tmp_b;-tmp_b',tmp_a']; audio_estimate(k,:) = (W(:,:,k)*signal_whitened(:,k)).'; for index=1:Ns % gassian_v1(k,index) = real(1/(1/gassian_v1(k,index)*m_1r_old(index)/m_1r(index)+... % q_s1(index)/m_1r(index)*audio_estimate(k,1)*audio_estimate(k,1)')); % gassian_v2(k,index) = real(1/(1/gassian_v2(k,index)*m_2r_old(index)/m_2r(index)+... % q_s2(index)/m_2r(index)*audio_estimate(k,2)*audio_estimate(k,2)')); if(isnan(gassian_v1(k,index))||isnan(gassian_v2(k,index))) fprintf('7'); return; end end audio_estimate(k,:) = (diag(diag(inv(W(:,:,k)*V(:,:,k))))*audio_estimate(k,:).').'; end for k = floor(fft_length/2+1)+1:fft_length audio_estimate(k,:) = conj(audio_estimate(fft_length-k+2,:)); end estimate_out1((n-1)*shift_size+1:(n-1)*shift_size+window_length)=... ifft(audio_estimate(:,1))+estimate_out1((n-1)*shift_size... +1:(n-1)*shift_size+window_length); estimate_out2((n-1)*shift_size+1:(n-1)*shift_size+window_length)=... ifft(audio_estimate(:,2))+estimate_out2((n-1)*shift_size... +1:(n-1)*shift_size+window_length); %W(:,:,40) if (n>400) cov(test_whitening(:,n-400:n)') end end toc estimate_out1 = estimate_out1/max(abs(estimate_out1)); estimate_out2 = estimate_out2/max(abs(estimate_out2)); contrast_plot(estimate_out1,estimate_out2,expect_sample_rate,'separated'); function contrast_plot(x,y,fs,title_str) figure; subplot(2,1,1); plot((1:length(x))/fs,x,'b'); xlabel('time(s)'); ylabel('relative sound intensity'); title([title_str,'1']); subplot(2,1,2); plot((1:length(y))/fs,y,'b'); title([title_str,'2']); xlabel('time(s)'); ylabel('relative sound intensity'); pause(0); end function p = multi_guassian_calculate(Y,Phi) p = real(log(abs(sqrt(abs(det(Phi)))/2/pi))+((-1/2*Y'*Phi*Y))); end
github
jacky18008/NCCU_Coding_is_Magic-master
eval_multiclass.m
.m
NCCU_Coding_is_Magic-master/UniMiB-SHAR/code/eval_multiclass.m
13,160
utf_8
08f4ba858317dd05be872e7f3b82cb9c
% /************************************************************************************* % % Project Name: UniMiB SHAR: a new dataset for human activity recognition using acceleration data from smartphones % File Name: eval_multiclass.m % Authors: D. Micucci and M. Mobilio and P. Napoletano ([email protected]) % History: October 2016 created % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This function implements the evalaution of the UniMiB SHAR dataset using KNN and SVM. % % USAGE % final_results = eval_multiclass(path,split_path,results_path,data_type,type_eval,classifier_type) % % INPUT % path = accelerometer datapath % split_path = training/test splits datapath % results_path = path of the folder containing the results % data_type = type of accelerometer splits: 'two_classes','acc','adl', % 'fall' % type_eval = 'kfold' or 'subjective' % classifier_type = KNN or SVM % % OUTPUT % final_results - cell [n x 3] containing the SA, MAA, ConfusionMatrix % % function [final_results] = eval_multiclass(path,split_path,results_path,data_type,type_eval,classifier_type) final_results = []; switch type_eval case 'kfold' final_results = kfold_eval(path,split_path,results_path,5,data_type,classifier_type) case 'subjective' final_results = subjective_eval(path,split_path,results_path,data_type,classifier_type) otherwise disp('error typing type of evaluation') end end function final_results = kfold_eval(path,split_path,results_path,num_split,data_type,classifier_type) class_names = [data_type '_names']; data_names_fn = fullfile(path,[class_names '.mat']); load(data_names_fn,class_names) data_name = [data_type '_data']; data_labels = [data_type '_labels']; data_fn = fullfile(path,[data_name '.mat']); labels_fn = fullfile(path,[data_labels '.mat']); load(data_fn,data_name) load(labels_fn,data_labels) loaded_class_names = eval(class_names); loaded_data = eval(data_name); loaded_labels = eval(data_labels); num_classes = size(unique(loaded_labels(:,1)),1); num_subjects = size(unique(loaded_labels(:,2)),1); start = 1:3:size(loaded_data,1); stop = 3:3:size(loaded_data,1); new_data = []; for ii=1:size(start,2) new_data = [new_data; reshape(loaded_data(start(ii):stop(ii),:)',[],size(loaded_data,2)*3)]; end loaded_labels = loaded_labels(start,:); loaded_data = new_data; splitted_data_fn = fullfile(path,split_path,[data_type '_splitted_data' num2str(num_split) '_folds.mat']); train_idxs_fn = fullfile(path,split_path,[data_type '_train_idxs' num2str(num_split) '_folds.mat']); test_idxs_fn = fullfile(path,split_path,[data_type '_test_idxs' num2str(num_split) '_folds.mat']); splitted_data = {}; train_idxs = {}; test_idxs = {}; if((~exist(splitted_data_fn))||(~exist(train_idxs_fn))||(~exist(test_idxs_fn))) for l=1:num_classes class_labels = loaded_labels(:,1) ==l; class_adl_data = loaded_data(class_labels,:); current_prob_class = sum(class_labels); step = floor(current_prob_class/num_split); current_prob_class = step*num_split; start = 1:step:current_prob_class; splitted_data{l,1}=class_adl_data(1:current_prob_class,:); adl_index = randperm(current_prob_class); class_test_idx = []; class_train_idx = []; for ss = 1:size(start,2) current_test_idx = adl_index(start(ss):start(ss)+step-1); class_test_idx = [class_test_idx; current_test_idx]; class_train_idx = [class_train_idx; setdiff(adl_index,current_test_idx)]; end train_idxs{l,1} = class_train_idx; test_idxs{l,1} = class_test_idx; end save(splitted_data_fn,'splitted_data') save(train_idxs_fn,'train_idxs') save(test_idxs_fn,'test_idxs') else load(splitted_data_fn,'splitted_data') load(train_idxs_fn,'train_idxs') load(test_idxs_fn,'test_idxs') end final_results = {}; for eva=1:num_split % eva current_train_data = []; current_test_data = []; current_train_labes = []; current_test_labes = []; for l=1:num_classes current_class_data = splitted_data{l,1}; class_train_idxs = train_idxs{l,1}; current_train_data = [current_train_data; current_class_data(class_train_idxs(eva,:),:)]; class_test_idxs = test_idxs{l,1}; current_test_data = [current_test_data; current_class_data(class_test_idxs(eva,:),:)]; current_train_labes = [current_train_labes; ones(size(class_train_idxs,2),1)*l]; current_test_labes = [current_test_labes; ones(size(class_test_idxs,2),1)*l]; end results_fn = fullfile(path,results_path,['results_' data_type '_' classifier_type '_' num2str(num_split) '_folds.mat']); switch classifier_type case 'svm' SVMModels = cell(num_classes,1); Scores = zeros(size(current_test_data,1),num_classes); fprintf('training split n.%d with svm\n',eva) for j = 1:num_classes; indx = current_train_labes==j; SVMModels{j} = fitcsvm(current_train_data,indx,'Standardize',true,'KernelFunction','RBF',... 'KernelScale','auto'); %SVMModels{j} = crossval(SVMModels{j}); [~,score] = predict(SVMModels{j},current_test_data); Scores(:,j) = score(:,2); end fprintf('testing split n.%d with svm\n',eva) [~,predictions] = max(Scores,[],2); results = predictions ==current_test_labes; class_accuracy = []; for l=1:num_classes true_positives = current_test_labes == l; class_accuracy = [class_accuracy; sum(predictions(true_positives) == l)/size(test_idxs{l,1},2)]; end final_results{eva,1} = (sum(results))/size(current_test_labes,1); final_results{eva,2} = mean(class_accuracy); final_results{eva,3} = confusionmat(current_test_labes,predictions); case 'knn' fprintf('training split n.%d with knn\n',eva) KNNModel = fitcknn(current_train_data,current_train_labes,'NumNeighbors',1); fprintf('testing split n.%d with knn\n',eva) predictions = predict(KNNModel,current_test_data); results = predictions ==current_test_labes; class_accuracy = []; for l=1:num_classes true_positives = current_test_labes == l; class_accuracy = [class_accuracy; sum(predictions(true_positives) == l)/size(test_idxs{l,1},2)]; end final_results{eva,1} = (sum(results))/size(current_test_labes,1); final_results{eva,2} = mean(class_accuracy); final_results{eva,3} = confusionmat(current_test_labes,predictions); otherwise disp('please choose a valid classifier') end end save(results_fn,'final_results') disp('evaluation_completed') end function final_results = subjective_eval(path,split_path,results_path,data_type,classifier_type) class_names = [data_type '_names']; data_names_fn = fullfile(path,[class_names '.mat']); load(data_names_fn,class_names) data_name = [data_type '_data']; data_labels = [data_type '_labels']; data_fn = fullfile(path,[data_name '.mat']); labels_fn = fullfile(path,[data_labels '.mat']); load(data_fn,data_name) load(labels_fn,data_labels) loaded_class_names = eval(class_names); loaded_data = eval(data_name); loaded_labels = eval(data_labels); num_classes = size(unique(loaded_labels(:,1)),1); num_subjects = size(unique(loaded_labels(:,2)),1); start = 1:3:size(loaded_data,1); stop = 3:3:size(loaded_data,1); new_data = []; for ii=1:size(start,2) new_data = [new_data; reshape(loaded_data(start(ii):stop(ii),:)',[],size(loaded_data,2)*3)]; end loaded_labels = loaded_labels(start,:); loaded_data = new_data; splitted_data_fn = fullfile(path,split_path,[data_type '_splitted_data' 'subjective' '_folds.mat']); train_idxs_fn = fullfile(path,split_path,[data_type '_train_idxs' 'subjective' '_folds.mat']); test_idxs_fn = fullfile(path,split_path,[data_type '_test_idxs' 'subjective' '_folds.mat']); splitted_data = {}; train_idxs = {}; test_idxs = {}; if((~exist(splitted_data_fn))||(~exist(train_idxs_fn))||(~exist(test_idxs_fn))) indexes_vector = 1:1:size(loaded_labels,1); for l=1:num_subjects subject_labels = loaded_labels(:,2) ==l; no_subject_labels = ~subject_labels; train_idxs{l,1} = indexes_vector(no_subject_labels)'; test_idxs{l,1} = indexes_vector(subject_labels)'; end save(train_idxs_fn,'train_idxs') save(test_idxs_fn,'test_idxs') else load(train_idxs_fn,'train_idxs') load(test_idxs_fn,'test_idxs') end final_results = {}; for l=1:num_subjects % eva current_train_data = []; current_test_data = []; current_train_labes = []; current_test_labes = []; % for l=1:num_classes class_train_idxs = train_idxs{l,1}; class_test_idxs = test_idxs{l,1}; current_train_data = loaded_data(class_train_idxs,:); current_test_data = loaded_data(class_test_idxs,:); current_train_labes = loaded_labels(class_train_idxs,1); current_test_labes = loaded_labels(class_test_idxs,1); % end %disp('training and testing') results_fn = fullfile(path,results_path,['results_' data_type '_' classifier_type '_subjective.mat']); switch classifier_type case 'svm' SVMModels = cell(num_classes,1); Scores = zeros(size(current_test_data,1),num_classes); fprintf('training split n.%d with svm\n',l) for j = 1:num_classes; indx = current_train_labes==j; % Create binary classes for each classifier SVMModels{j} = fitcsvm(current_train_data,indx,'Standardize',true,'KernelFunction','RBF',... 'KernelScale','auto'); %SVMModels{j} = crossval(SVMModels{j}); [~,score] = predict(SVMModels{j},current_test_data); Scores(:,j) = score(:,2); % Second column contains positive-class scores end fprintf('testing split n.%d with svm\n',l) [~,predictions] = max(Scores,[],2); results = predictions ==current_test_labes; class_accuracy = []; for j=1:num_classes true_positives = current_test_labes == j; class_current_test_labes = sum(true_positives); class_accuracy = [class_accuracy; sum(predictions(true_positives) == j)/class_current_test_labes]; end class_accuracy(isnan(class_accuracy)) = 0; final_results{l,1} = (sum(results))/size(current_test_labes,1); final_results{l,2} = mean(class_accuracy); final_results{l,3} = confusionmat(current_test_labes,predictions); case 'knn' fprintf('training split n.%d with knn\n',l) KNNModel = fitcknn(current_train_data,current_train_labes,'NumNeighbors',1); fprintf('testing split n.%d with knn\n',l) predictions = predict(KNNModel,current_test_data); results = predictions ==current_test_labes; class_accuracy = []; for j=1:num_classes true_positives = current_test_labes == j; class_current_test_labes = sum(true_positives); class_accuracy = [class_accuracy; sum(predictions(true_positives) == j)/class_current_test_labes]; end % if(sum(isnan(class_accuracy))>0) % disp('please choose a valid classifier') % % end class_accuracy(isnan(class_accuracy)) = 0; final_results{l,1} = (sum(results))/size(current_test_labes,1); final_results{l,2} = mean(class_accuracy); final_results{l,3} = confusionmat(current_test_labes,predictions); otherwise disp('please choose a valid classifier') end end save(results_fn,'final_results') disp('evaluation_completed') end
github
KaygoYM/FBMC-channel-estimation-based-on-SVR-master
FBMC_signal.m
.m
FBMC-channel-estimation-based-on-SVR-master/FBMC_signal.m
631
utf_8
5a30487cbebb6691662c236897f61d4d
%author:KAI function [BinaryDataStream_FBMC_Aux,xP_FBMC,x_FBMC_Aux,s_FBMC_Aux]= FBMC_signal(AuxiliaryMethod,FBMC,PAM,ChannelEstimation_FBMC) BinaryDataStream_FBMC_Aux = randi([0 1],AuxiliaryMethod.NrDataSymbols*log2(PAM.ModulationOrder),1); xD_FBMC_Aux = PAM.Bit2Symbol(BinaryDataStream_FBMC_Aux); xP_FBMC = PAM.SymbolMapping(randi(PAM.ModulationOrder,[ChannelEstimation_FBMC.NrPilotSymbols 1])); xP_FBMC = xP_FBMC./abs(xP_FBMC); x_FBMC_Aux = reshape(AuxiliaryMethod.PrecodingMatrix*[xP_FBMC;xD_FBMC_Aux],[FBMC.Nr.Subcarriers FBMC.Nr.MCSymbols]); s_FBMC_Aux = FBMC.Modulation(x_FBMC_Aux); end
github
KaygoYM/FBMC-channel-estimation-based-on-SVR-master
FBMC_data.m
.m
FBMC-channel-estimation-based-on-SVR-master/FBMC_data.m
414
utf_8
85fbcece29580b65dd76cf907f6808e9
%author:KAI function [BinaryDataStream_FBMC_Aux,x_FBMC_Aux,s_FBMC_Aux]= FBMC_data(AuxiliaryMethod,FBMC,PAM) BinaryDataStream_FBMC_Aux = randi([0 1],AuxiliaryMethod.NrTransmittedSymbols*log2(PAM.ModulationOrder),1); xD_FBMC_Aux = PAM.Bit2Symbol(BinaryDataStream_FBMC_Aux); x_FBMC_Aux = reshape(xD_FBMC_Aux,FBMC.Nr.Subcarriers,FBMC.Nr.MCSymbols); s_FBMC_Aux = FBMC.Modulation(x_FBMC_Aux); end
github
KaygoYM/FBMC-channel-estimation-based-on-SVR-master
svminterp_real.m
.m
FBMC-channel-estimation-based-on-SVR-master/svminterp_real.m
393
utf_8
06978ab9d707b8ba097cdc297eb53840
%author:KAI function h_FBMC_Aux = svminterp_real(index,hP_LS_FBMC_Aux,h,NrTime) x=index.'; y=(hP_LS_FBMC_Aux).'; h_FBMC_Aux=nan(size(h)); model=svmtrain(y,x,'-s 3 -t 2 -c 2.2 -g 2.8 -p 0.01'); new_x=(1:NrTime).'; new_x(index)=[]; new_y=h(new_x); [predict_real,mse_real,dec_real]=svmpredict(new_y,new_x,model); h_FBMC_Aux(new_x)=predict_real; h_FBMC_Aux(index)=hP_LS_FBMC_Aux; end
github
KaygoYM/FBMC-channel-estimation-based-on-SVR-master
make.m
.m
FBMC-channel-estimation-based-on-SVR-master/libsvm/matlab/make.m
888
utf_8
4a2ad69e765736f8cca8e3b721fb7ebd
% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix function make() try % This part is for OCTAVE if (exist ('OCTAVE_VERSION', 'builtin')) mex libsvmread.c mex libsvmwrite.c mex -I.. svmtrain.c ../svm.cpp svm_model_matlab.c mex -I.. svmpredict.c ../svm.cpp svm_model_matlab.c % This part is for MATLAB % Add -largeArrayDims on 64-bit machines of MATLAB else mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../svm.cpp svm_model_matlab.c mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../svm.cpp svm_model_matlab.c end catch err fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line); disp(err.message); fprintf('=> Please check README for detailed instructions.\n'); end
github
KaygoYM/FBMC-channel-estimation-based-on-SVR-master
FBMC.m
.m
FBMC-channel-estimation-based-on-SVR-master/+Modulation/FBMC.m
37,528
utf_8
00e25b472f90c845f3f2e1e60aba51c5
classdef FBMC < handle % Ronald Nissel, [email protected] % (c) 2016 by Institute of Telecommunications, TU Wien % www.tc.tuwien.ac.at properties (SetAccess = private) Method Nr PHY PrototypeFilter Implementation end methods %% Class constructor, define default values. function obj = FBMC(varargin) %% Initialize parameters, set default values if numel(varargin)==10 obj.Nr.Subcarriers = varargin{1}; obj.Nr.MCSymbols = varargin{2}; obj.PHY.SubcarrierSpacing = varargin{3}; obj.PHY.SamplingRate = varargin{4}; obj.PHY.IntermediateFrequency = varargin{5}; obj.PHY.TransmitRealSignal = varargin{6}; obj.Method = varargin{7}; obj.PrototypeFilter.OverlappingFactor = varargin{8}; obj.Implementation.InitialPhaseShift = varargin{9}; obj.Implementation.UsePolyphase = varargin{10}; elseif numel(varargin)==0 % Default Values (can later be changed using FBMC.Set...) obj.Nr.Subcarriers = 12; obj.Nr.MCSymbols = 30; obj.PHY.SubcarrierSpacing = 15e3; obj.PHY.SamplingRate = obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing; obj.PHY.IntermediateFrequency = 0; obj.PHY.TransmitRealSignal = false; obj.Method = 'Hermite-OQAM'; obj.PrototypeFilter.OverlappingFactor = 8; obj.Implementation.InitialPhaseShift = 0; obj.Implementation.UsePolyphase = true; else error('Number of input variables must be either 0 (default values) or 10'); end %% Check Parameters if mod(obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing),1)~=0 obj.PHY.SubcarrierSpacing=obj.PHY.SamplingRate/(2*round(obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing))); disp('Sampling Rate divided by (Subcarrier spacing times 2) must be must be an integer!'); disp(['Therefore, the subcarrier spacing is set to: ' int2str(obj.PHY.SubcarrierSpacing) 'Hz']); end if mod(obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing,2)~=0 obj.PHY.IntermediateFrequency = round(obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing)*obj.PHY.SubcarrierSpacing; disp('The intermediate frequency must be a multiple of the subcarrier spacing!'); disp(['Therefore, the intermediate frequency is set to ' int2str(obj.PHY.IntermediateFrequency) 'Hz']); end if (obj.PHY.SamplingRate<obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing) error('Sampling Rate must be higher: at least Number of Subcarriers times Subcarrier Spacing'); end %% Dependent parameters obj.PHY.dt = 1/obj.PHY.SamplingRate; %% Different Prototype Filters and OQAM or QAM switch obj.Method case 'Hermite-OQAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing); obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor; obj.PrototypeFilter.TimeDomain = PrototypeFilter_Hermite(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2); case 'Hermite-QAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2; obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4; obj.PrototypeFilter.TimeDomain = PrototypeFilter_Hermite(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor); case 'Rectangle-QAM' % OFDM without cyclic prefix obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing); obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*2; TimeDomain = zeros(2*obj.PrototypeFilter.OverlappingFactor*obj.Implementation.TimeSpacing,1); TimeDomain(1:obj.Implementation.TimeSpacing) = 1/sqrt(obj.PHY.TimeSpacing); TimeDomain=circshift(TimeDomain,length(TimeDomain)/2-obj.Implementation.TimeSpacing/2); obj.PrototypeFilter.TimeDomain = TimeDomain; case 'RRC-OQAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing); obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor; obj.PrototypeFilter.TimeDomain = PrototypeFilter_RootRaisedCosine(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2); case 'RRC-QAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2; obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4; obj.PrototypeFilter.TimeDomain = PrototypeFilter_RootRaisedCosine(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor); case 'PHYDYAS-OQAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing); obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor; obj.PrototypeFilter.TimeDomain = PrototypeFilter_PHYDYAS(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2); case 'PHYDYAS-QAM' obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2; obj.PHY.TimeSpacing =obj.Implementation.TimeSpacing*obj.PHY.dt; obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4; obj.PrototypeFilter.TimeDomain = PrototypeFilter_PHYDYAS(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor); otherwise error(['Method (prototype filter) "' obj.Method '" is not supported']); end obj.Nr.SamplesPrototypeFilter = length(obj.PrototypeFilter.TimeDomain); obj.Nr.SamplesTotal = obj.Nr.SamplesPrototypeFilter+(obj.Nr.MCSymbols-1)*obj.Implementation.TimeSpacing; % We assume a symmetric filter (=> real) and set small values to zero (=> lower computational complexity) PrototypefilterFFT = obj.PHY.dt*real(fft(circshift(obj.PrototypeFilter.TimeDomain,obj.Nr.SamplesPrototypeFilter/2))); PrototypefilterFFT = obj.PHY.dt*(fft(circshift(obj.PrototypeFilter.TimeDomain,obj.Nr.SamplesPrototypeFilter/2))); PrototypefilterFFT(abs(PrototypefilterFFT)./PrototypefilterFFT(1)<10^-14)=0; obj.PrototypeFilter.FrequencyDomain = PrototypefilterFFT; % Prepare paramters for an efficient implementation % Phase shift to guarentee that the interference is purely imaginary [k,l]=meshgrid(0:obj.Nr.MCSymbols-1,0:obj.Nr.Subcarriers-1); obj.Implementation.PhaseShift = exp(1j*pi/2*(l+k))*exp(1j*obj.Implementation.InitialPhaseShift); % index for the time shift of different FBMC symbols IndexAfterIFFT =[ones(obj.Nr.SamplesPrototypeFilter,obj.Nr.MCSymbols);zeros(obj.Implementation.TimeSpacing*(obj.Nr.MCSymbols-1),obj.Nr.MCSymbols)]; for i_k = 1:obj.Nr.MCSymbols IndexAfterIFFT(:,i_k) = circshift(IndexAfterIFFT(:,i_k),(i_k-1)*obj.Implementation.TimeSpacing); end obj.Implementation.IndexAfterIFFT = logical(IndexAfterIFFT); % index for the polyphase implementation obj.Implementation.IndexPolyphaseMap = logical(circshift([ones(obj.Nr.Subcarriers,obj.Nr.MCSymbols);... zeros(obj.Nr.SamplesPrototypeFilter./obj.Implementation.FrequencySpacing-obj.Nr.Subcarriers,obj.Nr.MCSymbols)],... [obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing 1])); % Normalization factor so that the default power = 1 obj.Implementation.NormalizationFactor = sqrt(obj.PHY.SamplingRate^2/obj.PHY.SubcarrierSpacing^2*obj.PHY.TimeSpacing/obj.Nr.Subcarriers); end %% Set Functions function SetNrSubcarriers(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.Nr.Subcarriers = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetNrMCSymbols(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.Nr.MCSymbols = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetSubcarrierSpacing(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.PHY.SubcarrierSpacing = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetSamplingRate(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.PHY.SamplingRate = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetIntermediateFrequency(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.PHY.IntermediateFrequency = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetTransmitRealSignal(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.PHY.TransmitRealSignal = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetMethod(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.Method = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetOverlappingFactor(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.PrototypeFilter.OverlappingFactor = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetInitialPhaseShift(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.Implementation.InitialPhaseShift = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function SetUsePolyphase(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; obj.Implementation.UsePolyphase = varargin{2}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); obj.Method = NEWobj.Method; obj.Nr = NEWobj.Nr; obj.PHY = NEWobj.PHY; obj.PrototypeFilter = NEWobj.PrototypeFilter; obj.Implementation = NEWobj.Implementation; end function NEWobj = Copy(varargin) % This is a very sloppy implementation :/ obj = varargin{1}; NEWobj = Modulation.FBMC(obj.Nr.Subcarriers,obj.Nr.MCSymbols,obj.PHY.SubcarrierSpacing,obj.PHY.SamplingRate,obj.PHY.IntermediateFrequency,obj.PHY.TransmitRealSignal,obj.Method,obj.PrototypeFilter.OverlappingFactor,obj.Implementation.InitialPhaseShift,obj.Implementation.UsePolyphase); end %% Modulation and Demodulation function TransmitSignal = Modulation(varargin) %asdf obj = varargin{1}; DataSymbols = varargin{2}; TransmitSignal = zeros(size(obj.Implementation.IndexAfterIFFT)); if obj.Implementation.UsePolyphase DataSymbolsTemp = zeros(size(obj.Implementation.IndexPolyphaseMap)); DataSymbolsTemp(obj.Implementation.IndexPolyphaseMap) = DataSymbols.*obj.Implementation.PhaseShift.*obj.Implementation.NormalizationFactor; if obj.PHY.TransmitRealSignal DataSymbolsTemp = (DataSymbolsTemp+conj(DataSymbolsTemp([1 end:-1:2],:)))/sqrt(2); end TransmitSignal(obj.Implementation.IndexAfterIFFT) = repmat(ifft(DataSymbolsTemp),[obj.Implementation.FrequencySpacing 1]).*repmat(obj.PrototypeFilter.TimeDomain,[1 obj.Nr.MCSymbols]); TransmitSignal = sum(TransmitSignal,2); else % Include also the design in the frequency domain because it provides a better understanding of FBMC, but is less efficient! % Note that this matrix could be precomputed! FrequencyGeneration = zeros(size(obj.PrototypeFilter.FrequencyDomain,1),obj.Nr.Subcarriers); for i_l=1:obj.Nr.Subcarriers FrequencyGeneration(:,i_l) = circshift(obj.PrototypeFilter.FrequencyDomain, obj.Implementation.FrequencySpacing*(i_l-1+obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing)); end % normalized to have power 1 FrequencyGeneration = FrequencyGeneration*sqrt(1/obj.Nr.Subcarriers*obj.PHY.TimeSpacing)*obj.PHY.SamplingRate; FrequencyDomain = FrequencyGeneration*(DataSymbols.*obj.Implementation.PhaseShift); if obj.PHY.TransmitRealSignal FrequencyDomain = (FrequencyDomain+conj(FrequencyDomain([1 end:-1:2],:)))/sqrt(2); end TransmitSignal(obj.Implementation.IndexAfterIFFT) = circshift(ifft(FrequencyDomain),[-obj.Nr.SamplesPrototypeFilter/2 0]); TransmitSignal = sum(TransmitSignal,2); end end function ReceivedSymbols = Demodulation(varargin) obj = varargin{1}; ReceivedSignal = varargin{2}; ReceivedSignal_Repeated = repmat(ReceivedSignal,[1 obj.Nr.MCSymbols]); ReceivedSignal_CorrespondingSamplesToFBMCSymbol = reshape(ReceivedSignal_Repeated(obj.Implementation.IndexAfterIFFT),[obj.Nr.SamplesPrototypeFilter obj.Nr.MCSymbols]); if obj.Implementation.UsePolyphase % similar to the transmitter, just in reversed order FilteredReceivedSignal = ReceivedSignal_CorrespondingSamplesToFBMCSymbol.*repmat(obj.PrototypeFilter.TimeDomain,[1 obj.Nr.MCSymbols]); ReceivedSymbolsTemp = fft(sum(reshape(FilteredReceivedSignal,[size(obj.Implementation.IndexPolyphaseMap,1) obj.Implementation.FrequencySpacing obj.Nr.MCSymbols]),2)); if obj.PHY.TransmitRealSignal % ReceivedSymbolsTemp = (ReceivedSymbolsTemp+conj(ReceivedSymbolsTemp([1 end:-1:2],1,:)))/(2); ReceivedSymbolsTemp = ReceivedSymbolsTemp *sqrt(2); end ReceivedSymbols = reshape(ReceivedSymbolsTemp(obj.Implementation.IndexPolyphaseMap),size(obj.Implementation.PhaseShift)).*conj(obj.Implementation.PhaseShift)/(obj.Implementation.NormalizationFactor*obj.PHY.SubcarrierSpacing); else % same as before FrequencyGeneration = zeros(size(obj.PrototypeFilter.FrequencyDomain,1),obj.Nr.Subcarriers); for i_l=1:obj.Nr.Subcarriers FrequencyGeneration(:,i_l) = circshift(obj.PrototypeFilter.FrequencyDomain, obj.Implementation.FrequencySpacing*(i_l-1+obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing)); end % normalized to have power 1 FrequencyGeneration = FrequencyGeneration*sqrt(1/obj.Nr.Subcarriers*obj.PHY.TimeSpacing)*obj.PHY.SamplingRate; FrequencyDomain = fft(circshift(ReceivedSignal_CorrespondingSamplesToFBMCSymbol,[obj.Nr.SamplesPrototypeFilter/2 0])); ReceivedSymbols = (FrequencyGeneration'*FrequencyDomain).*conj(obj.Implementation.PhaseShift)*(obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing)/(obj.PHY.SamplingRate^2*obj.PHY.TimeSpacing*obj.Implementation.FrequencySpacing); end end %% Matrix Description function TXMatrix = GetTXMatrix(obj) TransmitRealSignal=false; if obj.PHY.TransmitRealSignal obj.PHY.TransmitRealSignal = false; TransmitRealSignal=true; end TXMatrix=zeros(obj.Nr.SamplesTotal,obj.Nr.Subcarriers*obj.Nr.MCSymbols); TXMatrixTemp=zeros(obj.Nr.SamplesTotal,obj.Nr.Subcarriers); x = zeros(obj.Nr.Subcarriers, obj.Nr.MCSymbols); for i_l= 1:obj.Nr.Subcarriers; x(i_l)=1; TXMatrixTemp(:,i_l) = obj.Modulation(x); x(i_l)=0; end for i_k=1:obj.Nr.MCSymbols TXMatrix(:,(1:obj.Nr.Subcarriers)+(i_k-1)*obj.Nr.Subcarriers)=circshift(TXMatrixTemp,[(i_k-1)*obj.Implementation.TimeSpacing,0])*1j^(i_k-1); end if TransmitRealSignal obj.PHY.TransmitRealSignal = true; TXMatrix = real(TXMatrix)*sqrt(2); end end function RXMatrix = GetRXMatrix(obj) if obj.PHY.TransmitRealSignal obj.PHY.TransmitRealSignal = false; RXMatrix = sqrt(2)*obj.GetTXMatrix'*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing)); obj.PHY.TransmitRealSignal = true; else RXMatrix = obj.GetTXMatrix'*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing)); end end function FBMCMatrix = GetFBMCMatrix(varargin) obj = varargin{1}; if numel(varargin)>=2 FastCalculation = varargin{2}; else FastCalculation = true; end if FastCalculation % Small Bug InterferenceMatrix = obj.GetInterferenceMatrix; [Symbol_i,Subcarrier_i] = meshgrid(1:obj.Nr.MCSymbols,1:obj.Nr.Subcarriers); LK = obj.Nr.Subcarriers*obj.Nr.MCSymbols; Index_DeltaSubcarrier = repmat(Subcarrier_i(:),1,LK)-repmat(Subcarrier_i(:)',LK,1); Index_DeltaSymbols = repmat(Symbol_i(:),1,LK)-repmat(Symbol_i(:)',LK,1); Index_Subcarrier = repmat(Subcarrier_i(:),1,LK)-1; FBMCMatrix=reshape(InterferenceMatrix(Index_DeltaSubcarrier(:)+obj.Nr.Subcarriers+(Index_DeltaSymbols(:)+obj.Nr.MCSymbols-1)*size(InterferenceMatrix,1)),LK,LK); if obj.Method(end-3)=='-' % QAM, works only for an odd number of subcarriers, needs to be fixed! Hower it does not really matter because values are small! FBMCMatrix=FBMCMatrix.*exp(-1j*pi/2*(Index_DeltaSubcarrier+Index_DeltaSymbols)).*exp(-1j*pi*3/2*Index_DeltaSymbols.*Index_DeltaSubcarrier); else % OQAM, this works FBMCMatrix=FBMCMatrix.*exp(-1j*pi/2*(Index_DeltaSubcarrier+Index_DeltaSymbols)).*exp(-1j*2*pi*(obj.PHY.TimeSpacing*obj.PHY.SubcarrierSpacing)*Index_DeltaSymbols.*(Index_Subcarrier+Index_DeltaSubcarrier/2)); end else % straightforward slow implementation FBMCMatrix = zeros(obj.Nr.Subcarriers*obj.Nr.MCSymbols); DataImpulse=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); for i_lk=1:obj.Nr.Subcarriers*obj.Nr.MCSymbols DataImpulse(i_lk)=1; FBMCMatrix(:,i_lk) = reshape(obj.Demodulation(obj.Modulation(DataImpulse)),[],1); DataImpulse(i_lk)=0; end end end function InterferenceMatrix = GetInterferenceMatrix(obj) [k_all,l_all] = meshgrid(0:obj.Nr.MCSymbols-1,0:obj.Nr.Subcarriers-1); l=0; k=0; DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(l+1,k+1)=1; Y11=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); dl = l_all-l; dk = k_all-k; Y11=Y11.*(exp(1j*pi/2*(dl+dk)).*exp(-1j*pi*dk.*(l+dl/2))); DataSymbols(l+1,k+1)=0; l=obj.Nr.Subcarriers-1; k=0; DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(l+1,k+1)=1; YE1=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); dl = l_all-l; dk = k_all-k; YE1=YE1.*(exp(1j*pi/2*(dl+dk)).*exp(-1j*pi*dk.*(l+dl/2))); DataSymbols(l+1,k+1)=0; l=0; k=obj.Nr.MCSymbols-1; DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(l+1,k+1)=1; Y1E=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); dl = l_all-l; dk = k_all-k; Y1E=Y1E.*(exp(1j*pi/2*(dl+dk)).*exp(-1j*pi*dk.*(l+dl/2))); DataSymbols(l+1,k+1)=0; l=obj.Nr.Subcarriers-1; k=obj.Nr.MCSymbols-1; DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(l+1,k+1)=1; YEE=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); dl = l_all-l; dk = k_all-k; YEE=YEE.*(exp(1j*pi/2*(dl+dk)).*exp(-1j*pi*dk.*(l+dl/2))); InterferenceMatrix = [YEE(1:end-1,1:end),YE1(1:end-1,2:end);Y1E(1:end,1:end-1),Y11(1:end,1:end)]; end function InterferenceMatrix = GetInterferenceMatrix2(obj) DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(1,1)=1; Y11=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); [k_all,l_all] = meshgrid(0:obj.Nr.MCSymbols-1,0:obj.Nr.Subcarriers-1); Y11=Y11.*(exp(1j*pi/2*(l_all+k_all)).*exp(-1j*pi*k_all.*(l_all/2))); InterferenceMatrix = [Y11(end:-1:2,end:-1:2),Y11(end:-1:2,1:end);Y11(:,end:-1:2),Y11(1:end,1:end)]; end %% Plot function [TransmitPower,Time]=PlotTransmitPower(varargin) obj = varargin{1}; if numel(varargin)==2 [V,D] = eig(varargin{2}); else V = eye(obj.Nr.Subcarriers*obj.Nr.MCSymbols); D = V; end D=sqrt(D); TransmitPower = zeros(obj.Nr.SamplesTotal,1); for i_lk = 1:obj.Nr.Subcarriers*obj.Nr.MCSymbols TransmitPower = TransmitPower+abs(obj.Modulation(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols))*D(i_lk,i_lk)).^2; if mod(i_lk,1000)==0 disp([int2str(i_lk/(obj.Nr.Subcarriers*obj.Nr.MCSymbols )*100) '%']); end end Time = (0:length(TransmitPower)-1)*obj.PHY.dt; if nargout==0 plot(Time,TransmitPower); ylabel('Transmit Power'); xlabel('Time(s)'); end end function [PowerSpectralDensity,Frequency] = PlotPowerSpectralDensity(varargin) obj = varargin{1}; if numel(varargin)==2 [V,D] = eig(varargin{2}); else V = eye(obj.Nr.Subcarriers*obj.Nr.MCSymbols); D = V; end D=sqrt(D); PowerSpectralDensity = zeros(obj.Nr.SamplesTotal,1); for i_lk = 1:obj.Nr.Subcarriers*obj.Nr.MCSymbols PowerSpectralDensity = PowerSpectralDensity+abs(fft(obj.Modulation(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols))*D(i_lk,i_lk))).^2; if mod(i_lk,1000)==0 disp([int2str(i_lk/(obj.Nr.Subcarriers*obj.Nr.MCSymbols )*100) '%']); end end Frequency = (0:length(PowerSpectralDensity)-1)*1/(length(PowerSpectralDensity)*obj.PHY.dt); PowerSpectralDensity=PowerSpectralDensity/length(PowerSpectralDensity)^2/Frequency(2)^2; if nargout==0 plot(Frequency,10*log10(PowerSpectralDensity)); ylabel('Power Spectral Density (dB)'); xlabel('Frequency (Hz)'); end end function [PowerSpectralDensity,Frequency] = PlotPowerSpectralDensity2(varargin) obj = varargin{1}; if numel(varargin)==2 [V,D] = eig(varargin{2}); else V = eye(obj.Nr.Subcarriers*obj.Nr.MCSymbols); D = V; end FrequencyGeneration = zeros(size(obj.PrototypeFilter.FrequencyDomain,1),obj.Nr.Subcarriers); for i_l=1:obj.Nr.Subcarriers FrequencyGeneration(:,i_l) = circshift(obj.PrototypeFilter.FrequencyDomain, obj.Implementation.FrequencySpacing*(i_l-1+obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing)); end FrequencyGeneration = FrequencyGeneration*sqrt(1/obj.Nr.Subcarriers*obj.PHY.TimeSpacing)*obj.PHY.SamplingRate; D=sqrt(D); PowerSpectralDensity = zeros(obj.Nr.SamplesTotal,1); for i_lk = 1:obj.Nr.Subcarriers*obj.Nr.MCSymbols PowerSpectralDensity = PowerSpectralDensity+abs(fft(obj.Modulation(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols))*D(i_lk,i_lk))).^2; FrequencyDomain = FrequencyGeneration*(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols).*obj.Implementation.PhaseShift); if obj.PHY.TransmitRealSignal FrequencyDomain = (FrequencyDomain+conj(FrequencyDomain([1 end:-1:2],:)))/sqrt(2); end TransmitSignal(obj.Implementation.IndexAfterIFFT) = circshift(ifft(FrequencyDomain),[-obj.Nr.SamplesPrototypeFilter/2 0]); TransmitSignal = sum(TransmitSignal,2); if mod(i_lk,1000)==0 disp([int2str(i_lk/(obj.Nr.Subcarriers*obj.Nr.MCSymbols )*100) '%']); end end Frequency = (0:length(PowerSpectralDensity)-1)*1/(length(PowerSpectralDensity)*obj.PHY.dt); PowerSpectralDensity=PowerSpectralDensity/length(PowerSpectralDensity)^2/Frequency(2)^2; if nargout==0 plot(Frequency,10*log10(PowerSpectralDensity)); ylabel('Power Spectral Density (dB)'); xlabel('Frequency (Hz)'); end end function [PowerSpectralDensity,Frequency] = PlotPowerSpectralDensityUncorrelatedData(varargin) obj = varargin{1}; PowerSpectralDensity = zeros(obj.Nr.SamplesTotal,1); for i_lk = 1:obj.Nr.Subcarriers V = zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); V(i_lk,round(obj.Nr.MCSymbols/2))=1; PowerSpectralDensity = PowerSpectralDensity+abs(fft(obj.Modulation(V))).^2; end Frequency = (0:length(PowerSpectralDensity)-1)*1/(length(PowerSpectralDensity)*obj.PHY.dt); PowerSpectralDensity=obj.Nr.MCSymbols*PowerSpectralDensity/length(PowerSpectralDensity)^2/Frequency(2)^2; if nargout==0 plot(Frequency,10*log10(PowerSpectralDensity)); ylabel('Power Spectral Density'); xlabel('Frequency (Hz)'); end end %% SIR and Noise power function [SIR] = GetSIRdBDoublyFlat(obj) DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols); DataSymbols(ceil(end/2),ceil(end/2))=1; Y=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols); if obj.Method(end-3)=='O' Y = real(Y); end S = abs(Y(ceil(end/2),ceil(end/2))).^2; Y(ceil(end/2),ceil(end/2))=0; I =sum(sum(abs(Y).^2)); SIR = 10*log10(S/I); end function Pn = GetSymbolNoisePower(varargin) obj = varargin{1}; Pn_time = varargin{2}; Pn = (Pn_time*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing))); end end end function PrototypeFilter = PrototypeFilter_Hermite(T0,dt,OF) % The pulse is orthogonal for a time-spacing of T=T_0 and a frequency-spacing of F=2/T_0 % Values taken from: R.Nissel et al. "ON PILOT-SYMBOL AIDED CHANNEL ESTIMATION IN FBMC-OQAM" t_filter=-(OF*T0):dt:(OF*T0-dt); D0=1/sqrt(T0)*HermiteH(0,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2); D4=1/sqrt(T0)*HermiteH(4,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2); D8=1/sqrt(T0)*HermiteH(8,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2); D12=1/sqrt(T0)*HermiteH(12,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2); D16=1/sqrt(T0)*HermiteH(16,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2); D20=1/sqrt(T0)*HermiteH(20,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2); H0= 1.412692577; H4= -3.0145e-3; H8=-8.8041e-6; H12=-2.2611e-9; H16=-4.4570e-15; H20 = 1.8633e-16; PrototypeFilter=(D0.*H0+D4.*H4+D8.*H8+D12.*H12+D16.*H16+D20.*H20).'; PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt); end function PrototypeFilter = PrototypeFilter_RootRaisedCosine(T0,dt,OF) % The pulse is orthogonal for a time-spacing of T=T0 and a frequency-spacing of F=2/T0 t_filter=-(OF*T0):dt:(OF*T0-dt); PrototypeFilter=(1/sqrt(T0)*(4*t_filter/T0.*cos(2*pi*t_filter/T0))./(pi*t_filter/T0.*(1-(4*t_filter/T0).^2))); PrototypeFilter(abs(t_filter)<10^-14) =1/sqrt(T0)*(4/pi); PrototypeFilter(abs(abs(t_filter)-T0/4)<10^-14)=1/sqrt(2*T0)*((1+2/pi)*sin(pi/4)+(1-2/pi)*cos(pi/4)); PrototypeFilter=PrototypeFilter.'; PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt); % Set to zero so that out of band emmision is reduced (but SIR is worse) % PrototypeFilter(1:T0/dt/4+1)=PrototypeFilter(1:T0/dt/4+1).*linspace(0,1,(T0/dt/4+1))'; % PrototypeFilter((end-T0/dt/4):end)=PrototypeFilter((end-T0/dt/4):end).*linspace(1,0,(T0/dt/4+1))'; % Test % PrototypeFilterFrequency = zeros(size(t_filter)); % PrototypeFilterFrequency(1:(length(t_filter)*dt)/T0*2) = cos(pi*linspace(-0.5,0.5,(length(t_filter)*dt)/T0*2)); % PrototypeFilter=ifft((circshift(PrototypeFilterFrequency.',-(length(t_filter)*dt)/T0))); % PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt); end function PrototypeFilter = PrototypeFilter_PHYDYAS(T0,dt,OF) % The pulse is orthogonal for a time-spacing of T=T0 and a frequency-spacing of F=2/T0 t_filter=-(OF*T0):dt:(OF*T0-dt); switch OF*2 case 2 H= [sqrt(2)/2]; case 3 H = [0.91143783 0.41143783]; case 4 H = [0.97195983 sqrt(2)/2 0.23514695]; case 5 H = [0.99184131 0.86541624 0.50105361 0.12747868]; case 6 H = [0.99818572 0.94838678 sqrt(2)/2 0.31711593 0.06021021]; case 7 H = [0.99938080 0.97838560 0.84390076 0.53649931 0.20678881 0.03518546]; case 8 H = [0.99932588 0.98203168 0.89425129 sqrt(2)/2 0.44756522 0.18871614 0.03671221]; otherwise error('Oversampling factor must be an integer between 1 and 8 for OQAM or betwen 1 and 4 for QAM'); end PrototypeFilter = 1+2*sum(repmat(H,length(t_filter),1).*cos(2*pi*repmat(t_filter',1,length(H)).*repmat(1:length(H),length(t_filter),1)/((length(H)+1)*T0)),2); PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt); end %% Hermite polynomials (obtained by Mathematica, "ToMatlab[HermiteH[n, x]]") function Hermite = HermiteH(n,x) if n==0 Hermite=ones(size(x)); elseif n==4 Hermite=12+(-48).*x.^2+16.*x.^4; elseif n==8 Hermite = 1680+(-13440).*x.^2+13440.*x.^4+(-3584).*x.^6+256.*x.^8; elseif n==12 Hermite = 665280+(-7983360).*x.^2+13305600.*x.^4+(-7096320).*x.^6+1520640.* ... x.^8+(-135168).*x.^10+4096.*x.^12; elseif n==16 Hermite = 518918400+(-8302694400).*x.^2+19372953600.*x.^4+(-15498362880).* ... x.^6+5535129600.*x.^8+(-984023040).*x.^10+89456640.*x.^12+( ... -3932160).*x.^14+65536.*x.^16; elseif n==20 Hermite = 670442572800+(-13408851456000).*x.^2+40226554368000.*x.^4+( ... -42908324659200).*x.^6+21454162329600.*x.^8+(-5721109954560).* ... x.^10+866834841600.*x.^12+(-76205260800).*x.^14+3810263040.*x.^16+ ... (-99614720).*x.^18+1048576.*x.^20; end end
github
DrNickDMartin/VehicleDynamics-master
optimplotfval2.m
.m
VehicleDynamics-master/tyres/MF_Tire_GUI_V2a/optimplotfval2.m
3,179
utf_8
e633e336e1fff27a799afa1f818057eb
function stop = optimplotfval(~,optimValues,state,varargin) % OPTIMPLOTFVAL Plot value of the objective function at each iteration. % % STOP = OPTIMPLOTFVAL(X,OPTIMVALUES,STATE) plots OPTIMVALUES.fval. If % the function value is not scalar, a bar plot of the elements at the % current iteration is displayed. If the OPTIMVALUES.fval field does not % exist, the OPTIMVALUES.residual field is used. % % Example: % Create an options structure that will use OPTIMPLOTFVAL as the plot % function % options = optimset('PlotFcns',@optimplotfval); % % Pass the options into an optimization problem to view the plot % fminbnd(@sin,3,10,options) % Copyright 2006-2010 The MathWorks, Inc. % $Revision: 1.1.6.2 $ $Date: 2012/08/21 00:30:41 $ stop = false; switch state case 'iter' if isfield(optimValues,'fval') if isscalar(optimValues.fval) plotscalar(optimValues.iteration,optimValues.fval); else plotvector(optimValues.iteration,optimValues.fval); end else plotvector(optimValues.iteration,optimValues.residual); end end function plotscalar(iteration,fval) % PLOTSCALAR initializes or updates a line plot of the function value % at each iteration. if iteration == 0 axes(findobj(gcf,'Tag','Fval_axes')) plotfval = plot(iteration,fval,'b.'); title(getString(message('MATLAB:funfun:optimplots:TitleCurrentFunctionValue',sprintf('%g',fval))),'interp','none'); xlabel(getString(message('MATLAB:funfun:optimplots:LabelIteration')),'interp','none'); set(plotfval,'Tag','optimplotfval'); ylabel(getString(message('MATLAB:funfun:optimplots:LabelFunctionValue')),'interp','none') else allaxes = findall(gcf,'type','axes'); plotfval= get(allaxes(2),'Children'); newX = [get(plotfval,'Xdata') iteration]; newY = [get(plotfval,'Ydata') fval]; set(plotfval,'Xdata',newX, 'Ydata',newY); set(get(gca,'Title'),'String',getString(message('MATLAB:funfun:optimplots:TitleCurrentFunctionValue',sprintf('%g',fval)))); end function plotvector(iteration,fval) % PLOTVECTOR creates or updates a bar plot of the function values or % residuals at the current iteration. if iteration == 0 xlabelText = getString(message('MATLAB:funfun:optimplots:LabelNumberOfFunctionValues0',sprintf('%g',length(fval)))); % display up to the first 100 values if numel(fval) > 100 xlabelText = {xlabelText,getString(message('MATLAB:funfun:optimplots:LabelShowingOnlyFirst100Values'))}; fval = fval(1:100); end plotfval = bar(fval); title(getString(message('MATLAB:funfun:optimplots:TitleCurrentFunctionValues')),'interp','none'); set(plotfval,'edgecolor','none') set(gca,'xlim',[0,1 + length(fval)]) xlabel(xlabelText,'interp','none') set(plotfval,'Tag','optimplotfval'); ylabel(getString(message('MATLAB:funfun:optimplots:LabelFunctionValue')),'interp','none') else plotfval = findobj(get(gca,'Children'),'Tag','optimplotfval'); % display up to the first 100 values if numel(fval) > 100 fval = fval(1:100); end set(plotfval,'Ydata',fval); end
github
DrNickDMartin/VehicleDynamics-master
MF_Tire_GUI_V2a.m
.m
VehicleDynamics-master/tyres/MF_Tire_GUI_V2a/MF_Tire_GUI_V2a.m
42,176
utf_8
083e33679131da8156761186600a9c74
function varargout = MF_Tire_GUI_V2a(varargin) % MF_Tire_GUI_V2a MATLAB code for MF_Tire_GUI_V2a.fig % MF_Tire_GUI_V2a, by itself, creates a new MF_Tire_GUI_V2a or raises the existing % singleton*. % % H = MF_Tire_GUI_V2a returns the handle to a new MF_Tire_GUI_V2a or the handle to % the existing singleton*. % % MF_Tire_GUI_V2a('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MF_Tire_GUI_V2a.M with the given input arguments. % % MF_Tire_GUI_V2a('Property','Value',...) creates a new MF_Tire_GUI_V2a or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before MF_Tire_GUI_V2a_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to MF_Tire_GUI_V2a_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help MF_Tire_GUI_V2a % Last Modified by GUIDE v2.5 26-Aug-2015 11:38:11 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @MF_Tire_GUI_V2a_OpeningFcn, ... 'gui_OutputFcn', @MF_Tire_GUI_V2a_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before MF_Tire_GUI_V2a is made visible. function MF_Tire_GUI_V2a_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to MF_Tire_GUI_V2a (see VARARGIN) % Choose default command line output for MF_Tire_GUI_V2a handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes MF_Tire_GUI_V2a wait for user response (see UIRESUME) % uiwait(handles.figure1); load([pwd '\MF52_par0.mat']) handles.Start_MF52Par= [Pcx1 Pdx1 Pdx2 Pex1 Pex2 Pex3 Pex4 Pkx1 Pkx2 Pkx3 Phx1 Phx2 Pvx1 Pvx2]; guidata(hObject,handles); % --- Outputs from this function are returned to the command line. function varargout = MF_Tire_GUI_V2a_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function Pcx1_slider_Callback(hObject, eventdata, handles) % hObject handle to Pcx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pcx1_slider,'value')); set(handles.Text_Pcx1,'String',a); % --- Executes during object creation, after setting all properties. function Pcx1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pcx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on button press in Plot_Button. function Plot_Button_Callback(hObject, eventdata, handles) % hObject handle to Plot_Button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) Pac_MF52=get(handles.MF52_checkbox,'value'); Pac_96=get(handles.Pac96_checkbox,'value'); hold_on=get(handles.hold_checkbox,'value'); if (Pac_MF52+Pac_96==0) error('Please Choose one of the two Pacejka Models'); set(handles.Error_text,'String','Error: Please Choose one of the two Pacejka Models'); else set(handles.Error_text,'String',''); NominalForce=1125.65; %get variables from Edit Text boxes NormalForce=str2num(get(handles.NormalForce_editT,'string')); slipStart=str2num(get(handles.SlpStart_editT,'string'))/100; slipEnd=str2num(get(handles.SlpEnd_editT,'string'))/100; %get variables from Slider widgets Pcx1=get(handles.Pcx1_slider,'value'); Pdx1=get(handles.Pdx1_slider,'value'); Pdx2=get(handles.Pdx2_slider,'value'); Pex1=get(handles.Pex1_slider,'value'); Pex2=get(handles.Pex2_slider,'value'); Pex3=get(handles.Pex3_slider,'value'); Pex4=get(handles.Pex4_slider,'value'); Pkx1=get(handles.Pkx1_slider,'value'); Pkx2=get(handles.Pkx2_slider,'value'); Pkx3=get(handles.Pkx3_slider,'value'); Phx1=get(handles.Phx1_slider,'value'); Phx2=get(handles.Phx2_slider,'value'); Pvx1=get(handles.Pvx1_slider,'value'); Pvx2=get(handles.Pvx2_slider,'value'); MF_par= [Pcx1 Pdx1 Pdx2 Pex1 Pex2 Pex3 Pex4 Pkx1 Pkx2 Pkx3 Phx1 Phx2 Pvx1 Pvx2]; K= slipStart:0.02:slipEnd; if Pac_MF52==1 Shx=(Phx1 + Phx2 *(NormalForce/10000))*1; Kx= K*100+ Shx; [Fx0,MF_macro_par]= MF52_LongForce_calc(MF_par,Kx,NormalForce); slp4plot= Kx/100; handles.Current_TP_Design= MF_par; guidata(hObject,handles); else dfz=(NormalForce-NominalForce)/NominalForce; Shx=(Phx1 + Phx2 *dfz)*1; Kx= K+ Shx; [Fx0,MF_macro_par]= MF1996_LongForce_calc(MF_par,Kx,NormalForce,NominalForce); slp4plot= Kx; handles.Current_TP_Design= []; guidata(hObject,handles); end handles.figure1; plot(slp4plot,Fx0); grid on; ylabel('Longitudinal Force Fx (N)'); xlabel('Slip Ratio '); if hold_on hold on; else hold off; end set(handles.IstCx_text,'String',num2str(MF_macro_par.Cx)); set(handles.IstDx_text,'String',num2str(MF_macro_par.Dx)); set(handles.IstEx_text,'String',num2str(MF_macro_par.Ex)); set(handles.IstBx_text,'String',num2str(MF_macro_par.Bx)); end % --- Executes on button press in Debug_button. function Debug_button_Callback(hObject, eventdata, handles) % hObject handle to Debug_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) keyboard; function SlpStart_editT_Callback(hObject, eventdata, handles) % hObject handle to SlpStart_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of SlpStart_editT as text % str2double(get(hObject,'String')) returns contents of SlpStart_editT as a double % --- Executes during object creation, after setting all properties. function SlpStart_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to SlpStart_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function SlpEnd_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to SlpEnd_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function NormalForce_editT_Callback(hObject, eventdata, handles) % hObject handle to NormalForce_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of NormalForce_editT as text % str2double(get(hObject,'String')) returns contents of NormalForce_editT as a double % --- Executes during object creation, after setting all properties. function NormalForce_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to NormalForce_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function Pex2_slider_Callback(hObject, eventdata, handles) % hObject handle to Pex2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pex2_slider,'value')); set(handles.Text_Pex2,'String',a); % --- Executes during object creation, after setting all properties. function Pex2_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pex2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pex1_slider_Callback(hObject, eventdata, handles) % hObject handle to Pex1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pex1_slider,'value')); set(handles.Text_Pex1,'String',a); % --- Executes during object creation, after setting all properties. function Pex1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pex1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pex3_slider_Callback(hObject, eventdata, handles) % hObject handle to Pex3_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pex3_slider,'value')); set(handles.Text_Pex3,'String',a); % --- Executes during object creation, after setting all properties. function Pex3_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pex3_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pdx2_slider_Callback(hObject, eventdata, handles) % hObject handle to Pdx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pdx2_slider,'value')); set(handles.Text_Pdx2,'String',a); % --- Executes during object creation, after setting all properties. function Pdx2_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pdx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pkx1_slider_Callback(hObject, eventdata, handles) % hObject handle to Pkx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pkx1_slider,'value')); set(handles.Text_Pkx1,'String',a); % --- Executes during object creation, after setting all properties. function Pkx1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pkx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pkx2_slider_Callback(hObject, eventdata, handles) % hObject handle to Pkx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pkx2_slider,'value')); set(handles.Text_Pkx2,'String',a); % --- Executes during object creation, after setting all properties. function Pkx2_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pkx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pkx3_slider_Callback(hObject, eventdata, handles) % hObject handle to Pkx3_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pkx3_slider,'value')); set(handles.Text_Pkx3,'String',a); % --- Executes during object creation, after setting all properties. function Pkx3_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pkx3_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Phx1_slider_Callback(hObject, eventdata, handles) % hObject handle to Phx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Phx1_slider,'value')); set(handles.Text_Phx1,'String',a); % --- Executes during object creation, after setting all properties. function Phx1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Phx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Phx2_slider_Callback(hObject, eventdata, handles) % hObject handle to Phx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Phx2_slider,'value')); set(handles.Text_Phx2,'String',a); % --- Executes during object creation, after setting all properties. function Phx2_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Phx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pvx1_slider_Callback(hObject, eventdata, handles) % hObject handle to Pvx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pvx1_slider,'value')); set(handles.Text_Pvx1,'String',a); % --- Executes during object creation, after setting all properties. function Pvx1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pvx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pdx1_slider_Callback(hObject, eventdata, handles) % hObject handle to Pdx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pdx1_slider,'value')); set(handles.Text_Pdx1,'String',a); % --- Executes during object creation, after setting all properties. function Pdx1_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pdx1_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pvx2_slider_Callback(hObject, eventdata, handles) % hObject handle to Pvx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pvx2_slider,'value')); set(handles.Text_Pvx2,'String',a); % --- Executes during object creation, after setting all properties. function Pvx2_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pvx2_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function Pex4_slider_Callback(hObject, eventdata, handles) % hObject handle to Pex4_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a=num2str(get(handles.Pex4_slider,'value')); set(handles.Text_Pex4,'String',a); % --- Executes during object creation, after setting all properties. function Pex4_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to Pex4_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function Cx_editT_Callback(hObject, eventdata, handles) % hObject handle to Cx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Cx_editT as text % str2double(get(hObject,'String')) returns contents of Cx_editT as a double % --- Executes during object creation, after setting all properties. function Cx_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to Cx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Dx_editT_Callback(hObject, eventdata, handles) % hObject handle to Dx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Dx_editT as text % str2double(get(hObject,'String')) returns contents of Dx_editT as a double % --- Executes during object creation, after setting all properties. function Dx_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to Dx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Ex_editT_Callback(hObject, eventdata, handles) % hObject handle to Ex_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Ex_editT as text % str2double(get(hObject,'String')) returns contents of Ex_editT as a double % --- Executes during object creation, after setting all properties. function Ex_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to Ex_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Bx_editT_Callback(hObject, eventdata, handles) % hObject handle to Bx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Bx_editT as text % str2double(get(hObject,'String')) returns contents of Bx_editT as a double % --- Executes during object creation, after setting all properties. function Bx_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to Bx_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in MF52_checkbox. function MF52_checkbox_Callback(hObject, eventdata, handles) % hObject handle to MF52_checkbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of MF52_checkbox set(handles.Pac96_checkbox,'value',0); set(handles.Pcx1_slider,'value',1.5); set(handles.Pex2_slider,'value',0); set(handles.Pex4_slider,'value',0); set(handles.Pkx3_slider,'value',0); set(handles.Phx2_slider,'value',0); set(handles.Pdx1_slider,'max',3000); set(handles.Pdx1_slider,'min',1000); set(handles.Pdx1_slider,'value',2300); a=num2str(get(handles.Pdx1_slider,'value')); set(handles.Text_Pdx1,'String',a); set(handles.Pdx2_slider,'max',80); set(handles.Pdx2_slider,'min',-80); set(handles.Pdx2_slider,'value',-0.256); a=num2str(get(handles.Pdx2_slider,'value')); set(handles.Text_Pdx2,'String',a); set(handles.Pex1_slider,'max',1); set(handles.Pex1_slider,'min',-20); set(handles.Pex1_slider,'value',-2); a=num2str(get(handles.Pex1_slider,'value')); set(handles.Text_Pex1,'String',a); set(handles.Pex3_slider,'max',0.1); set(handles.Pex3_slider,'min',-0.1); set(handles.Pex3_slider,'value',0); a=num2str(get(handles.Pex3_slider,'value')); set(handles.Text_Pex3,'String',a); set(handles.Pkx1_slider,'max',500); set(handles.Pkx1_slider,'min',100); set(handles.Pkx1_slider,'value',300); a=num2str(get(handles.Pkx1_slider,'value')); set(handles.Text_Pkx1,'String',a); set(handles.Pkx2_slider,'max',20); set(handles.Pkx2_slider,'min',-20); set(handles.Pkx2_slider,'value',0); a=num2str(get(handles.Pkx2_slider,'value')); set(handles.Text_Pkx2,'String',a); set(handles.Phx1_slider,'max',5); set(handles.Phx1_slider,'min',-5); set(handles.Phx1_slider,'value',0); a=num2str(get(handles.Phx1_slider,'value')); set(handles.Text_Phx1,'String',a); set(handles.Pvx2_slider,'max',100); set(handles.Pvx2_slider,'min',-100); set(handles.Pvx2_slider,'value',0); a=num2str(get(handles.Pvx2_slider,'value')); set(handles.Text_Pvx2,'String',a); set(handles.Pvx1_slider,'max',10); set(handles.Pvx1_slider,'min',-10); set(handles.Pvx1_slider,'value',0); a=num2str(get(handles.Pvx2_slider,'value')); set(handles.Text_Pvx2,'String',a); handles.figure1; cla; % --- Executes on button press in Pac96_checkbox. function Pac96_checkbox_Callback(hObject, eventdata, handles) % hObject handle to Pac96_checkbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Pac96_checkbox set(handles.MF52_checkbox,'value',0); set(handles.Pcx1_slider,'value',1.5); set(handles.Pex2_slider,'value',-0.36673); set(handles.Pex4_slider,'value',-0.05543); set(handles.Pkx3_slider,'value',-0.45644); set(handles.Phx2_slider,'value',-0.00179); set(handles.Pdx1_slider,'max',4); set(handles.Pdx1_slider,'min',1); set(handles.Pdx1_slider,'value',2.22960); a=num2str(get(handles.Pdx1_slider,'value')); set(handles.Text_Pdx1,'String',a); set(handles.Pdx2_slider,'max',1); set(handles.Pdx2_slider,'min',-1); set(handles.Pdx2_slider,'value',-0.26506); a=num2str(get(handles.Pdx2_slider,'value')); set(handles.Text_Pdx2,'String',a); set(handles.Pex1_slider,'max',1); set(handles.Pex1_slider,'min',-1); set(handles.Pex1_slider,'value',0.34731); a=num2str(get(handles.Pex1_slider,'value')); set(handles.Text_Pex1,'String',a); set(handles.Pex3_slider,'max',1); set(handles.Pex3_slider,'min',-1); set(handles.Pex3_slider,'value',-0.2813); a=num2str(get(handles.Pex3_slider,'value')); set(handles.Text_Pex3,'String',a); set(handles.Pkx1_slider,'max',80); set(handles.Pkx1_slider,'min',-80); set(handles.Pkx1_slider,'value',46.06520); a=num2str(get(handles.Pkx1_slider,'value')); set(handles.Text_Pkx1,'String',a); set(handles.Pkx2_slider,'max',70); set(handles.Pkx2_slider,'min',-70); set(handles.Pkx2_slider,'value',-29.4306); a=num2str(get(handles.Pkx2_slider,'value')); set(handles.Text_Pkx2,'String',a); set(handles.Phx1_slider,'max',1); set(handles.Phx1_slider,'min',-1); set(handles.Phx1_slider,'value',-0.00087); a=num2str(get(handles.Phx1_slider,'value')); set(handles.Text_Phx1,'String',a); set(handles.Pvx2_slider,'max',1); set(handles.Pvx2_slider,'min',-1); set(handles.Pvx2_slider,'value',-0.04174); a=num2str(get(handles.Pvx2_slider,'value')); set(handles.Text_Pvx2,'String',a); set(handles.Pvx1_slider,'max',1); set(handles.Pvx1_slider,'min',-1); set(handles.Pvx1_slider,'value',0.00295); a=num2str(get(handles.Pvx2_slider,'value')); set(handles.Text_Pvx2,'String',a); handles.figure1; cla; % --- Executes on button press in TirePlotter_GUI_button. function TirePlotter_GUI_button_Callback(hObject, eventdata, handles) % hObject handle to TirePlotter_GUI_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.TireFitter_Panel,'Visible','off'); set(handles.TirePlotter_Panel,'Visible','on'); handles.figure1; cla; % --- Executes on button press in TireFitter_GUI_button. function TireFitter_GUI_button_Callback(hObject, eventdata, handles) % hObject handle to TireFitter_GUI_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.TirePlotter_Panel,'Visible','off'); set(handles.TireFitter_Panel,'Visible','on'); handles.figure1; cla; % --- Executes during object creation, after setting all properties. function edit35_CreateFcn(hObject, eventdata, handles) % hObject handle to edit35 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function edit36_CreateFcn(hObject, eventdata, handles) % hObject handle to edit36 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function edit37_CreateFcn(hObject, eventdata, handles) % hObject handle to edit37 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function MeasurementDataPath_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to MeasurementDataPath_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in BrowseFile_Button. function BrowseFile_Button_Callback(hObject, eventdata, handles) % hObject handle to BrowseFile_Button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.Error_text_Fitter,'String','') [FileName,PathName]= uigetfile('*.mat','Select a ".mat" File'); set(handles.MeasurementDataPath_editT,'String',[PathName FileName]); % --- Executes on button press in MeasurementDataPlot_Button. function MeasurementDataPlot_Button_Callback(hObject, eventdata, handles) % hObject handle to MeasurementDataPlot_Button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) MeasurementFilePath= get(handles.MeasurementDataPath_editT,'String'); if exist(MeasurementFilePath) load(MeasurementFilePath); if exist('NormalLoad') set(handles.Error_text_Fitter,'String',' ') handles.Fitter.NormalLoad= NormalLoad; handles.Fitter.Fx= Fx; handles.Fitter.xdata= xdata; guidata(hObject,handles); else error_text= 'Variable "Normal Load" not defined'; warning(error_text) set(handles.Error_text_Fitter,'String',error_text); end handles.figure1; cla; plot(xdata,Fx,'r.') else error_text= 'File Does not Exist'; set(handles.Error_text_Fitter,'String',error_text); warning(error_text); end % --- Executes on button press in StartFitting_Button. function StartFitting_Button_Callback(hObject, eventdata, handles) % hObject handle to StartFitting_Button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isfield(handles,'Fitter') if get(handles.DefaultSettings_checkbox,'Value') optim_opts= optimset('MaxFunEvals',1e3,'MaxIter',... 1e3,'TolFun',1e1,'TolX',1e1); else optim_opts= optimset('TolX',get(handles.TolX_editT,'String'),... 'TolFun',get(handles.TolFun_editT,'String'),... 'MaxIter',get(handles.MaxIter_editT,'String'),... 'MaxFunEval',get(handles.MaxFunEval_editT,'String'),... 'PlotFcns',get(handles.PlotFcns_editT,'String')); end if get(handles.PlotOpt_checkbox,'Value') optim_opts= optimset('OutputFcn',@optimplotfval2); handles.Fitter.plot_flag= 1; end set(handles.Error_text_Fitter,'ForegroundColor',[0 1 0]); set(handles.Error_text_Fitter,'String','Tire is being Fitted'); handles.Fitter.axes= handles.Main_axes; guidata(hObject,handles); if get(handles.Import_TP_Design_CB,'Value') if isfield(handles,'Current_TP_Design') if ~isempty(handles.Current_TP_Design) handles.startDesign= handles.Current_TP_Design; else warn_txt= 'Import Failed. Continuing to import a random design'; warning(warn_txt); set(handles.Error_text_Fitter,'String',warn_txt); handles.startDesign= handles.Start_MF52Par; end end else handles.startDesign= handles.Start_MF52Par; end guidata(hObject,handles); opt_par= fminsearch(@(par0) opt_fun(par0,handles.Fitter),... handles.startDesign,optim_opts); if get(handles.saveOptPar_checkbox,'Value') saveas(opt_par,[pwd '\OptimisedParameterSet.mat']); end set(handles.Error_text_Fitter,'ForegroundColor',[0 1 0]); set(handles.Error_text_Fitter,'String','Tire Fitting Complete'); else error_txt= 'Measurement Data not loaded!!'; warning(error_txt); set(handles.Error_text_Fitter,'String',error_txt); end % --- Executes during object creation, after setting all properties. function TolX_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to TolX_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function TolFun_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to TolFun_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function MaxIter_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to MaxIter_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function MaxFunEval_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to MaxFunEval_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function PlotFcns_editT_CreateFcn(hObject, eventdata, handles) % hObject handle to PlotFcns_editT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in DefaultSettings_checkbox. function DefaultSettings_checkbox_Callback(hObject, eventdata, handles) % hObject handle to DefaultSettings_checkbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of DefaultSettings_checkbox if ~get(hObject,'Value') set(handles.TolX_editT,'Enable','on') set(handles.TolFun_editT,'Enable','on') set(handles.MaxFunEval_editT,'Enable','on') set(handles.MaxIter_editT,'Enable','on') set(handles.TolX_text,'Enable','on') set(handles.TolFun_text,'Enable','on') set(handles.MaxFunEval_text,'Enable','on') set(handles.MaxIter_text,'Enable','on') else set(handles.TolX_editT,'Enable','off') set(handles.TolFun_editT,'Enable','off') set(handles.MaxFunEval_editT,'Enable','off') set(handles.MaxIter_editT,'Enable','off') set(handles.TolX_text,'Enable','off') set(handles.TolFun_text,'Enable','off') set(handles.MaxFunEval_text,'Enable','off') set(handles.MaxIter_text,'Enable','off') end
github
derpycode/muffinplot-master
plot_target.m
.m
muffinplot-master/source/plot_target.m
10,424
utf_8
e6dd9d9e31a424566dcedf77d9fe96cc
% ------------------------------PLOT_TARGET------------------------------- % ------------------------------------------------------------------------ % Description: Plots the target diagram of Jolliff et al.(2009) for % model skill assessment. % % plot_target has been designed to be accomodate most uses of the target % diagram including a parameter sweep coloured by parameter values and the % plotting of individual experiments with a legend (see EXAMPLE CALLS). % The function is designed such that statistics can be calculated elsewhere % and plotted in bulk, avoiding problems with processing large ensembles in % matlab. % % Reference: Joliff, J.K., Kindle, J.C., Shulman, I., Penta, B., Friedrichs % ,M.A.M., Helber, R., Arnone, R.A., (2009) Summary diagrams for coupled % hydrodynamic-ecosystem model skill assessment. Journal of Marine Systems, % 79, 64-82 (see figs 7 & 14). % % Author: J D Wilson ([email protected]) % ------------------------------------------------------------------------ % INPUT VARIABLES: % -rmsd: std dev normalised unbiased root mean square difference % (mx1 variable) % -bias: std dev normalised bias % (mx1 variable) % % OPTIONAL VARIABLES ([] for blank): % -colour: colour points according to value(s) % (mx1 variable OR LineSpec colour string i.e. 'r') % -R_marker: correlation coefficient that will be plotted as marker % (single value OR multiple i.e. [0.4 0.5]) % -ou_marker: observation uncertainity that will be plotted as marker % (single value OR multiple i.e. [0.4 0.5]) % -axes_handle: handle of axes, if present will plot on corresponding axes % otherwise if blank will plot in a new figure window % % OUTPUT VARIABLES: % -target_handle: handle of the target plot axes for plotting on same % axes % % ------------------------------------------------------------------------ % EXAMPLE CALLS: % -single parameter sweep coloured by parameter values with min R of 0.8: % plot_target(rmsd, bias, colour, 0.8, [], []) % % -single parameter sweep with multiple R markers: % plot_target(rmsd, bias, [], [0.2 0.4 0.8], [], []) % % -multiple experiments with ou values: % figure_handle = plot_target(rmsd_1, bias_1, 'r', [], 0.03, []) % plot_target(rmsd_2, bias_2, 'b', [], 0.05, figure_handle) % plot_target(rmsd_3, bias_3, 'g', [], 0.02, figure_handle) % % POTENTIAL PROBLEMS/ISSUES: % - resizing / zooming in & out within matlab window is not possible % - observational uncertainty not implemented fully % % ------------------------------HISTORY----------------------------------- % Created: 10/06/2012 % 15/06/2012: marker subfunctions, ability to plot multiple markers % 19/08/2012: added axes_handle input to fix open fig window problems % 28/08/2012: removed origin axes legend entries so legend can be used % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ function [ target_handle ] = plot_target ( rmsd , bias , colour , R_marker, ou_marker, axes_handle) % ------------------------------PLOT DATA--------------------------------- % determine whether this is plotting a new figure or adding to an existing % plot and set up an axes handle (==target_handle) so function knows % where to plot subsequent calls if needed. if isempty(axes_handle)==1 figs=max(findall(0,'Type','Figure')); % find highest figure handle if isempty(figs)==1 % if none, figs is empty! figs=0; % so set figs = 0 end figure(figs+1); % otherwise new figure window target_handle=gca; % get new axes_handle replot_flag=0; % flag for new plot else target_handle=axes_handle; % but if given, plot on this! replot_flag=1; % flag as replotting end % plot data as scatter plot (with standard matlab axes) % (n.b. scatter allows flexibility with colour over plot function) % >> no colour! if isempty(colour)==1 scatter(target_handle,rmsd,bias,50,'k','filled'); hold on end % >> colour! if isempty(colour)==0 colormap('Jet') scatter(target_handle,rmsd,bias,50,colour,'filled'); hold on end % ------------------------DRAW NEW ORIGIN AXES---------------------------- if replot_flag==0 % only draw if being plotted for first time! % determine min/max of axis if (max(abs(rmsd))>1 | max(abs(bias))>1) == 1 maxi=2.0; mini=-2.0; elseif (max(abs(rmsd))>2 | max(abs(bias))>2) == 1 disp('rmsd or bias numbers are large...problem?') maxi=2.0; mini=-2.0; elseif (max(abs(rmsd))<1 | max(abs(bias))<1) == 1 maxi=1.0; mini=-1.0; end % draw new axis lines through origin... haxisLine=plot([mini-0.2 maxi+0.2],[0 0],'k'); vaxisLine=plot([0 0],[maxi+0.2 mini-0.2],'k'); % ...but don't allow them to be included in the legend set(get(get(haxisLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); set(get(get(vaxisLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); % set major ticks... XL_major=[mini:0.5:maxi]; YL_major=[mini:0.5:maxi]; set(target_handle,'XTick',XL_major); set(target_handle,'YTick',YL_major); % and minor ticks... XL_minor=[mini-0.2:0.1:maxi+0.2]; YL_minor=[mini-0.2:0.1:maxi+0.2]; % get tick labels for major XLab=get(target_handle,'XtickLabel'); YLab=get(target_handle,'YtickLabel'); % derive tick offsets to align labels with ticks although a bit haphazard! Xoff=diff(get(target_handle,'XLim'))./70; Yoff=diff(get(target_handle,'YLim'))./70; Xoff_minor=diff(get(target_handle,'XLim'))./110; Yoff_minor=diff(get(target_handle,'YLim'))./90; % Plot new major ticks on new axes (and remove from legend) ... for i=1:length(XL_major) xmajtickLine=plot(target_handle,[XL_major(i) XL_major(i)],[0 Yoff],'-k'); set(get(get(xmajtickLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end; for i=1:length(YL_major) ymajtickLine=plot(target_handle,[Xoff, 0],[YL_major(i) YL_major(i)],'-k'); set(get(get(ymajtickLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end; % and minor ticks for i=1:length(XL_minor) xmintickLine=plot(target_handle,[XL_minor(i) XL_minor(i)],[0 Yoff_minor],'-k'); set(get(get(xmintickLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end; for i=1:length(YL_minor) ymintickLine=plot(target_handle,[Xoff_minor, 0],[YL_minor(i) YL_minor(i)],'-k'); set(get(get(ymintickLine,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end; % add new tick labels text(XL_major-0.05,zeros(size(XL_major))-1.*Yoff,XLab); text(zeros(size(YL_major))-3.*Xoff,YL_major,YLab); % add new axes labels text([maxi+0.1],[0]+0.1,'RMSD*''(\sigma_d)') text([0]+0.05,[maxi+0.1],'Bias*') % remove the original axes box off; axis off; set(gcf,'color','w'); % end of drawing new axes through the origin! end % ---------------------------PLOT MARKERS--------------------------------- range1=[-1:0.01:1]'; % range over which to calc circular line points % where RMSD = 1 (points within this marker are *almost* always % positively correlated see pg. 72): if replot_flag==0 circle1=real(0+sqrt(1-((range1-0)).^2)); circle2=real(0-sqrt(1-((range1-0)).^2)); markerLine1=plot(target_handle,range1,circle1,'k'); markerLine2=plot(target_handle,range1,circle2,'k'); set(get(get(markerLine1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end % ----------------------------PLOT R MARKERS------------------------------ % user defined marker(s) for correlation coefficient (R): % subfunction calculates equivalent RMSD*'(sigma_diff) value (see pg. 72, eq. 14) if isempty(R_marker)==0 plot_marker(R_marker , target_handle) end % ----------------PLOT OBSERVATION UNCERTAINITY MARKER-------------------- % plot marker for observational uncertainty, % (currently not fully implemented see pg. 73 for details on this) if isempty(ou_marker)==0 plot_ou(ou_marker , target_handle) end % ---------------------------COLOUR BAR----------------------------------- % plot a colourbar if data is given in colour (i.e. not a LineSpec) if isempty(colour)==0 & ischar(colour)==0 C=colorbar ('h'); set(C,'location','South',... 'XTick',[max(colour) min(colour)],... 'XTickLabel',{'Max', 'Min'}) end % --------------------------FINISHING TOUCHES----------------------------- % set dimensions straight set(gca,'DataAspectRatio',[1 1 1]) end % ------------------------------------------------------------------------ % -----------------------------SUB FUNCTIONS------------------------------ % ------------------------------------------------------------------------ function [] = plot_marker ( R_marker , target_handle ) R=sqrt(1.0+R_marker.^2-2*R_marker.^2)'; for n=1:size(R) range2{:,n}=[-(R(n)):0.01:R(n)+0.01]'; % range over which to calc circular line points end for n=1:size(R) circle1{:,n}=real(0+sqrt(R(n)^2-((range2{1,n}-0).^2))); circle2{:,n}=real(0-sqrt(R(n)^2-((range2{1,n}-0).^2))); end for n=1:size(R) RLine1=plot(target_handle,range2{1,n},circle1{1,n},'k--'); RLine2=plot(target_handle,range2{1,n},circle2{1,n},'k--'); set(get(get(RLine1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end end function [] = plot_ou ( ou_marker , target_handle ) ou=ou_marker'; for n=1:size(ou) range3{:,n}=[-(ou(n)):0.01:ou(n)+0.01]' % range over which to calc circular line points end for n=1:size(ou) circle1{:,n}=real(0+sqrt(ou(n)^2-((range3{1,n}-0).^2))); circle2{:,n}=real(0-sqrt(ou(n)^2-((range3{1,n}-0).^2))); end for n=1:size(ou) ouLine1=plot(target_handle,range3{1,n},circle1{1,n},'k--'); ouLine2=plot(target_handle,range3{1,n},circle2{1,n},'k--'); set(get(get(ouLine1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); end end %------------------------------------------------------------------------ %----------------------------------END-----------------------------------
github
derpycode/muffinplot-master
plot_taylordiag.m
.m
muffinplot-master/source/plot_taylordiag.m
17,558
utf_8
8b116586f635384019cd2826a13ecb9a
% TAYLORDIAG Plot a Taylor Diagram % % [hp ht axl] = taylordiag(STDs,RMSs,CORs,['option',value]) % % Plot a Taylor diagram from statistics of different series. % % INPUTS: % STDs: Standard deviations % RMSs: Centered Root Mean Square Difference % CORs: Correlation % % Each of these inputs are one dimensional with same length. First % indice corresponds to the reference serie for the diagram. For exemple % STDs(1) is the standard deviation of the reference serie and STDs(2:N) % are the standard deviations of the other series. % % Note that by definition the following relation must be true for all series i: % RMSs(i) - sqrt(STDs(i).^2 + STDs(1)^2 - 2*STDs(i)*STDs(1).*CORs(i)) = 0 % This relation is checked and if not verified an error message is sent. Please see % Taylor's JGR article for more informations about this. % You can use the ALLSTATS function to avoid this to happen, I guess ;-). You can get % it somewhere from: http://codes.guillaumemaze.org/matlab % % OUTPUTS: % hp: returns handles of plotted points % ht: returns handles of the text legend of points % axl: returns a structure of handles of axis labels % % LIST OF OPTIONS: % For an exhaustive list of options to customize your diagram, please call the function % without arguments: % >> taylordiag % % SHORT TUTORIAL (see taylordiag_test.m for more informations): % An easy way to get compute inputs is to use the ALLSTATS function you can get from: % http://codes.guillaumemaze.org/matlab % Let's say you gathered all the series you want to put in the Taylor diagram in a % single matrix BUOY(N,nt) with N the number of series and nt their (similar) length. % If BUOY(1,:) is the serie of reference for the diagram: % for iserie = 2 : size(BUOY,1) % S = allstats(BUOY(1,:),BUOY(iserie,:)); % MYSTATS(iserie,:) = S(:,2); % We get stats versus reference % end%for iserie % MYSTATS(1,:) = S(:,1); % We assign reference stats to the first row % Note that the ALLSTATS function can handle NaNs, so be careful to compute statistics % with enough points ! % Then you're ready to simply run: % taylordiag(MYSTATS(:,2),MYSTATS(:,3),MYSTATS(:,4)); % % REF: K. Taylor % Summarizing multiple aspects of model performance in a single diagram % Journal of Geophysical Research-Atmospheres, 2001, V106, D7. % % Rev. by Guillaume Maze on 2010-02-10: Help more helpful ! Options now displayed by call. % Copyright (c) 2008 Guillaume Maze. % http://codes.guillaumemaze.org % 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 the Laboratoire de Physique des Oceans 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 Guillaume Maze ''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 Guillaume Maze 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 varargout = plot_taylordiag(varargin) %% if nargin == 0 disp_optionslist; return else narg = nargin - 3; if mod(narg,2) ~=0 error('taylordiag.m : Wrong number of arguments') end end STDs = varargin{1}; RMSs = varargin{2}; CORs = varargin{3}; %% CHECK THE INPUT FIELDS: apro = 100; di = fix(RMSs*apro)/apro - fix(sqrt(STDs.^2 + STDs(1)^2 - 2*STDs*STDs(1).*CORs)*apro)/apro; if find(di~=0) % help taylordiag.m ii = find(di~=0); if length(ii) == length(di) error(sprintf('taylordiag.m : Something''s wrong with ALL the datas\nYou must have:\nRMSs - sqrt(STDs.^2 + STDs(1)^2 - 2*STDs*STDs(1).*CORs) = 0 !')) else error(sprintf('taylordiag.m : Something''s wrong with data indice(s): [%i]\nYou must have:\nRMSs - sqrt(STDs.^2 + STDs(1)^2 - 2*STDs*STDs(1).*CORs) = 0 !',ii)) end end %% IN POLAR COORDINATES: rho = STDs/STDs(1); theta = real(acos(CORs)); dx = rho(1); % Observed STD %% BEGIN THE PLOT HERE TO GET AXIS VALUES: hold off cax = gca; tc = get(cax,'xcolor'); %ls = get(cax,'gridlinestyle'); ls = '-'; % DEFINE HERE THE GRID STYLE next = lower(get(cax,'NextPlot')); %% LOAD CUSTOM OPTION OF AXE LIMIT: nopt = narg/2; foundrmax = 0; for iopt = 4 : 2 : narg+3 optvalue = varargin{iopt+1}; switch lower(varargin{iopt}), case 'limstd', rmax = optvalue; foundrmax=1; end end % make a radial grid hold(cax,'on'); if foundrmax==0 maxrho = max(abs(rho(:))); else maxrho = rmax; end hhh = line([-maxrho -maxrho maxrho maxrho],[-maxrho maxrho maxrho -maxrho],'parent',cax); set(cax,'dataaspectratio',[1 1 1],'plotboxaspectratiomode','auto') v = [get(cax,'xlim') get(cax,'ylim')]; ticks = sum(get(cax,'ytick')>=0); delete(hhh); % check radial limits and ticks rmin = 0; if foundrmax == 0; rmax = v(4); end rticks = max(ticks-1,2); if rticks > 5 % see if we can reduce the number if rem(rticks,2) == 0 rticks = rticks/2; elseif rem(rticks,3) == 0 rticks = rticks/3; end end rinc = (rmax-rmin)/rticks; tick = (rmin+rinc):rinc:rmax; %% LOAD DEFAULT PARAMETERS: if find(CORs<0) Npan = 2; % double panel else Npan = 1; end tickRMSangle = 135; showlabelsRMS = 1; showlabelsSTD = 1; showlabelsCOR = 1; colSTD = [0 0 0]; colRMS = [0 .6 0]; colCOR = [0 0 1]; tickCOR(1).val = [1 .99 .95 .9:-.1:0]; tickCOR(2).val = [1 .99 .95 .9:-.1:0 -.1:-.1:-.9 -.95 -.99 -1]; widthCOR = .8; widthRMS = .8; widthSTD = .8; styleCOR = '-.'; styleRMS = '--'; styleSTD = ':'; titleRMS = 1; titleCOR = 1; titleSTD = 1; tickRMS = tick; rincRMS = rinc; tickSTD = tick; rincSTD = rinc; %% LOAD CUSTOM OPTIONS: nopt = narg/2; for iopt = 4 : 2 : narg+3 optname = varargin{iopt}; optvalue = varargin{iopt+1}; switch lower(optname) case 'tickrms' tickRMS = sort(optvalue); rincRMS = (max(tickRMS)-min(tickRMS))/length(tickRMS); case 'showlabelsrms' showlabelsRMS = optvalue; case 'tickrmsangle' tickRMSangle = optvalue; case 'colrms' colRMS = optvalue; case 'widthrms' widthRMS = optvalue; case 'stylerms' styleRMS = optvalue; case 'titlerms' titleRMS = optvalue; case 'tickstd' tickSTD = sort(optvalue); rincSTD = (max(tickSTD)-min(tickSTD))/length(tickSTD); case 'showlabelsstd' showlabelsSTD = optvalue; case 'colstd' colstd = optvalue; case 'widthstd' widthSTD = optvalue; case 'stylestd' styleSTD = optvalue; case 'titlestd' titleSTD = optvalue; case 'npan' Npan = optvalue; case 'tickcor' tickCOR(Npan).val = optvalue; case 'colcor' colCOR = optvalue; case 'widthcor' widthCOR = optvalue; case 'stylecor' styleCOR = optvalue; case 'titlecor' titleCOR = optvalue; case 'showlabelscor' showlabelsCOR = optvalue; end end %% CONTINUE THE PLOT WITH UPDATED OPTIONS: % define a circle th = 0:pi/150:2*pi; xunit = cos(th); yunit = sin(th); % now really force points on x/y axes to lie on them exactly inds = 1:(length(th)-1)/4:length(th); xunit(inds(2:2:4)) = zeros(2,1); yunit(inds(1:2:5)) = zeros(3,1); % plot background if necessary if ~ischar(get(cax,'color')), % ig = find(th>=0 & th<=pi); ig = 1:length(th); patch('xdata',xunit(ig)*rmax,'ydata',yunit(ig)*rmax, ... 'edgecolor',tc,'facecolor',get(cax,'color'),... 'handlevisibility','off','parent',cax); end % DRAW RMS CIRCLES: % ANGLE OF THE TICK LABELS c82 = cos(tickRMSangle*pi/180); s82 = sin(tickRMSangle*pi/180); for ic = 1 : length(tickRMS) i = tickRMS(ic); iphic = find( sqrt(dx^2+rmax^2-2*dx*rmax*xunit) >= i ,1); ig = find(i*cos(th)+dx <= rmax*cos(th(iphic))); hhh = line(xunit(ig)*i+dx,yunit(ig)*i,'linestyle',styleRMS,'color',colRMS,'linewidth',widthRMS,... 'handlevisibility','off','parent',cax); if showlabelsRMS text((i+rincRMS/20)*c82+dx,(i+rincRMS/20)*s82, ... [' ' num2str(i)],'verticalalignment','bottom',... 'handlevisibility','off','parent',cax,'color',colRMS,'rotation',tickRMSangle-90) end end % DRAW DIFFERENTLY THE CIRCLE CORRESPONDING TO THE OBSERVED VALUE % hhh = line((cos(th)*dx),sin(th)*dx,'linestyle','--','color',colSTD,'linewidth',1,... % 'handlevisibility','off','parent',cax); % DRAW STD CIRCLES: % draw radial circles for ic = 1 : length(tickSTD) i = tickSTD(ic); hhh = line(xunit*i,yunit*i,'linestyle',styleSTD,'color',colSTD,'linewidth',widthSTD,... 'handlevisibility','off','parent',cax); if showlabelsSTD if Npan == 2 if length(find(tickSTD==0)) == 0 text(0,-rinc/20,'0','verticalalignment','top','horizontalAlignment','center',... 'handlevisibility','off','parent',cax,'color',colSTD); end text(i,-rinc/20, ... num2str(i),'verticalalignment','top','horizontalAlignment','center',... 'handlevisibility','off','parent',cax,'color',colSTD) else if length(find(tickSTD==0)) == 0 text(-rinc/20,rinc/20,'0','verticalalignment','middle','horizontalAlignment','right',... 'handlevisibility','off','parent',cax,'color',colSTD); end text(-rinc/20,i, ... num2str(i),'verticalalignment','middle','horizontalAlignment','right',... 'handlevisibility','off','parent',cax,'color',colSTD) end end end set(hhh,'linestyle','-') % Make outer circle solid % DRAW CORRELATIONS LINES EMANATING FROM THE ORIGIN: corr = tickCOR(Npan).val; th = acos(corr); cst = cos(th); snt = sin(th); cs = [-cst; cst]; sn = [-snt; snt]; line(rmax*cs,rmax*sn,'linestyle',styleCOR,'color',colCOR,'linewidth',widthCOR,... 'handlevisibility','off','parent',cax) % annotate them in correlation coef if showlabelsCOR rt = 1.05*rmax; for i = 1:length(corr) text(rt*cst(i),rt*snt(i),num2str(corr(i)),... 'horizontalalignment','center',... 'handlevisibility','off','parent',cax,'color',colCOR); if i == length(corr) loc = int2str(0); loc = '1'; else loc = int2str(180+i*30); loc = '-1'; end end end % AXIS TITLES axlabweight = 'bold'; ix = 0; if Npan == 1 if titleSTD ix = ix + 1; ax(ix).handle = ylabel('Standard deviation (normalized)','color',colSTD,'fontweight',axlabweight); end if titleCOR ix = ix + 1; clear ttt pos1 = 45; DA = 15; lab = 'Correlation Coefficient'; c = fliplr(linspace(pos1-DA,pos1+DA,length(lab))); dd = 1.1*rmax; ii = 0; for ic = 1 : length(c) ith = c(ic); ii = ii + 1; ttt(ii)=text(dd*cos(ith*pi/180),dd*sin(ith*pi/180),lab(ii)); set(ttt(ii),'rotation',ith-90,'color',colCOR,'horizontalalignment','center',... 'verticalalignment','bottom','fontsize',get(ax(1).handle,'fontsize'),'fontweight',axlabweight); end ax(ix).handle = ttt; end if titleRMS ix = ix + 1; clear ttt pos1 = tickRMSangle+(180-tickRMSangle)/2; DA = 15; pos1 = 160; lab = 'RMSD'; c = fliplr(linspace(pos1-DA,pos1+DA,length(lab))); dd = 1.05*tickRMS(1); dd = .95*tickRMS(2); ii = 0; for ic = 1 : length(c) ith = c(ic); ii = ii + 1; ttt(ii)=text(dx+dd*cos(ith*pi/180),dd*sin(ith*pi/180),lab(ii)); set(ttt(ii),'rotation',ith-90,'color',colRMS,'horizontalalignment','center',... 'verticalalignment','top','fontsize',get(ax(1).handle,'fontsize'),'fontweight',axlabweight); end ax(ix).handle = ttt; end else if titleSTD ix = ix + 1; ax(ix).handle =xlabel('Standard deviation','fontweight',axlabweight,'color',colSTD); end if titleCOR ix = ix + 1; clear ttt pos1 = 90; DA = 15; lab = 'Correlation Coefficient'; c = fliplr(linspace(pos1-DA,pos1+DA,length(lab))); dd = 1.1*rmax; ii = 0; for ic = 1 : length(c) ith = c(ic); ii = ii + 1; ttt(ii)=text(dd*cos(ith*pi/180),dd*sin(ith*pi/180),lab(ii)); set(ttt(ii),'rotation',ith-90,'color',colCOR,'horizontalalignment','center',... 'verticalalignment','bottom','fontsize',get(ax(1).handle,'fontsize'),'fontweight',axlabweight); end ax(ix).handle = ttt; end if titleRMS ix = ix + 1; clear ttt pos1 = 160; DA = 10; lab = 'RMSD'; c = fliplr(linspace(pos1-DA,pos1+DA,length(lab))); dd = 1.05*tickRMS(1); ii = 0; for ic = 1 : length(c) ith = c(ic); ii = ii + 1; ttt(ii)=text(dx+dd*cos(ith*pi/180),dd*sin(ith*pi/180),lab(ii)); set(ttt(ii),'rotation',ith-90,'color',colRMS,'horizontalalignment','center',... 'verticalalignment','bottom','fontsize',get(ax(1).handle,'fontsize'),'fontweight',axlabweight); end ax(ix).handle = ttt; end end % VARIOUS ADJUSTMENTS TO THE PLOT: set(cax,'dataaspectratio',[1 1 1]), axis(cax,'off'); set(cax,'NextPlot',next); set(get(cax,'xlabel'),'visible','on') set(get(cax,'ylabel'),'visible','on') % makemcode('RegisterHandle',cax,'IgnoreHandle',q,'FunctionName','polar'); % set view to 2-D view(cax,2); % set axis limits if Npan == 2 axis(cax,rmax*[-1.15 1.15 0 1.15]); line([-rmax rmax],[0 0],'color',tc,'linewidth',1.2); line([0 0],[0 rmax],'color',tc); else axis(cax,rmax*[0 1.15 0 1.15]); % axis(cax,rmax*[-1 1 -1.15 1.15]); line([0 rmax],[0 0],'color',tc,'linewidth',1.2); line([0 0],[0 rmax],'color',tc,'linewidth',2); end % FINALY PLOT THE POINTS: hold on ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; for ii = 1 : length(STDs) % pp(ii)=polar(theta(ii),rho(ii)); pp(ii)=plot(rho(ii)*cos(theta(ii)),rho(ii)*sin(theta(ii))); set(pp(ii),'marker','.','markersize',20); set(pp(ii),'color','r'); if length(STDs)<=26 tt(ii)=text(rho(ii)*cos(theta(ii)),rho(ii)*sin(theta(ii)),ALPHABET(ii),'color','r'); elseif length(STDs)<=26*2 tt(ii)=text(rho(ii)*cos(theta(ii)),rho(ii)*sin(theta(ii)),lower(ALPHABET(ii)),'color','r'); else error('sorry I don''t how to handle more than 52 points labels !'); end end set(tt,'verticalalignment','bottom','horizontalalignment','right') set(tt,'fontsize',12) %%% OUTPUT switch nargout case 1 varargout(1) = {pp}; case 2 varargout(1) = {pp}; varargout(2) = {tt}; case 3 varargout(1) = {pp}; varargout(2) = {tt}; varargout(3) = {ax}; end end%function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = disp_optionslist(varargin) disp('General options:') dispopt('''Npan''',sprintf('1 or 2: Panels to display (1 for positive correlations, 2 for positive and negative correlations).\n\t\tDefault value depends on CORs')); disp('RMS axis options:') dispopt('''tickRMS''','RMS values to plot gridding circles from observation point'); dispopt('''colRMS''','RMS grid and tick labels color. Default: green'); dispopt('''showlabelsRMS''','0 / 1 (default): Show or not the RMS tick labels'); dispopt('''tickRMSangle''','Angle for RMS tick lables with the observation point. Default: 135 deg.'); dispopt('''styleRMS''','Linestyle of the RMS grid'); dispopt('''widthRMS''','Line width of the RMS grid'); dispopt('''titleRMS''','0 / 1 (default): Show RMSD axis title'); disp('STD axis options:') dispopt('''tickSTD''','STD values to plot gridding circles from origin'); dispopt('''colSTD''','STD grid and tick labels color. Default: black'); dispopt('''showlabelsSTD''','0 / 1 (default): Show or not the STD tick labels'); dispopt('''styleSTD''','Linestyle of the STD grid'); dispopt('''widthSTD''','Line width of the STD grid'); dispopt('''titleSTD''','0 / 1 (default): Show STD axis title'); dispopt('''limSTD''','Max of the STD axis (radius of the largest circle)'); disp('CORRELATION axis options:') dispopt('''tickCOR''','CORRELATON grid values'); dispopt('''colCOR''','CORRELATION grid color. Default: blue'); dispopt('''showlabelsCOR''','0 / 1 (default): Show or not the CORRELATION tick labels'); dispopt('''styleCOR''','Linestyle of the COR grid'); dispopt('''widthCOR''','Line width of the COR grid'); dispopt('''titleCOR''','0 / 1 (default): Show CORRELATION axis title'); end%function function [] = dispopt(optname,optval) disp(sprintf('\t%s',optname)); disp(sprintf('\t\t%s',optval)); end
github
derpycode/muffinplot-master
calc_allstats_target.m
.m
muffinplot-master/source/calc_allstats_target.m
3,876
utf_8
52793ea025c4e3068d275402196cf5b1
% STATM Compute statistics from 2 series % % STATM = calc_allstats(Cr,Cf) % % Compute statistics from 2 series considering Cr as the reference. % % Inputs: % Cr and Cf are of same length and uni-dimensional. They may contain NaNs. % % Outputs: % STATM(1,:) => Mean % STATM(2,:) => Standard Deviation (scaled by N) % STATM(3,:) => Centered Root Mean Square Difference (scaled by N) % STATM(4,:) => Correlation % % Notes: % - N is the number of points where BOTH Cr and Cf are defined % % - NaN are handled in the following way: because this function % aims to compair 2 series, statistics are computed with indices % where both Cr and Cf are defined. % % - STATM(:,1) are from Cr (ie with C=Cr hereafter) % STATM(:,2) are from Cf versus Cr (ie with C=Cf hereafter) % % - The MEAN is computed using the Matlab mean function. % % - The STANDARD DEVIATION is computed as: % / sum[ {C-mean(C)} .^2] \ % STD = sqrt| --------------------- | % \ N / % % - The CENTERED ROOT MEAN SQUARE DIFFERENCE is computed as: % / sum[ { [C-mean(C)] - [Cr-mean(Cr)] }.^2 ] \ % RMSD = sqrt| ------------------------------------------- | % \ N / % % - The CORRELATION is computed as: % sum( [C-mean(C)].*[Cr-mean(Cr)] ) % COR = --------------------------------- % N*STD(C)*STD(Cr) % % - STATM(3,1) = 0 and STATM(4,1) = 1 by definition ! % % Created by Guillaume Maze on 2008-10-28. % Rev. by Guillaume Maze on 2010-02-10: Add NaN values handling, some checking % in the inputs and a more complete help % Copyright (c) 2008 Guillaume Maze. % http://codes.guillaumemaze.org % % 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 3 of the License, or any later version. % This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. % function STATM = calc_allstats(varargin) Cr = varargin{1}; Cr = Cr(:); Cf = varargin{2}; Cf = Cf(:); %%% Check size: if length(Cr) ~= length(Cf) error('Cr and Cf must be of same length'); end %%% Check NaNs: iok = find(isnan(Cr)==0 & isnan(Cf)==0); if length(iok) ~= length(Cr) %warning('Found NaNs in inputs, removed them to compute statistics'); end Cr = Cr(iok); Cf = Cf(iok); N = length(Cr); %%% STD: st(1) = sqrt(sum( (Cr-mean(Cr) ).^2) / N ); st(2) = sqrt(sum( (Cf-mean(Cf) ).^2) / N ); %%% MEAN: me(1) = mean(Cr); me(2) = mean(Cf); %%% RMSD: rms(1) = sqrt(sum( ( ( Cr-mean(Cr) )-( Cr-mean(Cr) )).^2) /N); rms(2) = sqrt(sum( ( ( Cf-mean(Cf) )-( Cr-mean(Cr) )).^2) /N); %%% CORRELATIONS: co(1) = sum( ( ( Cr-mean(Cr) ).*( Cr-mean(Cr) )))/N/st(1)/st(1); co(2) = sum( ( ( Cf-mean(Cf) ).*( Cr-mean(Cr) )))/N/st(2)/st(1); %%% TOTAL RMSD: rms_total(1) = sqrt(sum( (Cr - Cr).^2)/N); rms_total(2) = sqrt(sum( (Cf - Cr).^2)/N); %%% STANDARD DEVIATION NORMALISED RMSD: rms_stdised(1) = (rms(1) * sign( st(2) - st(1) )) / st(1); rms_stdised(2) = (rms(2) * sign( st(2) - st(1) ))/ st(1); %%% NORMALISED BIAS: bias_stdised(1) = (mean(Cr) - mean(Cr)) / st(1); bias_stdised(2) = (mean(Cf) - mean(Cr)) / st(1); %%% OUTPUT STATM(1,:) = me; STATM(2,:) = st; STATM(3,:) = rms; STATM(4,:) = co; STATM(5,:) = N; STATM(6,:) = rms_total; STATM(7,:) = rms_stdised; STATM(8,:) = bias_stdised; end %function
github
derpycode/muffinplot-master
calc_allstats.m
.m
muffinplot-master/source/calc_allstats.m
4,749
utf_8
82a5324d8cf4ff557d819d13e12874cd
% STATM Compute statistics from 2 series % % STATM = calc_allstats(Cr,Cf) % % Compute statistics from 2 series considering Cr as the reference. % % Inputs: % Cr and Cf are of same length and uni-dimensional. They may contain NaNs. % % Outputs: % STATM(1,:) => Mean % STATM(2,:) => Standard Deviation (scaled by N) % STATM(3,:) => Centered Root Mean Square Difference (scaled by N) % STATM(4,:) => Correlation % % Notes: % - N is the number of points where BOTH Cr and Cf are defined % % - NaN are handled in the following way: because this function % aims to compair 2 series, statistics are computed with indices % where both Cr and Cf are defined. % % - STATM(:,1) are from Cr (ie with C=Cr hereafter) % STATM(:,2) are from Cf versus Cr (ie with C=Cf hereafter) % % - The MEAN is computed using the Matlab mean function. % % - The STANDARD DEVIATION is computed as: % / sum[ {C-mean(C)} .^2] \ % STD = sqrt| --------------------- | % \ N / % % - The CENTERED ROOT MEAN SQUARE DIFFERENCE is computed as: % / sum[ { [C-mean(C)] - [Cr-mean(Cr)] }.^2 ] \ % RMSD = sqrt| ------------------------------------------- | % \ N / % % - The CORRELATION is computed as: % sum( [C-mean(C)].*[Cr-mean(Cr)] ) % COR = --------------------------------- % N*STD(C)*STD(Cr) % % - STATM(3,1) = 0 and STATM(4,1) = 1 by definition ! % % Created by Guillaume Maze on 2008-10-28. % Rev. by Guillaume Maze on 2010-02-10: Add NaN values handling, some checking % in the inputs and a more complete help % Copyright (c) 2008 Guillaume Maze. % http://codes.guillaumemaze.org % % 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 3 of the License, or any later version. % This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. % function STATM = calc_allstats(varargin) Cr = varargin{1}; Cr = Cr(:); Cf = varargin{2}; Cf = Cf(:); %%% Check size: if length(Cr) ~= length(Cf) error('Cr and Cf must be of same length'); end %%% Check NaNs: iok = find(isnan(Cr)==0 & isnan(Cf)==0); if length(iok) ~= length(Cr) %warning('Found NaNs in inputs, removed them to compute statistics'); end Cr = Cr(iok); Cf = Cf(iok); N = length(Cr); %%% STD: st(1) = sqrt(sum( (Cr-mean(Cr) ).^2) / N ); st(2) = sqrt(sum( (Cf-mean(Cf) ).^2) / N ); %%% MEAN: me(1) = mean(Cr); me(2) = mean(Cf); %%% RMSD: rms(1) = sqrt(sum( ( ( Cr-mean(Cr) )-( Cr-mean(Cr) )).^2) /N); rms(2) = sqrt(sum( ( ( Cf-mean(Cf) )-( Cr-mean(Cr) )).^2) /N); %%% CORRELATIONS: co(1) = sum( ( ( Cr-mean(Cr) ).*( Cr-mean(Cr) )))/N/st(1)/st(1); co(2) = sum( ( ( Cf-mean(Cf) ).*( Cr-mean(Cr) )))/N/st(2)/st(1); %%% TOTAL RMSD: rms_total(1) = sqrt(sum( (Cr - Cr).^2)/N); rms_total(2) = sqrt(sum( (Cf - Cr).^2)/N); %%% STANDARD DEVIATION NORMALISED RMSD: rms_stdised(1) = (rms(1) * sign( st(2) - st(1) )) / st(1); rms_stdised(2) = (rms(2) * sign( st(2) - st(1) ))/ st(1); %%% NORMALISED BIAS: bias_stdised(1) = (mean(Cr) - mean(Cr)) / st(1); bias_stdised(2) = (mean(Cf) - mean(Cr)) / st(1); % R2 R2(1) = 1 - ( sum((Cr - Cr).^2) / sum( (Cr-mean(Cr) ).^2) ); R2(2) = 1 - ( sum((Cr - Cf).^2) / sum( (Cr-mean(Cr) ).^2) ); % Additional requirements to calculate the AMS score % Information for this metric is found in the paper % 'Non-dimensional measures of climate model performance' % I.G. Watterson, 1996, international journal of climatology, vol (16) pp % 379-391 % st dev squared V1 = st(1).^2; V2 = st(2).^2; %% BIAS B = (me(2) - me(1)).^2; %%% MEAN SQUARED ERROR MSE1 = sum( (Cf - Cr).^2); MSE = MSE1/N; Z = (1 - MSE/(V1 + V2 + B)); if (Z < -1) Z = -1; end %%% M SCORE M(1) = 0; %if (co(2) >= 0.0000) M(2) = (2/pi)*asin(Z); %else % M(2) = 0; %end %%% OUTPUT STATM(1,:) = me; STATM(2,:) = st; STATM(3,:) = rms; STATM(4,:) = co; STATM(5,:) = N; STATM(6,:) = rms_total; STATM(7,:) = rms_stdised; STATM(8,:) = bias_stdised; STATM(9,:) = R2; STATM(10,:) = M; %this is the value used for model ranking STATM(11,:) = [NaN MSE]; STATM(12,:) = [NaN B]; STATM(13,:) = [V1 V2]; STATM(14,:) = [NaN Z]; end %function
github
derpycode/muffinplot-master
plot_taylor.m
.m
muffinplot-master/source/plot_taylor.m
10,556
utf_8
6bdbf62fca37c526a199841f448e06c6
% Taylor diagram for summarizing model performance % % Taylor, 2001 - JGR, 106(D7) % % Program adapted from the IDL routine from K.E. Taylor % (simplified version including less options) % % ---- Call : % plot_taylor(tsig,rsig,tcorr,out,name_experiment,title) % % ---- Input: % Needed: % tsig : Standard deviation for the experiments (n values) % rsig : Standard deviation for the reference (1 value) % tcorr : Correlation between the reference and the experiments % (n values) % % Optional: % out : 1 = standard display in a window (default) % 2 = encapsulated postcript output named 'output.eps' % name_experiment : Name of the experiment used in the legend % ([n x length of the longer name] array of characters) % maintit : Title (string) % ---- Output: % postcript or figure depending on the 'out' option ... % % % ---------------------------------------------------------------------- % G. Charria (02/2008) % A. Yool (16/06/2008; extensive "prettying up") % ---------------------------------------------------------------------- function [plt, leg] = plot_taylor(tsig,rsig,tcorr,out,name_experiment,maintit,set_sigmax) % close all % clf % --------------------------- % ---- Parameters definition % --------------------------- % sigmax : radial limit of plot if (max(tsig./rsig) < 1) sigmax = 1; else sigmax = max((tsig./rsig))+0.1; end % AXY: allow user to control sigmax with a final argument flag_bounds = tsig * 0; if (nargin == 7) sigmax = set_sigmax; % this also sets all data values outside this maximum to equal the % maximum, and tags them up for special treatment (symbols turn % black) at the plotting stage t1 = tsig / rsig; t2 = find(t1 > sigmax); tsig(t2) = rsig * sigmax; flag_bounds(t2) = 1; end % AXY: just in case something other than standard deviation is used % and has values less than zero, this section sets the values % to NaNs t1 = tsig / rsig; t2 = find(t1 < 0); tsig(t2) = NaN; % Test on input for the choice of output. if (nargin < 4) out = 1; end % Y-axis title ytitle = 'Standard deviation (normalised)'; % X-axis title xtitle = 'Standard deviation (normalised)'; % Fontsize for the plot axcsiz = 12; % Tick location % AXY: parameter "val" should be adjusted ad hoc to get a satisfying % distribution of labels - I've tried, unsuccessfully, to come % up with a good automated version, but haven't managed so far % AXY: the new code below tries out a series of potential tick increments % and selects as the first/best one that which produces 8 ticks or more; % far from ideal, but the results look OK tryval = [0.1 0.2 0.25 0.5 1 2]; maxtry = max(size(tryval)); for i = 1:1:maxtry val = tryval(i); yticloc=0.:val:sigmax; [q1, q2] = max(size(yticloc)); numtic(i) = q1; end q1 = find(numtic >= 8); q2 = max(q1); if isempty(q2), q2 = maxtry; end val = tryval(q2); val = 1; yticloc=0.:val:sigmax; ylabels = yticloc; xticloc = yticloc; xlabels = ylabels; dummy=0.; % AXY: sort out legend labels str1 = name_experiment; [s1, s2] = size(str1); str2(2:(s1+1),:) = str1; if s2 < 9, str2(s1+1,9) = ' '; end str2(1,1:9) = 'Reference'; name_experiment = str2; % ------------------------------------- % Minor Ticks rminticval = 0.05:0.1:0.95; % Subminor Ticks rsubticval = 0.91:0.01:0.99; % Major Ticks rlabticval = [0.0, 0.1, 0.2, 0.3, 0.4,... 0.5, 0.6, 0.7, ... 0.8, 0.9, 0.95, 0.99, 1.0]; % Major Tick Labels rticlabels = ['0.0 '; '0.1 '; '0.2 ';... '0.3 '; '0.4 '; '0.5 ';... '0.6 '; '0.7 '; '0.8 ';... '0.9 '; '0.95'; '0.99';... '1.0 ']; % 'Correlation' label corrt=['C';'o';'r';'r';'e';'l';'a';'t';'i';'o';'n']; % Length of minor ticks minortic= 0.015; % Length of subminor ticks subtic = 0.010; % Definition of markers: val = length(tsig); % AXY: use Ocean Data View colourmap for plotting % pal2 = odvpal(val+2); pal = pal2(2:1:end-1,:); pal2 = hsv(val+2); pal = pal2(2:1:end-1,:); kind=['+';'o';'x';'s';'d';'^';'v';'p';'h';'*']; colorm=['b';'r';'g';'c';'m';'y';'k']; n=1; marker(1:(size(colorm,1)*size(kind,1)),1:2)=' '; for ic=1:size(colorm,1) for ik=1:size(kind,1) marker(n,:)=[kind(ik,:) colorm(ic,:)]; n=n+1; end end if (length(tsig) > 70) disp('You must introduce new markers to plot more than 70 cases.') disp('The ''marker'' character array need to be extended inside the code.') return end % -------------------------------------- % Test to draw main rays or not arccntl=1; if (arccntl > 0) rticlen=1.; % Draw the complete ray else rticlen=0.02; % Draw just a Tick end if (out==2) figure; set(gcf,'Visible','off') end % ----------------------------- % ---- Plot main axes (X and Y) % ----------------------------- % plot(dummy,dummy) box('off') pbaspect([1 1 1]) % set(gcf,'Color','w') set(gca,'XLim',[0 sigmax],... 'YLim',[0., sigmax],... 'YMinorTick','on',... 'XMinorTick','on',... 'TickLen',[0.01 0.01],... 'XTick',xticloc,... 'XTickLabel',xlabels,... 'YTick',yticloc,... 'YTickLabel',ylabels,... 'FontSize',axcsiz) xlabel(xtitle) ylabel(ytitle) hold on; % ------------------------------------ % ---- Draw Results % ------------------------------------ % Loop over the number of experiments % AXY: this has been moved here so that a legend can be plotted properly % -- Plot reference data point h = plot (1, 0, 'o', 'MarkerSize', 6, 'LineWidth', 2, ... 'MarkerEdgeColor', [1 0 0], 'MarkerFaceColor', [0 0 0]); % -- Plot data for i1=1:length(tsig) xx = (tsig(i1)/rsig(1))*tcorr(i1); yy = (tsig(i1)/rsig(1))*sqrt(1.-tcorr(i1)*tcorr(i1)); h=plot(xx,yy,marker(i1,1),'MarkerSize',6,'Linewidth',2); if flag_bounds(i1) == 0 set(h, 'Color', pal(i1,:)); else set(h, 'Color', [0 0 0]); end end % ----------------------------- % ---- Plot radial lines % ----------------------------- % Plot the extreme line xa = sigmax*(0:0.001:1); ya = sigmax*sqrt(1.-(0:0.001:1).*(0:0.001:1)); plot(xa,ya,'k') % Plot the '1' line xa = 1.*(0:0.001:1); ya = 1.*sqrt(1.-(0:0.001:1).*(0:0.001:1)); plot(xa,ya,':k','LineWidth',1.5) % Plot few other lines ... for il=0.2:0.2:1 xa = il*(0:0.001:1); ya = il*sqrt(1.-(0:0.001:1).*(0:0.001:1)); plot(xa,ya,':k') end for il=1:(sigmax-1)/3:sigmax xa = il*(0:0.001:1); ya = il*sqrt(1.-(0:0.001:1).*(0:0.001:1)); plot(xa,ya,':k') end % ------------------------------------ % ---- Draw tick marks (on the circle) % ------------------------------------ % *** Main Ticks *** + Correlation labels + 'Correlation' title for i=1:length(rlabticval) r = rlabticval(i); ticx(1) = sigmax*r; ticy(1) = sigmax*sqrt(1.0 - r*r); ticx(2) = (sigmax*(1.-rticlen))*r; ticy(2) = (sigmax*(1.-rticlen))*sqrt(1.0 - r*r); plot(ticx,ticy,'k') % Tick Labels val = 1.02; % default = 0.015 text((sigmax*val)*r,(sigmax*val)*sqrt(1.0 - r*r),rticlabels(i,:),'Fontsize',axcsiz) end % *** 'Correlation' title *** val = 1.1; % default = 0.1 for i=1:size(corrt,1) r=0.575+(i-1)*((0.825-0.575)/11); text((sigmax*val)*r,(sigmax*val)*sqrt(1.0 - r*r),corrt(i,:),... 'Fontsize',axcsiz,... 'Rotation',-((pi/2)-acos(r))*180/pi) end % *** Minor Ticks *** for i=1:length(rminticval) r = rminticval(i); ticx(1) = sigmax*r; ticy(1) = sigmax*sqrt(1.0 - r*r); ticx(2) = (sigmax*(1.-minortic))*r; ticy(2) = (sigmax*(1.-minortic))*sqrt(1.0 - r*r); plot(ticx,ticy,'k') end % *** Sub minor Ticks *** for i=1:length(rsubticval) r = rsubticval(i); ticx(1) = sigmax*r; ticy(1) = sigmax*sqrt(1.0 - r*r); ticx(2) = (sigmax*(1.-subtic))*r; ticy(2) = (sigmax*(1.-subtic))*sqrt(1.0 - r*r); plot(ticx,ticy,'k') end % ------------------------------------ % ---- Draw Results % ------------------------------------ % Loop over the number of experiments % AXY: the data is plotted twice so that it appears on top of all of % the plot's "scaffolding"; otherwise the plot symbols could be % obscured by the various lines that are plotted after the first % set of data plot instructions % -- Plot reference h = plot (1, 0, 'o', 'MarkerSize', 6, 'LineWidth', 2, ... 'MarkerEdgeColor', [1 0 0], 'MarkerFaceColor', [0 0 0]); % -- Plot data for i1=1:length(tsig) xx = (tsig(i1)/rsig(1))*tcorr(i1); yy = (tsig(i1)/rsig(1))*sqrt(1.-tcorr(i1)*tcorr(i1)); h=plot(xx,yy,marker(i1,1),'MarkerSize',6,'Linewidth',2); if flag_bounds(i1) == 0 set(h, 'Color', pal(i1,:)); else set(h, 'Color', [0 0 0]); end end % -- Draw legend % val = 1.05; % axis ([0 (sigmax*val) 0 (sigmax*val)]); % for i1=1:length(tsig) % xx = sigmax * val; % yy = sigmax - ((i1-1)*0.05*sigmax); % if ((nargin > 4) & (~isempty(name_experiment))) % h=plot(xx,yy,marker(i1,1),... % 'MarkerSize',8,'Linewidth',2.5); % set(h, 'Color', pal(i1,:)); % text(xx+0.06,yy,name_experiment(i1,:),'Fontsize',axcsiz) % end % end % AXY: because of the way that data is now plotted, it's possible to % use a normal Matlab legend to show the data h1 = legend(name_experiment, 0); set(h1, 'FontSize', 6); pos = get(h1, 'Position'); % sort out horizontal position of legend box pos(1) = 0.78; % sort out vertical position of legend box pos(2) = 0.99 - pos(4); set(h1, 'Position', pos); % h2 = get(h1, 'Children'); % set(h2(1)) % lt = length(tsig); % for i = 1:1:lt % j = ((i-1)*2)+1; % % set(h2(j+1), 'LineStyle', '.'); % set(h2(j), 'Marker', marker(lt+1-i,1)); % set(h2(j), 'Color', pal(lt+1-i,:)); % set(h2(j), 'MarkerSize', 8, 'Linewidth', 2.5); % end % AXY: shunt graph slightly sideways to left pos = get(gca, 'Position'); if pos(1) < 0.2, pos(1) = 0.05; set(gca, 'Position', pos); end plt = gca; leg = h1; % ------------------------------------ % ---- Title % ------------------------------------ if (nargin > 5) title(maintit,'Fontsize',axcsiz) end % ------------------------------------ % ---- Print eps file % ------------------------------------ if (out==2) set(gcf, 'PaperType', 'A4'); set(gcf, 'PaperOrientation', 'portrait'); set(gcf, 'PaperUnits', 'inches'); set(gcf, 'PaperPosition', [0.8353 3.3765 6.5882 4.9412]); end
github
eulertech/DeepLearningCrudeOilForecast-master
jdqr.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/jdqr.m
73,068
utf_8
b45810ddb5b2767c9289909175d1dc04
function varargout=jdqr(varargin) %JDQR computes a partial Schur decomposition of a square matrix or operator. % Lambda = JDQR(A) returns the absolute largest eigenvalues in a K vector % Lambda. Here K=min(5,N) (unless K has been specified), where N=size(A,1). % JDQR(A) (without output argument) displays the K eigenvalues. % % [X,Lambda] = JDQR(A) returns the eigenvectors in the N by K matrix X and % the eigenvalues in the K by K diagonal matrix Lambda. Lambda contains the % Jordan structure if there are multiple eigenvalues. % % [X,Lambda,HISTORY] = JDQR(A) returns also the convergence history % (that is, norms of the subsequential residuals). % % [X,Lambda,Q,S] = JDQR(A) returns also a partial Schur decomposition: % S is an K by K upper triangular matrix and Q is an N by K orthonormal matrix % such that A*Q = Q*S. The diagonal elements of S are eigenvalues of A. % % [X,Lambda,Q,S,HISTORY] = JDQR(A) returns also the convergence history. % % [X,Lambda,HISTORY] = JDQR('Afun') % [X,Lambda,HISTORY] = JDQR('Afun',N) % The first input argument is either a square matrix (which can be % full or sparse, symmetric or nonsymmetric, real or complex), or a % string containing the name of an M-file which applies a linear % operator to a given column vector. In the latter case, the M-file must % return the the order N of the problem with N = Afun([],'dimension') or % N must be specified in the list of input arguments. % For example, EIGS('fft',...) is much faster than EIGS(F,...) % where F is the explicit FFT matrix. % % The remaining input arguments are optional and can be given in % practically any order: % ... = JDQR(A,K,SIGMA,OPTIONS) % ... = JDQR('Afun',K,SIGMA,OPTIONS) % where % % K An integer, the number of eigenvalues desired. % SIGMA A scalar shift or a two letter string. % OPTIONS A structure containing additional parameters. % % With one output argument, S is a vector containing K eigenvalues. % With two output arguments, S is a K-by-K upper triangular matrix % and Q is a matrix with K columns so that A*Q = Q*S and Q'*Q=I. % With three output arguments, HISTORY contains the convergence history. % % If K is not specified, then K = MIN(N,5) eigenvalues are computed. % % If SIGMA is not specified, then the K-th eigenvalues largest in magnitude % are computed. If SIGMA is zero, then the K-th eigenvalues smallest in % magnitude are computed. If SIGMA is a real or complex scalar then the % K-th eigenvalues nearest SIGMA are computed. If SIGMA is one of the % following strings, then it specifies the desired eigenvalues. % % SIGMA Location wanted eigenvalues % % 'LM' Largest Magnitude (the default) % 'SM' Smallest Magnitude (same as sigma = 0) % 'LR' Largest Real part % 'SR' Smallest Real part % 'BE' Both Ends. Computes k/2 eigenvalues % from each end of the spectrum (one more % from the high end if k is odd.) % % % The OPTIONS structure specifies certain parameters in the algorithm. % % Field name Parameter Default % % OPTIONS.Tol Convergence tolerance: 1e-8 % norm(A*Q-Q*S,1) <= tol * norm(A,1) % OPTIONS.jmin minimum dimension search subspace k+5 % OPTIONS.jmax maximum dimension search subspace jmin+5 % OPTIONS.MaxIt Maximum number of iterations. 100 % OPTIONS.v0 Starting space ones+0.1*rand % OPTIONS.Schur Gives schur decomposition 'no' % also in case of 2 or 3 output % arguments (X=Q, Lambda=R). % % OPTIONS.TestSpace For using harmonic Ritz values 'Standard' % If 'TestSpace'='Harmonic' then % sigma=0 is the default value for SIGMA % % OPTIONS.Disp Shows size of intermediate residuals 1 % and displays the appr. eigenvalues. % % OPTIONS.LSolver Linear solver 'GMRES' % OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,.. % OPTIONS.LS_MaxIt Maximum number it. linear solver 5 % OPTIONS.LS_ell ell for BiCGstab(ell) 4 % % OPTIONS.Precond Preconditioner LU=[[],[]]. % % For instance % % OPTIONS=STRUCT('Tol',1.0e-10,'LSolver','BiCGstab','LS_ell',2,'Precond',M); % % changes the convergence tolerance to 1.0e-10, takes BiCGstab(2) as linear % solver and the preconditioner defined in M.m if M is the string 'M', % or M = L*U if M is an n by 2*n matrix: M = [L,U]. % % The preconditoner can be specified in the OPTIONS structure, % but also in the argument list: % ... = JDQR(A,K,SIGMA,M,OPTIONS) % ... = JDQR(A,K,SIGMA,L,U,OPTIONS) % ... = JDQR('Afun',K,SIGMA,'M',OPTIONS) % ... = JDQR('Afun',K,SIGMA,'L','U',OPTIONS) % as an N by N matrix M (then M is the preconditioner), or an N by 2*N % matrix M (then L*U is the preconditioner, where M = [L,U]), % or as N by N matrices L and U (then L*U is the preconditioner), % or as one or two strings containing the name of M-files ('M', or % 'L' and 'U') which apply a linear operator to a given column vector. % % JDQR (without input arguments) lists the options and the defaults. % Gerard Sleijpen. % Copyright (c) 98 % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology global Qschur Rschur PinvQ Pinv_u Pu nm_operations if nargin==0, possibilities, return, end %%% Read/set parameters [n,nselect,sigma,SCHUR,... jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV0,t_tol,... lsolver,LSpar] = ReadOptions(varargin{1:nargin}); LSpar0=LSpar; JDV=0; tol0=tol; LOCK0=~ischar(sigma); if nargout>3, SCHUR=0; end tau=0; if INTERIOR>=1 & LOCK0, tau=sigma(1); end n_tar=size(sigma,1); nt=1; FIG=gcf; %%% Initiate global variables Qschur = zeros(n,0); Rschur = []; PinvQ = zeros(n,0); Pinv_u = zeros(n,1); Pu = []; nm_operations = 0; history = []; %%% Return if eigenvalueproblem is trivial if n<2 if n==1, Qschur=1; Rschur=MV(1); end if nargout == 0, eigenvalue=Rschur, else [varargout{1:nargout}]=output(history,Qschur,Rschur); end, return, end String = ['\r#it=%i #MV=%i dim(V)=%i |r_%i|=%6.1e ']; StrinP = '--- Checking for conjugate pair ---\n'; time = clock; %%% Initialize V, W: %%% V,W orthonormal, A*V=W*R+Qschur*E, R upper triangular [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol); j=size(V,2); k=size(Rschur,1); nit=0; nlit=0; SOLVED=0; switch INTERIOR case 0 %%% The JD loop (Standard) %%% V orthogonal, V orthogonal to Qschur %%% V*V=eye(j), Qschur'*V=0, %%% W=A*V, M=V'*W %%% W=W*R; if tau ~=0; W=W+tau*V; end, M=M'*R; temptarget=sigma(nt,:); while (k<nselect) & (nit < maxit) %%% Compute approximate eigenpair and residual [UR,S]=SortSchur(M,temptarget,j==jmax,jmin); y=UR(:,1); theta=S(1,1); u=V*y; w=W*y; r=w-theta*u; [r,s]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1; if LOCK0 & nr<t_tol, temptarget=[theta;sigma(nt,:)]; end % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defekt',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, LOCK = LOCK0 & nr<t_tol; %%% if MovieTheta(n,nit,diag(S),jmin,sigma(nt,:),LOCK,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,s;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1, [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end W=W*R; if tau ~=0; W=W+tau*V; end; M=M'*R; j=size(V,2); else, J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, temptarget=conj(theta); if SHOW, fprintf(StrinP), end else, nlit=0; nt=min(nt+1,n_tar); temptarget=sigma(nt,:); end end % nr<tol %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end % if r_KNOWN if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS([Qschur,V],v); if size(v,2)>0 w=MV(v); M=[M,V'*w;v'*W,v'*w]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end % if EXPAND end % while (nit<maxit) case 1 %%% The JD loop (Harmonic Ritz values) %%% Both V and W orthonormal and orthogonal w.r.t. Qschur %%% V*V=eye(j), Qschur'*V=0, W'*W=eye(j), Qschur'*W=0 %%% (A*V-tau*V)=W*R+Qschur*E, E=Qschur'*(A*V-tau*V), M=W'*V %%% temptarget=0; FIXT=1; lsolver0=lsolver; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin); y=UR(:,1); theta=T(1,1)'*S(1,1); u=V*y; w=W*(R*y); r=w-theta*u; nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,E*y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; JDV=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1, [V,W,R,E,M]=... SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end, j=size(V,2); else J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J); R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; [r,a]=RepGS(u,r,0); E=[E*UR;(T(1,1)'-a/S(1,1))*S(1,J)]; s=(S(1,J)/S(1,1))/R; W=W+r*s; M=M+s'*(r'*V); if (nr*norm(s))^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, if SHOW, fprintf(StrinP), end temptarget=[conj(theta)-tau;0]; else, nlit=0; temptarget=0; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau; [W,R]=qr(W*R+tau0*V,0); M=W'*V; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J); R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; E=E*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation if JDV, disp('Stagnation'), LSpar(end-1)=(LSpar(end-1)+15)*2; % lsolver='bicgstab'; LSpar=[1.e-2,300,4]; else LSpar=LSpar0; JDV=0; lsolver=lsolver0; end if nr>0.001 & FIXT, theta=tau; else, FIXT=0; end v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; SOLVED=1; JDV=0; end if EXPAND %%% Expand the subspaces of the interaction matrix [v,zeta]=RepGS([Qschur,V],v); if JDV0 & abs(zeta(end,1))/norm(zeta)<0.06, JDV=JDV+1; end if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v; end [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); R=[[R;zeros(1,j)],y]; M=[M,W'*v;w'*V,w'*v]; E=[E,e]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) case 1.1 %%% The JD loop (Harmonic Ritz values) %%% V W AV. %%% Both V and W orthonormal and orthogonal w.r.t. Qschur, AV=A*V-tau*V %%% V*V=eye(j), W'*W=eye(j), Qschur'*V=0, Qschur'*W=0, %%% (I-Qschur*Qschur')*AV=W*R, M=W'*V; R=W'*AV; %%% AV=W*R; temptarget=0; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin); y=UR(:,1); u=V*y; w=AV*y; theta=u'*w; r=w-theta*u; [r,y]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2,Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1 [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end AV=W*R; j=size(V,2); else J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J); AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND,if SHOW, fprintf(StrinP), end temptarget=[conj(theta)-tau;0]; else, nlit=0; temptarget=0; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau; AV=AV+tau0*V; [W,R]=qr(W*R+tau0*V,0); M=W'*V; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J); AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS([Qschur,V],v); if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v;end AV=[AV,w]; R=[R,W'*w]; w=RepGS([Qschur,W],w); R=[R;w'*AV]; M=[M,W'*v;w'*V,w'*v]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) case 1.2 %%% The JD loop (Harmonic Ritz values) %%% W orthonormal, V and W orthogonal to Qschur, %%% W'*W=eye(j), Qschur'*V=0, Qschur'*W=0 %%% W=(A*V-tau*V)-Qschur*E, E=Qschur'*(A*V-tau*V), %%% M=W'*V V=V/R; M=M/R; temptarget='LM'; E=E/R; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,S]=SortSchur(M,temptarget,j==jmax,jmin); y=UR(:,1); u=V*y; nrm=norm(u); y=y/nrm; u=u/nrm; theta=S(1,1)'/(nrm*nrm); w=W*y; r=w-theta*u; nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[S(1,1);inf]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, Lambda=1./diag(S)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; y=E*y; Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1 [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end V=V/R; j=size(V,2); M=M/R; E=E/R; else J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; [r,a]=RepGS(u,r,0); s=u'*V; V=V-u*s; W=W-r*s; M=M-s'*(r'*V)-(W'*u)*s; E=[E*UR-y*s;(tau-theta-a)*s]; if (nr*norm(s))^2>eps, [W,R]=qr(W,0); V=V/R; M=(R'\M)/R; E=E/R; end end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, if SHOW, fprintf(StrinP), end temptarget=[1/(conj(theta)-tau);inf]; else, nlit=0; temptarget='LM'; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); [W,R]=qr(W+(tau0-tau)*V,0); V=V/R; M=W'*V; E=E/R; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; E=E*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS(Qschur,v,0); if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v; end [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); nrw=y(j+1,1); y=y(1:j,:); v=v-V*y; v=v/nrw; e=e-E*y; e=e/nrw; M=[M,W'*v;w'*V,w'*v]; V=[V,v]; W=[W,w]; j=j+1; E=[E,e]; if 1/cond(M)<10*tol [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E); k=size(Rschur,1); if k>=nselect, break, end V=V/R; M=M/R; j=size(V,2);temptarget='LM'; E=E/R; end EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) end % case time_needed=etime(clock,time); Refine([Qschur,V],1);% 2-SCHUR); CheckSortSchur(sigma); Lambda=[]; X=zeros(n,0); if ~SCHUR & k>0, [z,Lambda]=Jordan(Rschur); X=Qschur*z; end %-------------- display results ---------------------------- if SHOW == 2, MovieTheta, figure(FIG), end if SHOW & size(history,1)>0 switch INTERIOR case 0 testspace='V, V orthonormal'; case 1 testspace='A*V-sigma*V, V and W orthonormal'; case 1.1 testspace='A*V-sigma*V, V and W orthonormal, AV'; case 1.2 testspace='A*V-sigma*V, W orthogonal'; otherwise testspace='Experimental'; end StringT=sprintf('The test subspace W is computed as W = %s.',testspace); StringX=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',... jmin,jmax,tol); StringY=sprintf('Correction equation solved with %s.',lsolver); date=fix(clock); String=sprintf('\n%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6)); StringL='log_{10} || r_{#it} ||_2'; for pl=1:SHOW subplot(SHOW,1,pl), t=history(:,pl+1); plot(t,log10(history(:,1)),'*-',t,log10(tol)+0*t,':') legend(StringL), title(StringT) StringL='log_{10} || r_{#MV} ||_2'; StringT=StringX; end if SHOW==2, xlabel([StringY,String]) else, xlabel([StringX,String]), ylabel(StringY), end drawnow end if SHOW str1=num2str(abs(k-nselect)); str='s'; if k>nselect, if k==nselect+1, str1='one'; str=''; end fprintf('\n\nDetected %s additional eigenpair%s.',str1,str) end if k<nselect, if k==0, str1='any'; str=''; elseif k==nselect-1, str1='one'; str=''; end fprintf('\n\nFailed detection of %s eigenpair%s.',str1,str) end if k>0, ShowLambda(diag(Rschur)); else, fprintf('\n'); end Str='time_needed'; DispResult(Str,eval(Str)) if (k>0) if ~SCHUR Str='norm(MV(X)-X*Lambda)'; DispResult(Str,eval(Str)) end Str='norm(MV(Qschur)-Qschur*Rschur)'; DispResult(Str,eval(Str)) I=eye(k); Str='norm(Qschur''*Qschur-I)'; DispResult(Str,eval(Str)) end fprintf('\n\n') end if nargout == 0, if ~SHOW, eigenvalues=diag(Rschur), end, return, end [varargout{1:nargout}]=output(history,X,Lambda); return %=========================================================================== %======= PREPROCESSING ===================================================== %=========================================================================== %======= INITIALIZE SUBSPACE =============================================== function [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E); %[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol); % Output: V(:,1:SIZE(VV,2))=ORTH(VV), % V'*V=W'*W=EYE(JMIN), M=W'*V; % such that A*V-tau*V=W*R+Qschur*E, % with R upper triangular, and E=Qschur'*(A*V-tau*V). % %[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol,AV,EE); % Input such that % A*VV-tau*VV=AV+Qschur*EE, EE=Qschur'*(A*VV-tau*VV); % % Output: V(:,1:SIZE(VV,2))=ORTH(VV), % V'*V=W'*W=EYE(JMIN), M=W'*V; % such that A*V-tau*V=W*R+Qschur*E, % with R upper triangular, and E=Qschur'*(A*V-tau*V). global Qschur Rschur [n,j]=size(V); k=size(Qschur,2); if j>1, [V,R]=qr(V,0); if nargin <6, W=MV(V); R=eye(j); if tau~=0, W=W-tau*V; end if k>0, E=Qschur'*W; W=W-Qschur*E; else, E=zeros(0,j); end end [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,R); l=size(Qschur,2); j=size(V,2); if l>=nselect, if size(V,2)==0; R=1; M=1; return, end, end if l>k, UpdateMinv(Qschur(:,k+1:l),0); end, k=l; end if j==0, nr=0; while nr==0 V = ones(n,1)+0.1*rand(n,1); V=RepGS(Qschur,V); nr=norm(V); end, j=1; end if j==1 [V,H,E]=Arnoldi(V,tau,jmin,nselect,tol); l=size(Qschur,2); j=max(size(H,2),1); if l>=nselect, W=V; R=eye(j); M=R; return, end if l>k, UpdateMinv(Qschur(:,k+1:l),0); end [Q,R]=qr(full(H),0); W=V*Q; V(:,j+1)=[]; M=Q(1:j,:)'; %% W=V*Q; V=V(:,1:j)/R; E=E/R; R=eye(j); M=Q(1:j,:)'/R; %% W=V*H; V(:,j+1)=[];R=R'*R; M=H(1:j,:)'; end return %%%======== ARNOLDI (for initializing spaces) =============================== function [V,H,E]=Arnoldi(v,tau,jmin,nselect,tol) % %[V,AV,H,nMV,tau]=ARNOLDI(A,V0,TAU,JMIN,NSELECT,TOL) % ARNOLDI computes the Arnoldi factorization of dimenison JMIN+1: % (A-tau)*V(:,1:JMIN)=V*H where V is n by JMIN+1 orthonormal with % first column a multiple of V0, and H is JMIN+1 by JMIN Hessenberg. % % If an eigenvalue if H(1:j,1:j) is an eigenvalue of A % within the required tolerance TOL then the Schurform % A*Qschur=Qschur*Rschur is expanded and the Arnoldi factorization % (A-tau)*V(:,1:j)=V(:,1:j+1)*H(1:j+1,1:j) is deflated. % Returns if size(Qschur,2) = NSELECT or size(V,2) = JMIN+1 % (A-tau)*V(:,1:JMIN)=V*H+Qschur*E, Qschur'*V=0 % Coded November 5, 1998, G. Sleijpen global Qschur Rschur k=size(Qschur,2); [n,j]=size(v); if ischar(tau), tau=0; end H=zeros(1,0); V=zeros(n,0); E=[]; j=0; nr=norm(v); while j<jmin & k<nselect & j+k<n if nr>=tol v=v/nr; V=[V,v]; j=j+1; Av=MV(v); end if j==0 H=zeros(1,0); j=1; nr=0; while nr==0, v=RepGS(Qschur,rand(n,1)); nr=norm(v); end v=v/nr; V=v; Av=MV(v); end if tau~=0; Av=Av-tau*v; end, [v,e] = RepGS(Qschur,Av,0); if k==0, E=zeros(0,j); else, E = [E,e(1:k,1)]; end [v,y] = RepGS(V,v,0); H = [H,y(1:j,1)]; nr = norm(v); H = [H;zeros(1,j-1),nr]; [Q,U,H1] = DeflateHess(full(H),tol); j=size(U,2); l=size(Q,2); if l>0 %--- expand Schur form ------ Qschur=[Qschur,V*Q]; Rschur=[Rschur,E*Q; zeros(l,k),H1(1:l,1:l)+tau*eye(l)]; k=k+l; E=[E*U;H1(1:l,l+1:l+j)]; if j>0, V=V*U; H=H1(l+1:l+j+1,l+1:l+j); else, V=zeros(n,0); H=zeros(1,0); end end end % while if nr>=tol v=v/nr; V=[V,v]; end return %---------------------------------------------------------------------- function [Q,U,H]=DeflateHess(H,tol) % H_in*[Q,U]=[Q,U]*H_out such that H_out(K,K) upper triangular % where K=1:SIZE(Q,2) and ABS(Q(end,2)*H_in(j+1,j))<TOL, j=SIZE(H,2), [j1,j]=size(H); if j1==j, [Q,H]=schur(H); U=zeros(j,0); return, end nr=H(j+1,j); U=eye(j); i=1; J=i:j; for l=1:j [X,Lambda]=eig(H(J,J)); I=find(abs(X(size(X,1),:)*nr)<tol); if isempty(I), break, end q=X(:,I(1)); q=q/norm(q); q(1,1)=q(1,1)+sign(q(1,1)); q=q/norm(q); H(:,J)=H(:,J)-(2*H(:,J)*q)*q'; H(J,:)=H(J,:)-2*q*(q'*H(J,:)); U(:,J)=U(:,J)-(2*U(:,J)*q)*q'; i=i+1; J=i:j; end [Q,HH]=RestoreHess(H(i:j+1,J)); H(:,J)=H(:,J)*Q; H(J,:)=Q'*H(J,:); U(:,J)=U(:,J)*Q; Q=U(:,1:i-1); U=U(:,i:j); return %---------------------------------------------------------------------- function [Q,M]=RestoreHess(M) [j1,j2]=size(M); Q=eye(j2); for j=j1:-1:2 J=1:j-1; q=M(j,J)'; q=q/norm(q); q(j-1,1)=q(j-1,1)+sign(q(j-1,1)); q=q/norm(q); M(:,J)=M(:,J)-2*(M(:,J)*q)*q'; M(J,:)=M(J,:)-2*q*q'*M(J,:); Q(:,J)=Q(:,J)-2*Q(:,J)*q*q'; end return %%%=========== END ARNOLDI ============================================ function [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,Rv); % V,W orthonormal, A*V-tau*V=W*R+Qschur'*E global Qschur Rschur k=size(Rschur,1); j=size(V,2); [W,R]=qr(W,0); E=E/Rv; R=R/Rv; M=W'*V; %%% not accurate enough M=Rw'\(M/Rv); if k>=nselect, return, end CHECK=1; l=k; [S,T,Z,Q]=qz(R,M); Z=Z'; while CHECK I=SortEigPairVar(S,T,2); [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1)); s=abs(S(1,1)); t=min(abs(T(1,1)),1); CHECK=(s*sqrt(1-t*t)<tol); if CHECK V=V*Q; W=W*Z; E=E*Q; u=V(:,1); [r,a]=RepGS(u,(W(:,1)-T(1,1)'*u)*S(1,1),0); Qschur=[Qschur,u]; t=(T(1,1)'-a/S(1,1))*S(1,:); Rschur=[Rschur,E(:,1);zeros(1,k),tau+t(1,1)]; k=k+1; J=[2:j]; j=j-1; V=V(:,J); W=W(:,J); E=[E(:,J);t(1,J)]; s=S(1,J)/S(1,1); R=S(J,J); M=T(J,J); Q=eye(j); Z=eye(j); s=s/R; nrs=norm(r)*norm(s); if nrs>=tol, W=W+r*s; M=M+s'*(r'*V); if nrs^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end end S=R; T=M; CHECK=(k<nselect & j>0); end end return %=========================================================================== %======= POSTPROCESSING ==================================================== %=========================================================================== function Refine(V,gamma); if gamma==0, return, end global Qschur Rschur J=1:size(Rschur,1); if gamma==1, [V,R]=qr(V(:,J),0); W=MV(V); M=V'*W; [U,Rschur]=schur(M); [U,Rschur]=rsf2csf(U,Rschur); Qschur=V*U; return elseif gamma==2 [V,R]=qr(V,0); W=MV(V); M=V'*W; [U,S]=schur(M); [U,S]=rsf2csf(U,S); R=R*U; F=R'*R-S'*S; [X,Lambda]=Jordan(S); % Xinv=inv(X); D=sqrt(diag(Xinv*Xinv')); X=X*diag(D); [d,I]=sort(abs(diag(X'*F*X))); [U,S]=SwapSchur(U,S,I(J)); Qschur=V*U(:,J); Rschur=S(J,J); end return %=========================================================================== function CheckSortSchur(sigma) global Qschur Rschur k=size(Rschur,1); if k==0, return, end I=SortEig(diag(Rschur),sigma); if ~min((1:k)'==I) [U,Rschur]=SwapSchur(eye(k),Rschur,I); Qschur=Qschur*U; end return %%%=========== COMPUTE SORTED JORDAN FORM ================================== function [X,Jordan]=Jordan(S) % [X,J]=JORDAN(S) % For S k by k upper triangular matrix with ordered diagonal elements, % JORDAN computes the Jordan decomposition. % X is a k by k matrix of vectors spanning invariant spaces. % If J(i,i)=J(i+1,i+1) then X(:,i)'*X(:,i+1)=0. % J is a k by k matrix, J is Jordan such that S*X=X*J. % diag(J)=diag(S) are the eigenvalues % coded by Gerard Sleijpen, Januari 14, 1998 k=size(S,1); X=zeros(k); if k==0, Jordan=[]; return, end %%% accepted separation between eigenvalues: delta=2*sqrt(eps)*norm(S,inf); delta=max(delta,10*eps); T=eye(k); s=diag(S); Jordan=diag(s); for i=1:k I=[1:i]; e=zeros(i,1); e(i,1)=1; C=S(I,I)-s(i,1)*T(I,I); C(i,i)=1; j=i-1; q=[]; jj=0; while j>0 if abs(C(j,j))<delta, jj=jj+1; j=j-1; else, j=0; end end q=X(I,i-jj:i-1); C=[C,T(I,I)*q;q',zeros(jj)]; q=C\[e;zeros(jj,1)]; nrm=norm(q(I,1)); Jordan(i-jj:i-1,i)=-q(i+1:i+jj,1)/nrm; X(I,i)=q(I,1)/nrm; end return %========== OUTPUT ========================================================= function varargout=output(history,X,Lambda) global Qschur Rschur if nargout == 1, varargout{1}=diag(Rschur); return, end if nargout > 2, varargout{nargout}=history; end if nargout > 3, varargout{3} = Qschur; varargout{4} = Rschur; end if nargout < 4 & size(X,2)<2 varargout{1}=Qschur; varargout{2}=Rschur; return else varargout{1}=X; varargout{2}=Lambda; end return %=========================================================================== %===== UPDATE PRECONDITIONED SCHUR VECTORS ================================= %=========================================================================== function solved=UpdateMinv(u,solved) global Qschur PinvQ Pinv_u Pu L_precond if ~isempty(L_precond) if ~solved, Pinv_u=SolvePrecond(u); end Pu=[[Pu;u'*PinvQ],Qschur'*Pinv_u]; PinvQ=[PinvQ,Pinv_u]; solved=0; end return %=========================================================================== %===== SOLVE CORRECTION EQUATION =========================================== %=========================================================================== function t=Solve_pce(theta,u,r,lsolver,par,nit) global Qschur PinvQ Pinv_u Pu L_precond switch lsolver case 'exact' t = exact(theta,[Qschur,u],r); case 'iluexact' t = iluexact(theta,[Qschur,u],r); case {'gmres','bicgstab','olsen'} if isempty(L_precond) %%% no preconditioning t = feval(lsolver,theta,... [Qschur,u],[Qschur,u],1,r,spar(par,nit)); else %%% solve left preconditioned system %%% compute vectors and matrices for skew projection Pinv_u=SolvePrecond(u); mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u]; %%% precondion and project r r=SolvePrecond(r); r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r); %%% solve preconditioned system t = feval(lsolver,theta,... [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit)); end case {'cg','minres','symmlq'} if isempty(L_precond) %%% no preconditioning t = feval(lsolver,theta,... [Qschur,u],[Qschur,u],1,r,spar(par,nit)); else %%% solve two-sided expl. precond. system %%% compute vectors and matrices for skew projection Pinv_u=SolvePrecond(u,'L'); mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u]; %%% precondion and project r r=SolvePrecond(r,'L'); r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r); %%% solve preconditioned system t = feval(lsolver,theta,... [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit)); %%% "unprecondition" solution t=SkewProj([PinvQ,Pinv_u],[Qschur,u],mu,t); t=SolvePrecond(t,'U'); end end return %======================================================================= %======= LINEAR SOLVERS ================================================ %======================================================================= function x = exact(theta,Q,r) global A_operator [n,k]=size(Q); [n,l]=size(r); if ischar(A_operator) [x,xtol]=bicgstab(theta,Q,Q,1,r,[5.0e-14/norm(r),200,4]); return end x = [A_operator-theta*speye(n,n),Q;Q',zeros(k,k)]\[r;zeros(k,l)]; x = x(1:n,1:l); return %---------------------------------------------------------------------- function x = iluexact(theta,Q,r) global L_precond U_precond [n,k]=size(Q); [n,l]=size(r); y = L_precond\[r,Q]; x = [U_precond,y(:,l+1:k+1);Q',zeros(k,k)]\[y(:,1:l);zeros(k,l)]; x = x(1:n,1:l); return %---------------------------------------------------------------------- function r = olsen(theta,Q,Z,M,r,par) return % %======= Iterative methods ============================================= % function x = bicgstab(theta,Q,Z,M,r,par) % BiCGstab(ell) % [x,rnrm] = bicgstab(theta,Q,Z,M,r,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % This function is specialized for use in JDQZ. % integer nmv: number of matrix multiplications % rnrm: relative residual norm % % par=[tol,mxmv,ell] where % integer m: max number of iteration steps % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: ETNA % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization -- % tol=par(1); max_it=par(2); l=par(3); n=size(r,1); rnrm=1; nmv=0; if max_it==0 | tol>=1, x=r; return, end rnrm=norm(r); snrm=rnrm; tol=tol*rnrm; sigma=1; omega=1; x=zeros(n,1); u=zeros(n,1); tr=r; % hist=rnrm; % -- Iteration loop while (rnrm > tol) & (nmv <= max_it) sigma=-omega*sigma; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; %%%%%% u(:,j+1)=Atilde*u(:,j) u(:,j+1)=mvp(theta,Q,Z,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; x=x+alp*u(:,1); r=r-alp*u(:,2:j+1); %%%%%% r(:,j+1)=Atilde*r(:,j) r(:,j+1)=mvp(theta,Q,Z,M,r(:,j)); end gamma=r(:,2:l+1)\r(:,1); omega=gamma(l,1); x=x+r*[gamma;0]; u=u*[1;-gamma]; r=r*[1;-gamma]; rnrm = norm(r); nmv = nmv+2*l; % hist=[hist,rnrm]; end % figure(3), % plot([0:length(hist)-1]*2*l,log10(hist/snrm),'-*'), % drawnow, rnrm = rnrm/snrm; return %---------------------------------------------------------------------- function v = gmres(theta,Q,Z,M,v,par) % GMRES % [x,rnrm] = gmres(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Saad % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); n = size(v,1); max_it=min(par(2),n); rnrm = 1; nmv=0; if max_it==0 | tol>=1, return, end H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)]; rnrm = norm(v); v = v/rnrm; V = [v]; tol = tol * rnrm; snrm = rnrm; y = [ rnrm ; zeros(max_it,1) ]; j=0; % hist=rnrm; while (nmv < max_it) & (rnrm > tol), j=j+1; nmv=nmv+1; v=mvp(theta,Q,Z,M,v); % [v, H(1:j+1,j)] = RepGS(V,v); [v,h] = RepGS(V,v); H(1:size(h,1),j)=h; V = [V, v]; for i = 1:j-1, a = Rot(:,i); H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j); end J=[j, j+1]; a=H(J,j); if a(2) ~= 0 cs = norm(a); a = a/cs; Rot(:,j) = a; H(J,j) = [cs; 0]; y(J) = [a'; -a(2) a(1)]*y(J); end rnrm = abs(y(j+1)); % hist=[hist,rnrm]; end % figure(3) % plot([0:length(hist)-1],log10(hist/snrm),'-*') % drawnow, pause J=[1:j]; v = V(:,J)*(H(J,J)\y(J)); rnrm = rnrm/snrm; return %====================================================================== %========== BASIC OPERATIONS ========================================== %====================================================================== function v=MV(v) global A_operator nm_operations if ischar(A_operator) v = feval(A_operator,v); else v = A_operator*v; end nm_operations = nm_operations+1; return %---------------------------------------------------------------------- function v=mvp(theta,Q,Z,M,v) % v=Atilde*v v = MV(v) - theta*v; v = SolvePrecond(v); v = SkewProj(Q,Z,M,v); return %---------------------------------------------------------------------- function u=SolvePrecond(u,flag); global L_precond U_precond if isempty(L_precond), return, end if nargin<2 if ischar(L_precond) if ischar(U_precond) u=feval(L_precond,u,U_precond); elseif isempty(U_precond) u=feval(L_precond,u); else u=feval(L_precond,u,'L'); u=feval(L_precond,u,'U'); end else u=U_precond\(L_precond\u); end else switch flag case 'U' if ischar(L_precond), u=feval(L_precond,u,'U'); else, u=U_precond\u; end case 'L' if ischar(L_precond), u=feval(L_precond,u,'L'); else, u=L_precond\u; end end end return %---------------------------------------------------------------------- function r=SkewProj(Q,Z,M,r); if ~isempty(Q), r=r-Z*(M\(Q'*r)); end return %---------------------------------------------------------------------- function ppar=spar(par,nit) % Changes par=[tol(:),max_it,ell] to % ppap=[TOL,max_it,ell] where % if lenght(tol)==1 % TOL=tol % else % red=tol(end)/told(end-1); tole=tol(end); % tol=[tol,red*tole,red^2*tole,red^3*tole,...] % TOL=tol(nit); % end k=size(par,2)-2; ppar=par(1,k:k+2); if k>1 if nit>k ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k)); else ppar(1,1)=par(1,max(nit,1)); end end ppar(1,1)=max(ppar(1,1),1.0e-8); return % %======= Iterative methods for symmetric systems ======================= % function x = cg(theta,Q,Z,M,r,par) % CG % [x,rnrm] = cg(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Hestenes and Stiefel % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; b=r; if max_it ==0 | tol>=1, x=r; return, end x= zeros(n,1); u=zeros(n,1); rho = norm(r); snrm = rho; rho = rho*rho; tol = tol*tol*rho; sigma=1; while ( rho > tol & nmv < max_it ) beta=rho/sigma; u=r-beta*u; y=smvp(theta,Q,Z,M,u); nmv=nmv+1; sigma=y'*r; alpha=rho/sigma; x=x+alpha*u; r=r-alpha*y; sigma=-rho; rho=r'*r; end % while rnrm=sqrt(rho)/snrm; return %---------------------------------------------------------------------- function x = minres(theta,Q,Z,M,r,par) % MINRES % [x,rnrm] = minres(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Paige and Saunders % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; if max_it ==0 | tol>=1, x=r; return, end x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho; beta = 0; v_old = zeros(n,1); beta_t = 0; c = -1; s = 0; w = zeros(n,1); www = v; tol=tol*rho; while ( nmv < max_it & abs(rho) > tol ) wv =smvp(theta,Q,Z,M,v)-beta*v_old; nmv=nmv+1; alpha = v'*wv; wv = wv-alpha*v; beta = norm(wv); v_old = v; v = wv/beta; l1 = s*alpha - c*beta_t; l2 = s*beta; alpha_t = -s*beta_t - c*alpha; beta_t = c*beta; l0 = sqrt(alpha_t*alpha_t+beta*beta); c = alpha_t/l0; s = beta/l0; ww = www - l1*w; www = v - l2*w; w = ww/l0; x = x + (rho*c)*w; rho = s*rho; end % while rnrm=abs(rho)/snrm; return %---------------------------------------------------------------------- function x = symmlq(theta,Q,Z,M,r,par) % SYMMLQ % [x,rnrm] = symmlq(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Paige and Saunders % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; if max_it ==0 | tol>=1, x=r; return, end x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho; beta = 0; beta_t = 0; c = -1; s = 0; v_old = zeros(n,1); w = v; gtt = rho; g = 0; tol=tol*rho; while ( nmv < max_it & rho > tol ) wv = smvp(theta,Q,Z,M,v) - beta*v_old; nmv=nmv+1; alpha = v'*wv; wv = wv - alpha*v; beta = norm(wv); v_old = v; v = wv/beta; l1 = s*alpha - c*beta_t; l2 = s*beta; alpha_t = -s*beta_t - c*alpha; beta_t = c*beta; l0 = sqrt(alpha_t*alpha_t+beta*beta); c = alpha_t/l0; s = beta/l0; gt = gtt - l1*g; gtt = -l2*g; g = gt/l0; rho = sqrt(gt*gt+gtt*gtt); x = x + (g*c)*w + (g*s)*v; w = s*w - c*v; end % while rnrm=rho/snrm; return %---------------------------------------------------------------------- function v=smvp(theta,Q,Z,M,v) % v=Atilde*v v = SkewProj(Z,Q,M,v); v = SolvePrecond(v,'U'); v = MV(v) - theta*v; v = SolvePrecond(v,'L'); v = SkewProj(Q,Z,M,v); return %======================================================================= %========== Orthogonalisation ========================================== %======================================================================= function [v,y]=RepGS(V,v,gamma) % [v,y]=REP_GS(V,w) % If V orthonormal then [V,v] orthonormal and w=[V,v]*y; % If size(V,2)=size(V,1) then w=V*y; % % The orthonormalisation uses repeated Gram-Schmidt % with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion. % % [v,y]=REP_GS(V,w,GAMMA) % GAMMA=1 (default) same as [v,y]=REP_GS(V,w) % GAMMA=0, V'*v=zeros(size(V,2)) and w = V*y+v (v is not normalized). % coded by Gerard Sleijpen, August 28, 1998 if nargin < 3, gamma=1; end [n,d]=size(V); if size(v,2)==0, y=zeros(d,0); return, end nr_o=norm(v); nr=eps*nr_o; y=zeros(d,1); if d==0 if gamma, v=v/nr_o; y=nr_o; else, y=zeros(0,1); end, return end y=V'*v; v=v-V*y; nr_n=norm(v); ort=0; while (nr_n<0.5*nr_o & nr_n > nr) s=V'*v; v=v-V*s; y=y+s; nr_o=nr_n; nr_n=norm(v); ort=ort+1; end if nr_n <= nr, if ort>2, disp(' dependence! '), end if gamma % and size allows, expand with a random vector if d<n, v=RepGS(V,rand(n,1)); y=[y;0]; else, v=zeros(n,0); end else, v=0*v; end elseif gamma, v=v/nr_n; y=[y;nr_n]; end return %======================================================================= %============== Sorts Schur form ======================================= %======================================================================= function [Q,S]=SortSchur(A,sigma,gamma,kk) %[Q,S]=SortSchur(A,sigma) % A*Q=Q*S with diag(S) in order prescribed by sigma. % If sigma is a scalar then with increasing distance from sigma. % If sigma is string then according to string % ('LM' with decreasing modulus, etc) % %[Q,S]=SortSchur(A,sigma,gamma,kk) % if gamma==0, sorts only for the leading element % else, sorts for the kk leading elements l=size(A,1); if l<2, Q=1;S=A; return, elseif nargin==2, kk=l-1; elseif gamma, kk=min(kk,l-1); else, kk=1; sigma=sigma(1,:); end %%%------ compute schur form ------------- [Q,S]=schur(A); %% A*Q=Q*S, Q'*Q=eye(size(A)); %%% transform real schur form to complex schur form if norm(tril(S,-1),1)>0, [Q,S]=rsf2csf(Q,S); end %%%------ find order eigenvalues --------------- I = SortEig(diag(S),sigma); %%%------ reorder schur form ---------------- [Q,S] = SwapSchur(Q,S,I(1:kk)); return %---------------------------------------------------------------------- function I=SortEig(t,sigma); %I=SortEig(T,SIGMA) sorts the indices of T. % % T is a vector of scalars, % SIGMA is a string or a vector of scalars. % I is a permutation of (1:LENGTH(T))' such that: % if SIGMA is a vector of scalars then % for K=1,2,...,LENGTH(T) with KK = MIN(K,SIZE(SIGMA,1)) % ABS( T(I(K))-SIGMA(KK) ) <= ABS( T(I(J))-SIGMA(KK) ) % SIGMA(kk)=INF: ABS( T(I(K)) ) >= ABS( T(I(J)) ) % for all J >= K if ischar(sigma) switch sigma case 'LM' [s,I]=sort(-abs(t)); case 'SM' [s,I]=sort(abs(t)); case 'LR'; [s,I]=sort(-real(t)); case 'SR'; [s,I]=sort(real(t)); case 'BE'; [s,I]=sort(real(t)); I=twistdim(I,1); end else [s,I]=sort(abs(t-sigma(1,1))); ll=min(size(sigma,1),size(t,1)-1); for j=2:ll if sigma(j,1)==inf [s,J]=sort(abs(t(I(j:end)))); J=flipdim(J,1); else [s,J]=sort(abs(t(I(j:end))-sigma(j,1))); end I=[I(1:j-1);I(J+j-1)]; end end return %---------------------------------------------------------------------- function t=twistdim(t,k) d=size(t,k); J=1:d; J0=zeros(1,2*d); J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J); if k==1, t=t(I,:); else, t=t(:,I); end return %---------------------------------------------------------------------- function [Q,S]=SwapSchur(Q,S,I) % [Q,S]=SwapSchur(QQ,SS,P) % QQ and SS are square matrices of size K by K % P is the first part of a permutation of (1:K)'. % % If M = QQ*SS*QQ' and QQ'*QQ = EYE(K), SS upper triangular % then M*Q = Q*S with Q'*Q = EYE(K), S upper triangular % and D(1:LENGTH(P))=DD(P) where D=diag(S), DD=diag(SS) % % Computations uses Givens rotations. kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end; while j<=kk i=I(j); for k=i-1:-1:j q = [S(k,k)-S(k+1,k+1),S(k,k+1)]; if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; J = [k,k+1]; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; S(J,:) = G'*S(J,:); end S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %---------------------------------------------------------------------- function [Q,Z,S,T]=SortQZ(A,B,sigma,gamma,kk) % % [Q,Z,S,T]=SORTQZ(A,B,SIGMA) % A and B are K by K matrices, SIGMA is a complex scalar or string. % SORTQZ computes the qz-decomposition of (A,B) with prescribed % ordering: A*Q=Z*S, B*Q=Z*T; % Q and Z are K by K unitary, % S and T are K by K upper triangular. % The ordering is as follows: % (DAIG(S),DAIG(T)) are the eigenpairs of (A,B) ordered % as prescribed by SIGMA. % % coded by Gerard Sleijpen, version Januari 12, 1998 l=size(A,1); if l<2; Q=1; Z=1; S=A; T=B; return elseif nargin==3, kk=l-1; elseif gamma, kk=min(kk,l-1); else, kk=1; sigma=sigma(1,:); end %%%------ compute qz form ---------------- [S,T,Z,Q]=qz(A,B); Z=Z'; S=triu(S); %%%------ sort eigenvalues --------------- I=SortEigPair(diag(S),diag(T),sigma); %%%------ sort qz form ------------------- [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk)); return %---------------------------------------------------------------------- function I=SortEigPair(s,t,sigma) % I=SortEigPair(S,T,SIGMA) % S is a complex K-vectors, T a positive real K-vector % SIGMA is a string or a vector of pairs of complex scalars. % SortEigPair gives the index set I that sorts the pairs (S,T). % % If SIGMA is a pair of scalars then the sorting is % with increasing "chordal distance" w.r.t. SIGMA. % % The chordal distance D between a pair A and a pair B is defined as follows. % Scale A by a scalar F such that NORM(F*A)=1 and F*A(2)>=0, % scale B by a scalar G such that NORM(G*B)=1 and G*B(2)>=0, % then D(A,B)=ABS((F*A)*RROT(G*B)) where RROT(alpha,beta)=(beta,-alpha) % coded by Gerard Sleijpen, version Januari 14, 1998 n=sign(t); n=n+(n==0); t=abs(t./n); s=s./n; if ischar(sigma) switch sigma case {'LM','SM'} case {'LR','SR','BE'} s=real(s); end [s,I]=sort((-t./sqrt(s.*conj(s)+t.*t))); switch sigma case {'LM','LR'} I=flipdim(I,1); case {'SM','SR'} case 'BE' I=twistdim(I,1); end else n=sqrt(sigma.*conj(sigma)+1); ll=size(sigma,1); tau=[ones(ll,1)./n,-sigma./n]; tau=tau.'; n=sqrt(s.*conj(s)+t.*t); s=[s./n,t./n]; [t,I]=sort(abs(s*tau(:,1))); ll = min(ll,size(I,1)-1); for j=2:ll [t,J]=sort(abs(s(I(j:end),:)*tau(:,j))); I=[I(1:j-1);I(J+j-1)]; end end return %---------------------------------------------------------------------- function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I) % [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P) % QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular. % P is the first part of a permutation of (1:K)'. % % Then Q and Z are K by K unitary, S and T are K by K upper triangular, % such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have % A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where % LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT). % % Computation uses Givens rotations. % % coded by Gerard Sleijpen, version October 12, 1998 kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end while j<=kk i=I(j); for k = i-1:-1:j, %%% i>j, move ith eigenvalue to position j J = [k,k+1]; q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J); if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G; end if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end if q(2) ~= 0 q=q/norm(q); G = [q';q(2),-q(1)]; Z(:,J) = Z(:,J)*G'; S(J,:) = G*S(J,:); T(J,:) = G*T(J,:); end T(k+1,k) = 0; S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %======================================================================= %======= SET PARAMETERS ================================================ %======================================================================= function [n,nselect,sigma,SCHUR,... jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV,OLD,... lsolver,par] = ReadOptions(varargin) % Read options and set defaults global A_operator L_precond U_precond A_operator = varargin{1}; %%% determine dimension if ischar(A_operator) n=-1; if exist(A_operator) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',A_operator); errordlg(msg,'MATRIX'),n=-2; end if n==-1, eval('n=feval(A_operator,[],''dimension'');','n=-1;'), end else [n,n] = size(A_operator); if any(size(A_operator) ~= n) msg=sprintf(' The operator must be a square matrix or a string. '); errordlg(msg,'MATRIX'),n=-3; end end %%% defaults SCHUR = 0; jmin = -1; jmax = -1; p0 = 5; % jmin=nselect+p0 p1 = 5; % jmax=jmin+p1 tol = 1e-8; maxit = 200; V = zeros(0,0); INTERIOR= 0; SHOW = 0; PAIRS = 0; JDV = 0; OLD = 1e-4; lsolver = 'gmres'; ls_maxit= 200; ls_tol = [1,0.7]; ell = 4; par = [ls_tol,ls_maxit,ell]; options=[]; sigma=[]; varg=[]; L_precond = []; U_precond = []; for j = 2:nargin if isstruct(varargin{j}) options = varargin{j}; elseif ischar(varargin{j}) if length(varargin{j}) == 2 & isempty(sigma) sigma = varargin{j}; elseif isempty(L_precond) L_precond=varargin{j}; elseif isempty(U_precond) U_precond=varargin{j}; end elseif length(varargin{j}) == 1 varg = [varg,varargin{j}]; elseif min(size(varargin{j}))==1 sigma = varargin{j}; if size(sigma,1)==1, sigma=conj(sigma'); end elseif isempty(L_precond) L_precond=varargin{j}; elseif isempty(U_precond) U_precond=varargin{j}; end end if ischar(sigma) sigma0=sigma; sigma=upper(sigma); switch sigma case {'LM','LR','SR','BE','SM'} otherwise if exist(sigma0)==2 & isempty(L_precond) ok=1; eval('v=feval(sigma,zeros(n,1));','ok=0') if ok, L_precond=sigma0; sigma=[]; end end end end [s,I]=sort(varg); I=flipdim(I,2); J=[]; j=0; while j<length(varg) j=j+1; jj=I(j); s=varg(jj); if isreal(s) & (s == fix(s)) & (s > 0) if n==-1 n=s; eval('v=feval(A_operator,zeros(n,0));','n=-1;') if n>-1, J=[J,jj]; end end else if isempty(sigma), sigma=s; elseif ischar(sigma) & isempty(L_precond) ok=1; eval('v=feval(sigma0,zeros(n,1));','ok=0') if ok, L_precond=sigma0; sigma=s; end end, J=[J,jj]; end end varg(J)=[]; if n==-1, msg1=sprintf(' Cannot find the dimension of ''%s''. \n',A_operator); msg2=sprintf(' Put the dimension n in the parameter list: \n like'); msg3=sprintf('\t\n\n\t jdqr(''%s'',n,..), \n\n',A_operator); msg4=sprintf(' or let\n\n\t n = %s(',A_operator); msg5=sprintf('[],''dimension'')\n\n give n.'); msg=[msg1,msg2,msg3,msg4,msg5]; errordlg(msg,'MATRIX') end nselect=[]; if n<2, return, end if length(varg) == 1 nselect=min(n,varg); elseif length(varg)>1 if isempty(sigma), sigma=varg(end); varg(end)=[]; end nselect=min(n,min(varg)); end fopts = []; if ~isempty(options), fopts=fields(options); end if isempty(L_precond) if strmatch('Precond',fopts) L_precond = options.Precond; elseif strmatch('L_Precond',fopts) L_precond = options.L_Precond; end end if isempty(U_precond) & strmatch('U_Precond',fopts) U_precond = options.U_Precond; end if isempty(L_precond), ls_tol = [0.7,0.49]; end if ~isempty(L_precond) & ischar(L_precond) if exist(L_precond) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',L_precond); n=-1; elseif ~isempty(U_precond) & ~ischar(U_precond) & n>0 msg=sprintf(' L and U should both be strings or matrices'); n=-1; elseif strcmp(L_precond,U_precond) eval('v=feval(L_precond,zeros(n,1),''L'');','n=-1;') eval('v=feval(L_precond,zeros(n,1),''U'');','n=-1;') if n<0 msg='L and U use the same M-file'; msg1=sprintf(' %s.m \n',L_precond); msg2='Therefore L and U are called'; msg3=sprintf(' as\n\n\tw=%s(v,''L'')',L_precond); msg4=sprintf(' \n\tw=%s(v,''U'')\n\n',L_precond); msg5=sprintf('Check the dimensions and/or\n'); msg6=sprintf('put this "switch" in %s.m.',L_precond); msg=[msg,msg1,msg2,msg3,msg4,msg5,msg6]; else U_precond=0; end elseif ischar(A_operator) & strcmp(A_operator,L_precond) U_precond='preconditioner'; eval('v=feval(L_precond,zeros(n,1),U_precond);','n=-1;') if n<0 msg='Preconditioner and matrix use the same M-file'; msg1=sprintf(' %s. \n',L_precond); msg2='Therefore the preconditioner is called'; msg3=sprintf(' as\n\n\tw=%s(v,''preconditioner'')\n\n',L_precond); msg4='Put this "switch" in the M-file.'; msg=[msg,msg1,msg2,msg3,msg4]; end else eval('v=feval(L_precond,zeros(n,1));','n=-1') if n<0 msg=sprintf('''%s'' should produce %i-vectors',L_precond,n); end end end Ud=1; if ~isempty(L_precond) & ~ischar(L_precond) & n>0 if ~isempty(U_precond) & ischar(U_precond) msg=sprintf(' L and U should both be strings or matrices'); n=-1; elseif ~isempty(U_precond) if ~min([n,n]==size(L_precond) & [n,n]==size(U_precond)) msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1; end elseif min([n,n]==size(L_precond)) U_precond=speye(n); Ud=0; elseif min([n,2*n]==size(L_precond)) U_precond=L_precond(:,n+1:2*n); L_precond=L_precond(:,1:n); else msg=sprintf('The preconditioning matrix\n'); msg2=sprintf('should be %iX%i or %ix%i ([L,U]).\n',n,n,n,2*n); msg=[msg,msg2]; n=-1; end end if n<0, errordlg(msg,'PRECONDITIONER'), return, end ls_tol0=ls_tol; if strmatch('Tol',fopts), tol = options.Tol; end if isempty(nselect), nselect=min(n,5); end if strmatch('jmin',fopts), jmin=min(n,options.jmin); end if strmatch('jmax',fopts) jmax=min(n,options.jmax); if jmin<0, jmin=max(1,jmax-p1); end else if jmin<0, jmin=min(n,nselect+p0); end jmax=min(n,jmin+p1); end if strmatch('MaxIt',fopts), maxit = abs(options.MaxIt); end if strmatch('v0',fopts); V = options.v0; [m,d]=size(V); if m~=n | d==0 if m>n, V = V(1:n,:); end nrV=norm(V); if nrV>0, V=V/nrV; end d=max(d,1); V = [V; ones(n-m,d) +0.1*rand(n-m,d)]; end else V = ones(n,1) +0.1*rand(n,1); d=1; end if strmatch('TestSpace',fopts), INTERIOR = boolean(options.TestSpace,... [INTERIOR,0,1,1.1,1.2],strvcat('standard','harmonic')); end if isempty(sigma) if INTERIOR, sigma=0; else, sigma = 'LM'; end elseif ischar(sigma) switch sigma case {'LM','LR','SR','BE'} case {'SM'} sigma=0; otherwise if INTERIOR, sigma=0; else, sigma='LM'; end end end if strmatch('Schur',fopts), SCHUR = boolean(options.Schur,SCHUR); end if strmatch('Disp',fopts), SHOW = boolean(options.Disp,[SHOW,2]); end if strmatch('Pairs',fopts), PAIRS = boolean(options.Pairs,PAIRS); end if strmatch('AvoidStag',fopts),JDV = boolean(options.AvoidStag,JDV); end if strmatch('Track',fopts) OLD = boolean(options.Track,[OLD,0,OLD,inf],strvcat('no','yes')); end OLD=max(abs(OLD),10*tol); if strmatch('LSolver',fopts), lsolver = lower(options.LSolver); end switch lsolver case {'exact'} L_precond=[]; if ischar(A_operator) msg=sprintf('The operator must be a matrix for ''exact''.'); msg=[msg,sprintf('\nDo you want to solve the correction equation')]; msg=[msg,sprintf('\naccurately with an iterative solver (BiCGstab)?')]; button=questdlg(msg,'Solving exactly','Yes','No','Yes'); if strcmp(button,'No'), n=-1; return, end end case {'iluexact'} if ischar(L_precond) msg=sprintf('The preconditioner must be matrices for ''iluexact''.'); errordlg(msg,'Solving with ''iluexact''') n=-1; return end case {'olsen'} case {'cg','minres','symmlq'} ls_tol=1.0e-12; case 'gmres' ls_maxit=5; case 'bicgstab' ls_tol=1.0e-10; otherwise error(['Unknown method ''' lsolver '''.']); end if strmatch('LS_MaxIt',fopts), ls_maxit=abs(options.LS_MaxIt); end if strmatch('LS_Tol',fopts), ls_tol=abs(options.LS_Tol); end if strmatch('LS_ell',fopts), ell=round(abs(options.LS_ell)); end par=[ls_tol,ls_maxit,ell]; if SHOW fprintf('\n'),fprintf('PROBLEM\n') if ischar(A_operator) fprintf(' A: ''%s''\n',A_operator); elseif issparse(A_operator) fprintf(' A: [%ix%i sparse]\n',n,n); else fprintf(' A: [%ix%i double]\n',n,n); end fprintf(' dimension: %i\n',n); fprintf(' nselect: %i\n\n',nselect); fprintf('TARGET\n') if ischar(sigma) fprintf(' sigma: ''%s''',sigma) else Str=ShowLambda(sigma); fprintf(' sigma: %s',Str) end fprintf('\n\n') fprintf('OPTIONS\n'); fprintf(' Schur: %i\n',SCHUR); fprintf(' Tol: %g\n',tol); fprintf(' Disp: %i\n',SHOW); fprintf(' jmin: %i\n',jmin); fprintf(' jmax: %i\n',jmax); fprintf(' MaxIt: %i\n',maxit); fprintf(' v0: [%ix%i double]\n',size(V)); fprintf(' TestSpace: %g\n',INTERIOR); fprintf(' Pairs: %i\n',PAIRS); fprintf(' AvoidStag: %i\n',JDV); fprintf(' Track: %g\n',OLD); fprintf(' LSolver: ''%s''\n',lsolver); switch lsolver case {'exact','iluexact','olsen'} case {'cg','minres','symmlq','gmres','bicgstab'} if length(ls_tol)>1 fprintf(' LS_Tol: ['); fprintf(' %g',ls_tol); fprintf(' ]\n'); else fprintf(' LS_Tol: %g\n',ls_tol); end fprintf(' LS_MaxIt: %i\n',ls_maxit); end if strcmp(lsolver,'bicgstab') fprintf(' LS_ell: %i\n',ell); end if isempty(L_precond) fprintf(' Precond: []\n'); else StrL='Precond'; StrU='U precond'; Us='double'; Ls=Us; ok=0; if issparse(L_precond), Ls='sparse'; end if ~isempty(U_precond) & Ud, StrL='L precond'; ok=1; if issparse(U_precond), Us='sparse'; end end if ischar(L_precond) fprintf('%13s: ''%s''\n',StrL,L_precond); if ok if U_precond~=0 & ~strcmp(U_precond,'preconditioner') fprintf('%13s: ''%s''\n',StrU,U_precond); else fprintf('%13s: ''%s''\n',StrU,L_precond); end end else fprintf('%13s: [%ix%i %s]\n',StrL,n,n,Ls); if ok & Ud, fprintf('%13s: [%ix%i %s]\n',StrU,n,n,Us); end end end fprintf('\n') string1='%13s: ''%s'''; string2='\n\t %s'; switch INTERIOR case 0 fprintf(string1,'TestSpace','Standard, W = V ') fprintf(string2,'V W: V orthogonal') fprintf(string2,'W=A*V') case 1 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W: V and W orthogonal') fprintf(string2,'AV-Q*E=W*R where AV=A*V-sigma*V and E=Q''*AV') case 1.1 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W AV: V and W orthogonal') fprintf(string2,'AV=A*V-sigma*V, AV-Q*Q''*AV=W*R') case 1.2 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W: W orthogonal') fprintf(string2,'W=AV-Q*E where AV=A*V-sigma*V and E=Q''*AV') otherwise fprintf(string1,'TestSpace','Experimental') end % switch INTERIOR fprintf('\n\n') end % if SHOW if ischar(sigma) & INTERIOR >=1 msg1=sprintf('\n The choice sigma = ''%s'' does not match',sigma); msg2=sprintf('\n the search for INTERIOR eigenvalues.'); msg3=sprintf('\n Specify a numerical value for sigma'); msg4=sprintf(',\n for instance, a value that is '); switch sigma case {'LM'} % sigma='SM'; msg5=sprintf('absolute large.\n'); msg4=[msg4,msg5]; case {'LR'} % sigma='SP'; % smallest positive real msg5=sprintf('positive large.\n'); msg4=[msg4,msg5]; case {'SR'} % sigma='LN'; % largest negative real msg5=sprintf('negative and absolute large.\n'); msg4=[msg4,msg5]; case {'BE'} % sigma='AS'; % alternating smallest pos., largest neg msg4=sprintf('.\n'); end msg=[msg1,msg2,msg3,msg4]; msg5=sprintf(' Do you want to continue with sigma=0?'); msg=[msg,msg5]; button=questdlg(msg,'Finding Interior Eigenvalues','Yes','No','Yes'); if strcmp(button,'Yes'), sigma=0, else, n=-1; end end return %------------------------------------------------------------------- function x = boolean(x,gamma,string) %Y = BOOLEAN(X,GAMMA,STRING) % GAMMA(1) is the default. % If GAMMA is not specified, GAMMA = 0. % STRING is a matrix of accepted strings. % If STRING is not specified STRING = ['no ';'yes'] % STRING(I,:) and GAMMA(I) are accepted expressions for X % If X=GAMMA(I) then Y=X. If X=STRING(I,:), then Y=GAMMA(I+1). % For other values of X, Y=GAMMA(1); if nargin < 2, gamma=0; end if nargin < 3, string=strvcat('no','yes'); gamma=[gamma,0,1]; end if ischar(x) i=strmatch(lower(x),string,'exact'); if isempty(i),i=1; else, i=i+1; end, x=gamma(i); elseif max((gamma-x)==0) elseif gamma(end) == inf else, x=gamma(1); end return %------------------------------------------------------------------- function possibilities fprintf('\n') fprintf('PROBLEM\n') fprintf(' A: [ square matrix | string ]\n'); fprintf(' nselect: [ positive integer {5} ]\n\n'); fprintf('TARGET\n') fprintf(' sigma: [ scalar | vector of scalars |\n'); fprintf(' ''LM'' | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n'); fprintf('OPTIONS\n'); fprintf(' Schur: [ yes | {no} ]\n'); fprintf(' Tol: [ positive scalar {1e-8} ]\n'); fprintf(' Disp: [ yes | {no} | 2 ]\n'); fprintf(' jmin: [ positive integer {nselect+5} ]\n'); fprintf(' jmax: [ positive integer {jmin+5} ]\n'); fprintf(' MaxIt: [ positive integer {200} ]\n'); fprintf(' v0: [ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n'); fprintf(' TestSpace: [ Standard | {Harmonic} ]\n'); fprintf(' Pairs: [ yes | {no} ]\n'); fprintf(' AvoidStag: [ yes | {no} ]\n'); fprintf(' Track: [ {yes} | no | non-negative scalar {1e-4} ]\n'); fprintf(' LSolver: [ {gmres} | bicgstab ]\n'); fprintf(' LS_Tol: [ row of positive scalars {[1,0.7]} ]\n'); fprintf(' LS_MaxIt: [ positive integer {5} ]\n'); fprintf(' LS_ell: [ positive integer {4} ]\n'); fprintf(' Precond: [ n by 2n matrix | string {identity} ]\n'); fprintf('\n') return %=========================================================================== %============= OUTPUT FUNCTIONS ============================================ %=========================================================================== function varargout=ShowLambda(lambda,kk) for k=1:size(lambda,1); if k>1, Str=[Str,sprintf('\n%15s','')]; else, Str=[]; end rlambda=real(lambda(k,1)); ilambda=imag(lambda(k,1)); Str=[Str,sprintf(' %+11.4e',rlambda)]; if abs(ilambda)>100*eps*abs(rlambda) if ilambda>0 Str=[Str,sprintf(' + %10.4ei',ilambda)]; else Str=[Str,sprintf(' - %10.4ei',-ilambda)]; end end end if nargout == 0 if nargin == 2 Str=[sprintf('\nlambda(%i) =',kk),Str]; else Str=[sprintf('\nDetected eigenvalues:\n\n%15s',''),Str]; end fprintf('%s\n',Str) else varargout{1}=Str; end return %=========================================================================== function DispResult(s,nr,gamma) if nargin<3, gamma=0; end extra=''; if nr > 100*eps & gamma extra=' norm > 100*eps !!! '; end if gamma<2 | nr>100*eps fprintf('\n %35s: %0.5g\t%s',s,nr,extra) end return %=========================================================================== function STATUS0=MovieTheta(n,nit,Lambda,jmin,tau,LOCKED,SHRINK) % MovieTheta(n,nit,Lambda,jmin,tau,nr<t_tol,j==jmax); global A_operator Rschur EigMATLAB CIRCLE MovieAxis M_STATUS f=256; if nargin==0, if ~isempty(CIRCLE) %figure(f), buttons(f,-2); hold off, refresh end return end if nit==0 EigMATLAB=[]; if ~ischar(A_operator) & n<201 EigMATLAB=eig(full(A_operator)); end CIRCLE=0:0.005:1; CIRCLE=exp(CIRCLE*2*pi*sqrt(-1)); if ischar(tau) switch tau case {'LR','SR'} if ~ischar(A_operator) CIRCLE=norm(A_operator,'inf')*[sqrt(-1),-sqrt(-1)]+1; end end end Explanation(~isempty(EigMATLAB),f-1) end %if gcf~=f, figure(f), end jmin=min(jmin,length(Lambda)); %plot(real(Lambda(1:jmin)),imag(Lambda(1:jmin)),'bo'); if nit>0, axis(MovieAxis), end, hold on pls='bo'; if SHRINK, pls='mo'; end %plot(real(Lambda(jmin+1:end)),imag(Lambda(jmin+1:end)),pls) %plot(real(EigMATLAB),imag(EigMATLAB),'cp'); THETA=diag(Rschur); %plot(real(THETA),imag(THETA),'k*'); x=real(Lambda(1)); y=imag(Lambda(1)); %plot(x,y,'kd'), pls='ks'; if LOCKED, plot(x,y,'ks'), pls='ms'; end if ischar(tau), tau=0; end delta=Lambda([1,jmin])-tau; if length(CIRCLE)~=2, delta=abs(delta); % plot(real(tau),imag(tau),pls) else, delta=real(delta); end for i=1:1+SHRINK, zeta=delta(i)*CIRCLE+tau; % plot(real(zeta),imag(zeta),'r:'), end if nit==0 buttons(f,-1); hold off, zoom on end title('legend see figure(255)') if SHRINK, STATUS0=buttons(f,2); if STATUS0, return, end, end STATUS0=buttons(f,1); drawnow, hold off return %============================================================= function Explanation(E,f) %if gcf~=f, figure(f), end HL=plot(0,0,'kh',0,0,'bo'); hold on StrL=str2mat('Detected eigenvalues','Approximate eigenvalues'); if E HL=[HL;plot(0,0,'cp')]; StrL=str2mat(StrL,'Exact eigenvenvalues'); end HL=[HL;plot(0,0,'kd',0,0,'ks',0,0,'r:')]; % StrL=str2mat(StrL,'Tracked app. eig.','target',... % 'inner/outer bounds for restart'); StrL=str2mat(StrL,'Selected approximate eigenvalue','target',... 'inner/outer bounds for restart'); legend(HL,StrL), hold on, drawnow, hold off title('legend for figure(256)') return %============================================================= function STATUS0=buttons(f,push) % push=0: do nothing % push>0: check status buttons, % STATUS0=1 if break else STATUS0=0. % push=-1: make buttons for pause and break % push=-2: remove buttons global M_STATUS MovieAxis if push>0 % check status buttons ud = get(f,'UserData'); if ud.pause ==1, M_STATUS=1; end if ud.break ==1, STATUS0=1; ud.pause=0; ud.break=0; set(f,'UserData',ud); return, else, STATUS0=0; end if push>1 ud.pause=0; set(f,'UserData',ud); while M_STATUS ud = get(f,'UserData'); pause(0.1) if ud.pause, M_STATUS=0; end if ud.break, M_STATUS=0; STATUS0=1; end MovieAxis=axis; end ud.pause=0; ud.break=0; set(f,'UserData',ud); end elseif push==0, STATUS0=0; return elseif push==-1 % make buttons ud = []; h = findobj(f,'Tag','pause'); if isempty(h) ud.pause = 0; pos = get(0,'DefaultUicontrolPosition'); pos(1) = pos(1) - 15; pos(2) = pos(2) - 15; str = 'ud=get(gcf,''UserData''); ud.pause=1; set(gcf,''UserData'',ud);'; uicontrol( ... 'Style','push', ... 'String','Pause', ... 'Position',pos, ... 'Callback',str, ... 'Tag','pause'); else set(h,'Visible','on'); % make sure it's visible if ishold oud = get(f,'UserData'); ud.pause = oud.pause; % don't change old ud.pause status else ud.pause = 0; end end h = findobj(f,'Tag','break'); if isempty(h) ud.break = 0; pos = get(0,'DefaultUicontrolPosition'); pos(1) = pos(1) + 50; pos(2) = pos(2) - 15; str = 'ud=get(gcf,''UserData''); ud.break=1; set(gcf,''UserData'',ud);'; uicontrol( ... 'Style','push', ... 'String','Break', ... 'Position',pos, ... 'Callback',str, ... 'Tag','break'); else set(h,'Visible','on'); % make sure it's visible if ishold oud = get(f,'UserData'); ud.break = oud.break; % don't change old ud.break status else ud.break = 0; end end set(f,'UserData',ud); M_STATUS=0; STATUS0=0; hold off, zoom on MA=axis; nl=MA/10; MovieAxis = MA-max(nl([2,4])-nl([1,3]))*[1,-1,1,-1]; else % remove buttons set(findobj(f,'Tag','pause'),'Visible','off'); set(findobj(f,'Tag','break'),'Visible','off'); STATUS0=0; return, refresh end return
github
eulertech/DeepLearningCrudeOilForecast-master
lmnn.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/lmnn.m
5,431
utf_8
622ccdd8948f805d0d4552822cca46de
function [M, L, Y, C] = lmnn(X, labels) %LMNN Learns a metric using large-margin nearest neighbor metric learning % % [M, L, Y, C] = lmnn(X, labels) % % The function uses large-margin nearest neighbor (LMNN) metric learning to % learn a metric on the data set specified by the NxD matrix X and the % corresponding Nx1 vector labels. The metric is returned in M. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % Initialize some variables [N, D] = size(X); assert(length(labels) == N); [lablist, ~, labels] = unique(labels); K = length(lablist); label_matrix = false(N, K); label_matrix(sub2ind(size(label_matrix), (1:length(labels))', labels)) = true; same_label = logical(double(label_matrix) * double(label_matrix')); M = eye(D); C = Inf; prev_C = Inf; % Set learning parameters min_iter = 50; % minimum number of iterations max_iter = 1000; % maximum number of iterations eta = .1; % learning rate mu = .5; % weighting of pull and push terms tol = 1e-3; % tolerance for convergence best_C = Inf; % best error obtained so far best_M = M; % best metric found so far no_targets = 3; % number of target neighbors % Select target neighbors sum_X = sum(X .^ 2, 2); DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (X * X'))); DD(~same_label) = Inf; DD(1:N + 1:end) = Inf; [~, targets_ind] = sort(DD, 2, 'ascend'); targets_ind = targets_ind(:,1:no_targets); targets = false(N, N); targets(sub2ind([N N], vec(repmat((1:N)', [1 no_targets])), vec(targets_ind))) = true; % Compute pulling term between target neigbhors to initialize gradient slack = zeros(N, N, no_targets); G = zeros(D, D); for i=1:no_targets G = G + (1 - mu) .* (X - X(targets_ind(:,i),:))' * (X - X(targets_ind(:,i),:)); end % Perform main learning iterations iter = 0; while (prev_C - C > tol || iter < min_iter) && iter < max_iter % Compute pairwise distances under current metric XM = X * M; sum_X = sum(XM .* X, 2); DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (XM * X'))); % Compute value of slack variables old_slack = slack; for i=1:no_targets slack(:,:,i) = ~same_label .* max(0, bsxfun(@minus, 1 + DD(sub2ind([N N], (1:N)', targets_ind(:,i))), DD)); end % Compute value of cost function prev_C = C; C = (1 - mu) .* sum(DD(targets)) + ... % push terms between target neighbors mu .* sum(slack(:)); % pull terms between impostors % Maintain best solution found so far (subgradient method) if C < best_C best_C = C; best_M = M; end % Perform gradient update for i=1:no_targets % Add terms for new violations [r, c] = find(slack(:,:,i) > 0 & old_slack(:,:,i) == 0); G = G + mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ... (X(r,:) - X(targets_ind(r, i),:)) - ... (X(r,:) - X(c,:))' * (X(r,:) - X(c,:))); % Remove terms for resolved violations [r, c] = find(slack(:,:,i) == 0 & old_slack(:,:,i) > 0); G = G - mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ... (X(r,:) - X(targets_ind(r, i),:)) - ... (X(r,:) - X(c,:))' * (X(r,:) - X(c,:))); end M = M - (eta ./ N) .* G; % Project metric back onto the PSD cone [V, L] = eig(M); V = real(V); L = real(L); ind = find(diag(L) > 0); if isempty(ind) warning('Projection onto PSD cone failed. All eigenvalues were negative.'); break end M = V(:,ind) * L(ind, ind) * V(:,ind)'; if any(isinf(M(:))) warning('Projection onto PSD cone failed. Metric contains Inf values.'); break end if any(isnan(M(:))) warning('Projection onto PSD cone failed. Metric contains NaN values.'); break end % Update learning rate if prev_C > C eta = eta * 1.01; else eta = eta * .5; end % Print out progress iter = iter + 1; no_slack = sum(slack(:) > 0); if rem(iter, 10) == 0 [~, sort_ind] = sort(DD, 2, 'ascend'); disp(['Iteration ' num2str(iter) ': error is ' num2str(C ./ N) ... ', nearest neighbor error is ' num2str(sum(labels(sort_ind(:,2)) ~= labels) ./ N) ... ', number of constraints: ' num2str(no_slack)]); end end % Return best metric and error M = best_M; C = best_C; % Compute mapped data [L, S, ~] = svd(M); L = bsxfun(@times, sqrt(diag(S)), L); Y = X * L; end function x = vec(x) x = x(:); end
github
eulertech/DeepLearningCrudeOilForecast-master
d2p.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/d2p.m
3,487
utf_8
0c7024a8039ea16b937d283585883fc3
function [P, beta] = d2p(D, u, tol) %D2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = d2p(D, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(D, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Run over all datapoints for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; % why not: H = exp(-sum(P(P > 1e-5) .* log(P(P > 1e-5)))); ??? P = P / sumP; end
github
eulertech/DeepLearningCrudeOilForecast-master
cg_update.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/cg_update.m
3,715
utf_8
1556078ae7c31950ec738949384cf180
% Version 1.000 % % Code provided by Ruslan Salakhutdinov and Geoff Hinton % % Permission is granted for anyone to copy, use, modify, or distribute this % program and accompanying programs and documents for any purpose, provided % this copyright notice is retained and prominently displayed, along with % a note saying that the original programs are available from our % web page. % The programs and documents are distributed without any warranty, express or % implied. As the programs were written for research purposes only, they have % not been tested to the degree that would be advisable in any important % application. All use of these programs is entirely at the user's own risk. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology function [f, df] = cg_update(VV, Dim, XX) l1 = Dim(1); l2 = Dim(2); l3 = Dim(3); l4 = Dim(4); l5 = Dim(5); l6 = Dim(6); l7 = Dim(7); l8 = Dim(8); l9 = Dim(9); N = size(XX, 1); % Extract weights back from VV w1 = reshape(VV(1:(l1 + 1) * l2), l1 + 1, l2); xxx = (l1 + 1) * l2; w2 = reshape(VV(xxx + 1:xxx + (l2 + 1) * l3), l2 + 1, l3); xxx = xxx + (l2 + 1) * l3; w3 = reshape(VV(xxx + 1:xxx + (l3 + 1) * l4), l3 + 1, l4); xxx = xxx + (l3 + 1) * l4; w4 = reshape(VV(xxx + 1:xxx + (l4 + 1) * l5), l4 + 1, l5); xxx = xxx + (l4 + 1) * l5; w5 = reshape(VV(xxx + 1:xxx + (l5 + 1) * l6), l5 + 1, l6); xxx = xxx + (l5 + 1) * l6; w6 = reshape(VV(xxx + 1:xxx + (l6 + 1) * l7), l6 + 1, l7); xxx = xxx + (l6 + 1) * l7; w7 = reshape(VV(xxx + 1:xxx + (l7 + 1) * l8), l7 + 1, l8); xxx = xxx + (l7 + 1) * l8; w8 = reshape(VV(xxx + 1:xxx + (l8 + 1) * l9), l8 + 1, l9); % Evaluate points XX = [XX ones(N, 1)]; w1probs = 1 ./ (1 + exp(-XX * w1)); w1probs = [w1probs ones(N,1)]; w2probs = 1 ./ (1 + exp(-w1probs * w2)); w2probs = [w2probs ones(N,1)]; w3probs = 1 ./ (1 + exp(-w2probs * w3)); w3probs = [w3probs ones(N,1)]; w4probs = w3probs * w4; w4probs = [w4probs ones(N,1)]; w5probs = 1 ./ (1 + exp(-w4probs * w5)); w5probs = [w5probs ones(N,1)]; w6probs = 1 ./ (1 + exp(-w5probs * w6)); w6probs = [w6probs ones(N,1)]; w7probs = 1 ./ (1 + exp(-w6probs * w7)); w7probs = [w7probs ones(N,1)]; XXout = 1 ./ (1 + exp(-w7probs * w8)); % Compute gradients f = (-1 / N) * sum(sum(XX(:,1:end - 1) .* log(XXout) + (1 - XX(:,1:end - 1)) .* log(1 - XXout))); IO = (1 / N) * (XXout - XX(:,1:end - 1)); Ix8 = IO; dw8 = w7probs'*Ix8; Ix7 = (Ix8 * w8') .* w7probs .* (1 - w7probs); Ix7 = Ix7(:,1:end - 1); dw7 = w6probs' * Ix7; Ix6 = (Ix7*w7') .* w6probs .* (1 - w6probs); Ix6 = Ix6(:,1:end - 1); dw6 = w5probs' * Ix6; Ix5 = (Ix6 * w6') .* w5probs .* (1 - w5probs); Ix5 = Ix5(:,1:end - 1); dw5 = w4probs' * Ix5; Ix4 = (Ix5 * w5'); Ix4 = Ix4(:,1:end - 1); dw4 = w3probs' * Ix4; Ix3 = (Ix4 * w4') .* w3probs .* (1 - w3probs); Ix3 = Ix3(:,1:end - 1); dw3 = w2probs' * Ix3; Ix2 = (Ix3 * w3') .* w2probs .* (1 - w2probs); Ix2 = Ix2(:,1:end - 1); dw2 = w1probs' * Ix2; Ix1 = (Ix2 * w2') .* w1probs .* (1 - w1probs); Ix1 = Ix1(:,1:end - 1); dw1 = XX' * Ix1; % Return gradients df = [dw1(:)' dw2(:)' dw3(:)' dw4(:)' dw5(:)' dw6(:)' dw7(:)' dw8(:)']';
github
eulertech/DeepLearningCrudeOilForecast-master
lmvu.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/lmvu.m
8,540
utf_8
c8003ed7ff0fd0e226776c42c72ad385
function [mappedX, mapping] = lmvu(X, no_dims, K, LL) %LMVU Performs Landmark MVU on dataset X % % [mappedX, mapping] = lmvu(X, no_dims, k1, k2) % % The function performs Landmark MVU on the DxN dataset X. The value of k1 % represents the number of nearest neighbors that is employed in the MVU % constraints. The value of k2 represents the number of nearest neighbors % that is employed to compute the reconstruction weights (for embedding the % non-landmark points). % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('K', 'var') K = 3; end if ~exist('LL', 'var') LL = 12; end % Save some data for out-of-sample extension if ischar(K) error('Adaptive neighborhood selection not supported for landmark MVU.'); end mapping.k1 = K; mapping.k2 = LL; mapping.X = X; % Initialize some variables N = size(X, 2); % number of datapoints B = ceil(0.02 * N); % number of landmark points % Set some parameters parameters pars.ep = eps; pars.fastmode = 1; pars.warmup = K * B / N; pars.verify = 1; pars.angles = 1; pars.maxiter = 100; pars.noise = 0; pars.ignore = 0.1; pars.penalty = 1; pars.factor = 0.9999; % Identify nearest neighbors disp('Identifying nearest neighbors...'); KK = max(LL, K); X = L2_distance(X, X); % memory-intensive: O(n^{2}) !!! [foo, neighbors] = find_nn(X, KK); neighbors = neighbors'; % Get inverse of reconstruction weight matrix Pia = getPia(B, LL, X, neighbors); % Generate SDP problem disp('Generating SDP problem...'); neighbors = neighbors(1:K,:); clear temp index sorted nck = nchoosek(1:K + 1, 2); AA = zeros(N * K, 2); pos3 = 1; for i=1:N ne = neighbors(:,i); nne = [ne; i]; pairs = nne(nck); js = pairs(:,1); ks = pairs(:,2); AA(pos3:pos3 + length(js) - 1,:) = sort([js ks], 2); pos3 = pos3 + length(js); if i == B AA = unique(AA, 'rows'); ForceC = size(AA, 1); end if pos3 > size(AA, 1) && i < N AA = unique(AA, 'rows'); pos3 = size(AA, 1) + 1; AA = [AA; zeros(round(N / (N - i) * pos3), 2)]; fprintf('.'); end end AA = unique(AA, 'rows'); AA = AA(2:end,:); clear neighbors ne v2 v3 js ks bb = zeros(1, size(AA, 1)); for i=1:size(AA, 1) bb(i) = sum((X(:,AA(i, 1)) - X(:,AA(i, 2))) .^ 2); end disp(' '); % Reduce the number of forced vectors ii = (1:ForceC)'; jj = zeros(1, size(AA, 1)); jj(ii) = 1; jj = find(jj == 0); jj1 = jj(jj <= ForceC); jj2 = jj(jj > ForceC); jj2 = jj2(randperm(length(jj2))); jj1 = jj1(randperm(length(jj1))); corder = [ii; jj1'; jj2']; AA = AA(corder,:); bb = bb(corder); ForceC = length(ii); clear temp jj1 jj2 jj ii Const = max(round(pars.warmup * size(AA, 1)), ForceC); [A, b, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars); Qt = sum(Pia, 1)' * sum(Pia, 1); A = [Qt(:)'; A]; b = [0; b]; clear K; solved = 0; % Start SDP iterations disp('Perform semi-definite programming...'); disp('CSDP OUTPUT ============================================================================='); while solved == 0 % Initialize some variables c = -vec(Pia' * Pia); flags.s = B; flags.l = size(A, 1) - 1; A = [[zeros(1,flags.l); speye(flags.l)] A]; % Set c (employ penalty) c = [ones(ForceC, 1) .* max(max(c)); zeros(flags.l - ForceC, 1); c]; % Launch the CSDP solver options.maxiter=pars.maxiter; [x, d, z, info] = csdp(A, b, c, flags, options); K = mat(x(flags.l + 1:flags.l + flags.s ^ 2)); % Check whether a solution is reached solved = isempty(AA); A = A(:,flags.l + 1:end); xx = K(:); if size(AA, 1) Aold = size(A,1); total = 0; while size(A, 1) - Aold < Const && ~isempty(AA) [newA, newb, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars); jj = find(newA * xx - newb > pars.ignore * abs(newb)); if info == 2 jj = 1:size(newA, 1); end total = total + length(jj); A(size(A,1) + 1:size(A,1) + length(jj),:) = newA(jj,:); b(length(b) + 1:length(b) + length(jj)) = newb(jj); end if total == 0 solved = 1; end else solved=1; end if solved == 1 && pars.maxiter < 100 pars.maxiter = 100; end end disp('========================================================================================='); % Perform eigendecomposition of kernel matrix to compute Y disp('Perform eigendecomposition to obtain low-dimensional data representation...'); [V, D] = eig(K); V = V * sqrt(D); Y = (V(:,end:-1:1))'; mappedX = Y * Pia'; % Reorder data in original order mappedX = mappedX(1:no_dims,:); % Set some information for the out-of-sample extension mapping.Y = Y; mapping.D = X; mapping.no_landmarks = B; mapping.no_dims = no_dims; % Function that computes LLE weight matrix function Q = getPia(B, LL, X, neighbors) % Initialize some variables N = size(X,2); % Compute reconstruction weights disp('Computing reconstruction weights...'); tol = 1e-7; Pia = sparse([], [], [], B, N); for i=1:N z = X(:,neighbors(:,i)) - repmat(X(:,i), 1, LL); C = z' * z; C = C + tol * trace(C) * eye(LL) / LL; invC = inv(C); Pia(neighbors(:,i),i) = sum(invC)' / sum(sum(invC)); end % Fill sparse LLE weight matrix M = speye(N) + sparse([], [], [], N, N, N * LL .^ 2); for i=1:N j = neighbors(:,i); w = Pia(j, i); M(i, j) = M(i, j) - w'; M(j, i) = M(j, i) - w; M(j, j) = M(j, j) + w * w'; end % Invert LLE weight matrix disp('Invert reconstruction weight matrix...'); Q = -M(B + 1:end, B + 1:end) \ M(B + 1:end, 1:B); Q = [eye(B); Q]; % Functions that constructs the constraints for the SDP function [A, b, AAomit, bbomit] = getConstraints(AA, Pia, bb, B, Const, pars) % Initialize some variables pos2 = 0; perm = 1:size(AA,1); if size(AA, 1) > Const AAomit = AA(perm(Const + 1:end),:); bbomit = bb(perm(Const + 1:end)); AA = AA(perm(1:Const),:); bb = bb(perm(1:Const)); else AAomit = []; bbomit = []; end % Allocate some memory persistent reqmem; if isempty(reqmem) A2 = zeros(size(AA, 1) * B, 3); else A2 = zeros(reqmem, 3); end % Set the constraints pos = 0; for j=1:size(AA, 1) % Evaluate for current row in AA ii = AA(j, 1); jj = AA(j, 2); Q = Pia(ii,:)' * Pia(ii,:) - 2 .* Pia(jj,:)' * Pia(ii,:) + Pia(jj,:)' * Pia(jj,:); Q = (Q + Q') ./ 2; it = find(abs(Q) > pars.ep .^ 2); % Constraint found if ~isempty(it) % Allocate more memory if needed pos = pos + 1; if pos2 + length(it) > size(A2, 1) A2 = [A2; zeros(ceil((size(AA, 1) - j) / j * size(A2, 1)), 3)]; end % Set constraint A2(1 + pos2:pos2 + length(it), 1) = ones(length(it), 1) .* pos; A2(1 + pos2:pos2 + length(it), 2) = it; A2(1 + pos2:pos2 + length(it), 3) = full(Q(it)); pos2 = pos2 + length(it); end end % Construct sparse constraint matrix reqmem = pos2; A2 = A2(1:pos2,:); A = sparse(A2(:,1), A2(:,2), A2(:,3), size(AA,1), B .^ 2); b = bb'; % Function that vectorizes a matrix function v = vec(M) v = M(:); % Function that matrixizes a vector function M = mat(C) r = round(sqrt(size(C, 1))); M = reshape(C, r, r);
github
eulertech/DeepLearningCrudeOilForecast-master
cca.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/cca.m
14,846
utf_8
935e971ffe825a64e0eb80c535d71ebb
function [Z, ccaEigen, ccaDetails] = cca(X, Y, EDGES, OPTS) % % Function [Z, CCAEIGEN, CCADETAILS] = CCA(X, Y, EDGES, OPTS) computes a low % dimensional embedding Z in R^d that maximally preserves angles among input % data X that lives in R^D, with the algorithm Conformal Component Analysis. % % The embedding Z is constrained to be Z = L*Y where Y is a partial basis that % spans the space of R^d. Such Y can be computed from graph Laplacian (such as % the outputs of Laplacian eigenmap and Locally Linear Embedding, ie, LLE). % The parameterization matrix L is found by this function as to maximally % prserve angles between edges coded in the sparse matrix EDGES. % % A basic usage of this function is given below: % % Inputs: % X: input data stored in matrix (D x N) where D is the dimensionality % % Y: partial basis stored in matrix (d x N) % % EDGES: a sparse matrix of (N x N). In each column i, the row indices j to % nonzero entrices define data points that are in the nearest neighbors of % data point i. % % OPTS: % OPTS.method: 'CCA' % % Outputs: % Z: low dimensional embedding (d X N) % CCAEIGN: eigenspectra of the matrix P = L'*L. If P is low-rank (say d' < d), % then Z can be cutoff at d' dimension as dimensionality reduced further. % % The CCA() function is fairly versatile. For more details, consult the file % README. % % by [email protected] Aug 18, 2006 % Feel free to use it for educational and research purpose. % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % sanity check if nargin ~= 4 error('Incorrect number of inputs supplied to cca().'); end N = size(X,2); if (N~=size(Y,2)) || (N ~= size(EDGES,1)) || (N~=size(EDGES,2)) disp('Unmatched matrix dimensions in cca().'); fprintf('# of data points: %d\n', N); fprintf('# of data points in Y: %d\n', size(Y,2)); fprintf('Size of the sparse matrix for edges: %d x %d\n', size(EDGES,1), size(EDGES,2)); error('All above 4 numbers should be the same.'); end % check necessary programs if exist('mexCCACollectData') ~= 3 error('Missing mexCCACollectData mex file on the path'); end if exist('csdp') ~= 2 error('You will need CSDP solver to run cca(). Please make sure csdp.m is in your path'); end % check options OPTS = check_opt(OPTS); D = size(X, 1); d = size(Y, 1); %disp('Step I. collect data needed for SDP formulation'); [tnn, vidx] = triangNN(EDGES, OPTS.CCA); [erow, ecol, evalue] = sparse_nn(tnn); irow = int32(erow); icol = int32(ecol); ividx = int32(vidx); ivalue = int32(evalue); [A,B, g] = mexCCACollectData(X,Y, irow, icol, int32(OPTS.relative), ivalue, ividx ); clear erow ecol irow icol tnn ividx ivalue evalue vidx; lst = find(g~=0); g = g(lst); B = B(:, lst); if OPTS.CCA == 1 BG = B*spdiags(1./sqrt(g),0, length(g),length(g)); Q = A - BG*BG'; BIAS = OPTS.regularizer*reshape(eye(d), d^2,1); else Q = A; BIAS = 2*sum(B,2)+OPTS.regularizer*reshape(eye(d), d^2,1); end [V, E] = eig(Q+eye(size(Q))); % adding an identity matrix to Q for numerical E = E-eye(size(Q)); % stability E(E<0) = 0; if ~isreal(diag(E)) warning('\tThe quadratic matrix is not positive definite..forced to be positive definite...\n'); E=real(E); V = real(V); S = sqrt(E)*V'; else S = sqrt(E)*V'; end % Formulate the SDP problem [AA, bb, cc] = formulateSDP(S, d, BIAS, (OPTS.CCA==1)); sizeSDP = d^2+1 + d + 2*(OPTS.CCA==1); csdppars.s = sizeSDP; csdpopts.printlevel = 0; % Solve it using CSDP [xx, yy, zz, info] = csdp(AA, bb, cc, csdppars,csdpopts); ccaDetails.sdpflag = info; % The negate of yy is our solution yy = -yy; idx = 0; P = zeros(d); for col=1:d for row = col:d idx=idx+1; P(row, col) = yy(idx); end end % Convert P to a positive definite matrix P = P + P' - diag(diag(P)); % Transform the original projection to the new projection [V, E] = eig(P); E(E < 0) = 0; L = diag(sqrt(diag(E))) * V'; newY = L * Y; % Eigenvalue of the new projection, doing PCA using covariance matrix [newV, newE] = eig(newY * newY'); newE = diag(newE); [dummy, idx] = sort(newE); newE = newE(idx(end:-1:1)); newY = newV' * newY; Z = newY(idx(end:-1:1),:); ccaEigen = newE; ccaDetails.cost = P(:)'*Q*P(:) - BIAS'*P(:) + sum(g(:))*(OPTS.MVU==1); if OPTS.CCA == 1 ccaDetails.c = spdiags(1./sqrt(g),0, length(g),length(g))*B'*P(:); else ccaDetails.c = []; end ccaDetails.P = P; ccaDetails.opts = OPTS; %%%%%%%%%%%%%%%%%%%% FOLLOWING IS SUPPORTING MATLAB FUNCTIONS function [A, b, c] = formulateSDP(S, D, bb, TRACE) [F0, FI, c] = localformulateSDP(S, D, bb, TRACE); [A, b, c] = sdpToSeDuMi(F0, FI, c); function [F0, FI, c] = localformulateSDP(S, D, b, TRACE) % formulate SDP problem % each FI that corresponds to the LMI for the quadratic cost function has % precisely 2*D^2 nonzero elements. But we need only D^2 storage for % indexing these elements since the FI are symmetric tempFidx = zeros(D^2, 3); dimF = (D^2+1) + D + 2*TRACE; idx= 0; tracearray = ones(TRACE,1); for col=1:D for row=col:D idx = idx+1; lindx1 = sub2ind([D D], row, col); lindx2 = sub2ind([D D], col, row); tempFidx(:,1) = [1:D^2]'; tempFidx(:,2) = D^2+1; if col==row tempFidx(:,3) = S(:, lindx1) ; FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row+D^2+1; ... % for P being p.s.d tracearray*(D^2+1+D+1); % for trace tracearray*(D^2+1+D+2); % for negate trace ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric row+D^2+1; ... % for P being p.s.d tracearray*(D^2+1+D+1); % for trace tracearray*(D^2+1+D+2); % for negate trace ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d tracearray*1; % for trace tracearray*(-1); % for negate trace ], dimF, dimF); else tempFidx(:,3) = S(:, lindx1) + S(:, lindx2); FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row+D^2+1; ... % for P being p.s.d col+D^2+1; ... % symmetric ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric col+D^2+1; ... % for P being p.s.d row+D^2+1; ... % being symmetric ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d 1; % symmetric ], dimF, dimF); end end end idx=idx+1; % for the F matrix corresponding to t FI{idx} = sparse(D^2+1, D^2+1, 1, dimF, dimF); % now for F0 if TRACE==1 F0 = sparse( [[1:D^2] dimF-1 dimF], [[1:D^2] dimF-1 dimF], [ones(1, D^2) -1 1], dimF, dimF); else F0 = sparse( [[1:D^2]], [[1:D^2]], [ones(1, D^2)], dimF, dimF); end % now for c b = reshape(-b, D, D); b = b*2 - diag(diag(b)); c = zeros(idx-1,1); kdx=0; %keyboard; for col=1:D for row=col:D kdx = kdx+1; c(kdx) = b(row, col); end end %keyboard; c = [c; 1]; % remember: we use only half of P return; function [A, b, c] = sdpToSeDuMi(F0, FI, cc) % convert the canonical SDP dual formulation: % (see Vandenberche and Boyd 1996, SIAM Review) % max -Tr(F0 Z) % s.t. Tr(Fi Z) = cci and Z is positive definite % % in which cc = (cc1, cc2, cc3,..) and FI = {F1, F2, F3,...} % % to SeDuMi format (formulated as vector decision variables ): % min c'x % s.t. Ax = b and x is positive definite (x is a vector, so SeDuMi % really means that vec2mat(x) is positive definite) % % by [email protected], June, 10, 2004 if nargin < 3 error('Cannot convert SDP formulation to SeDuMi formulation in sdpToSeDumi!'); end [m, n] = size(F0); if m ~= n error('F0 matrix must be squared matrix in sdpToSeDumi(F0, FI, b)'); end p = length(cc); if p ~= length(FI) error('FI matrix cellarray must have the same length as b in sdpToSeDumi(F0,FI,b)'); end % should check every element in the cell array FI...later.. % x = reshape(Z, n*n, 1); % optimization variables from matrix to vector % converting objective function of the canonical SDP c = reshape(F0', n*n,1); % converting equality constraints of the canonical SDP zz= 0; for idx=1:length(FI) zz= zz + nnz(FI{idx}); end A = spalloc( n*n, p, zz); for idx = 1:p temp = reshape(FI{idx}, n*n,1); lst = find(temp~=0); A(lst, idx) = temp(lst); end % The SeDuMi solver actually expects the transpose of A as in following % dual problem % max b'y % s.t. c - A'y is positive definite % Therefore, we transpose A % A = A'; % b doesn't need to be changed b = cc; return; % Check OPTS that is passed into function OPTS = check_opt(OPTS) if isfield(OPTS,'method') == 0 OPTS.method = 'cca'; disp('Options does''t have method field, so running CCA'); end if strncmpi(OPTS.method, 'MVU',3)==1 OPTS.CCA = 0; OPTS.MVU = 1; else OPTS.CCA = 1; OPTS.MVU = 0; end if isfield(OPTS, 'relative')==0 OPTS.relative = 0; end if OPTS.CCA==1 && OPTS.relative ==1 disp('Running CCA, so the .relative flag set to 0'); OPTS.relative = 0; end if isfield(OPTS, 'regularizer')==0 OPTS.regularizer = 0; end return function [tnn vidx]= triangNN(snn, TRI) % function [TNN VIDX]= triangNN(SNN) triangulates a sparse graph coded by spare matrix % SNN. TNN records the original edges in SNN as well as those that are % triangulated. Each edge is associated with a scaling factor that is specific % to a vertex. And VIDX records the id of the vertex. % % by [email protected] Aug. 15, 2006. N = size(snn,1); %fprintf('The graph has %d vertices\n', N); % figure out maximum degree a vertex has connectivs = sum(snn,1); maxDegree = max(connectivs); tnn = spalloc(N, N, round(maxDegree*N)); % prealloc estimated storage for speedup % triangulation for idx=1:N lst = find(snn(:, idx)>0); for jdx=1:length(lst) col = min (idx, lst(jdx)); row = max(idx, lst(jdx)); tnn(row, col) = tnn(row, col)+1; if TRI == 1 for kdx = jdx+1:length(lst) col = min(lst(jdx), lst(kdx)); row = max(lst(jdx), lst(kdx)); tnn(row, col) = tnn(row, col)+1; end end end end numVertexIdx = full(sum(tnn(:))); %fprintf('%d vertex entries are needed\n', numVertexIdx); rowIdx = zeros(numVertexIdx,1); colIdx = zeros(numVertexIdx,1); vidx = zeros(numVertexIdx,1); whichEdge = 0; for idx=1:N lst = find(snn(:, idx)>0); for jdx=1:length(lst) col = min(lst(jdx), idx); row = max(lst(jdx), idx); whichEdge = whichEdge+1; rowIdx(whichEdge) = row; colIdx(whichEdge) = col; vidx(whichEdge) = idx; if TRI==1 for kdx = jdx+1:length(lst) col = min(lst(jdx), lst(kdx)); row = max(lst(jdx), lst(kdx)); whichEdge = whichEdge+1; rowIdx(whichEdge) = row; colIdx(whichEdge) = col; vidx(whichEdge) = idx; end end end end linearIdx = sub2ind([N N],rowIdx, colIdx); [sa, sIdx] = sort(linearIdx); vidx = vidx(sIdx); return % turn sparse graph snn into row and col indices function [edgesrow, edgescol, value] = sparse_nn(snn) N = size(snn,1); edgescol = zeros(N+1,1); nnzer = nnz(snn); edgesrow = zeros(nnzer,1); value = zeros(nnzer,1); edgescol(1) = 0; for jdx=1:N lst = find(snn(:, jdx)>0); %lst = lst(find(lst>jdx)); edgescol(jdx+1) = edgescol(jdx)+length(lst); edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1; value(edgescol(jdx)+1:edgescol(jdx+1)) = snn(lst, jdx); end return
github
eulertech/DeepLearningCrudeOilForecast-master
x2p.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/x2p.m
3,597
utf_8
4a102e94922f4af38e36c374dccbc5a2
function [P, beta] = x2p(X, u, tol) %X2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = x2p(xx, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(X, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Compute pairwise distances % disp('Computing pairwise distances...'); D = squareform(pdist(X, 'euclidean') .^ 2); % Run over all datapoints % disp('Computing P-values...'); for i=1:n % if ~rem(i, 500) % disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); % end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision Di = D(i, [1:i-1 i+1:end]); [H, thisP] = Hbeta(Di, beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(Di, beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end % disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); % disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); % disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end
github
eulertech/DeepLearningCrudeOilForecast-master
sammon.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/sammon.m
7,108
utf_8
8a1fccbea9525bbebae4039127005ea6
function [y, E] = sammon(x, n, opts) %SAMMON Performs Sammon's MDS mapping on dataset X % % Y = SAMMON(X) applies Sammon's nonlinear mapping procedure on % multivariate data X, where each row represents a pattern and each column % represents a feature. On completion, Y contains the corresponding % co-ordinates of each point on the map. By default, a two-dimensional % map is created. Note if X contains any duplicated rows, SAMMON will % fail (ungracefully). % % [Y,E] = SAMMON(X) also returns the value of the cost function in E (i.e. % the stress of the mapping). % % An N-dimensional output map is generated by Y = SAMMON(X,N) . % % A set of optimisation options can also be specified using a third % argument, Y = SAMMON(X,N,OPTS) , where OPTS is a structure with fields: % % MaxIter - maximum number of iterations % TolFun - relative tolerance on objective function % MaxHalves - maximum number of step halvings % Input - {'raw','distance'} if set to 'distance', X is % interpreted as a matrix of pairwise distances. % Display - {'off', 'on', 'iter'} % Initialisation - {'pca', 'random'} % % The default options structure can be retrieved by calling SAMMON with % no parameters. % % References : % % [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data Structure % Analysis", IEEE Transactions on Computers, vol. C-18, no. 5, % pp 401-409, May 1969. % % See also : SAMMON_TEST % % File : sammon.m % % Date : Monday 12th November 2007. % % Author : Gavin C. Cawley and Nicola L. C. Talbot % % Description : Simple vectorised MATLAB implementation of Sammon's non-linear % mapping algorithm [1]. % % References : [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data % Structure Analysis", IEEE Transactions on Computers, % vol. C-18, no. 5, pp 401-409, May 1969. % % History : 10/08/2004 - v1.00 % 11/08/2004 - v1.10 Hessian made positive semidefinite % 13/08/2004 - v1.11 minor optimisation % 12/11/2007 - v1.20 initialisation using the first n principal % components. % % Thanks : Dr Nick Hamilton ([email protected]) for supplying the % code for implementing initialisation using the first n % principal components (introduced in v1.20). % % To do : The current version does not take advantage of the symmetry % of the distance matrix in order to allow for easy % vectorisation. This may not be a good choice for very large % datasets, so perhaps one day I'll get around to doing a MEX % version using the BLAS library etc. for very large datasets. % % Copyright : (c) Dr Gavin C. Cawley, November 2007. % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % use the default options structure if nargin < 3 opts.Display = 'iter'; opts.Input = 'raw'; opts.MaxHalves = 20; opts.MaxIter = 500; opts.TolFun = 1e-9; opts.Initialisation = 'random'; end % the user has requested the default options structure if nargin == 0 y = opts; return; end % Create a two-dimensional map unless dimension is specified if nargin < 2 n = 2; end % Set level of verbosity if strcmp(opts.Display, 'iter') display = 2; elseif strcmp(opts.Display, 'on') display = 1; else display = 0; end % Create distance matrix unless given by parameters if strcmp(opts.Input, 'distance') D = x; else D = euclid(x, x); end % Remaining initialisation N = size(x, 1); scale = 0.5 / sum(D(:)); D = D + eye(N); Dinv = 1 ./ D; if strcmp(opts.Initialisation, 'pca') [UU,DD] = svd(x); y = UU(:,1:n)*DD(1:n,1:n); else y = randn(N, n); end one = ones(N,n); d = euclid(y,y) + eye(N); dinv = 1./d; delta = D - d; E = sum(sum((delta.^2).*Dinv)); % Get on with it for i=1:opts.MaxIter % Compute gradient, Hessian and search direction (note it is actually % 1/4 of the gradient and Hessian, but the step size is just the ratio % of the gradient and the diagonal of the Hessian so it doesn't % matter). delta = dinv - Dinv; deltaone = delta * one; g = delta * y - y .* deltaone; dinv3 = dinv .^ 3; y2 = y .^ 2; H = dinv3 * y2 - deltaone - 2 * y .* (dinv3 * y) + y2 .* (dinv3 * one); s = -g(:) ./ abs(H(:)); y_old = y; % Use step-halving procedure to ensure progress is made for j=1:opts.MaxHalves y(:) = y_old(:) + s; d = euclid(y, y) + eye(N); dinv = 1 ./ d; delta = D - d; E_new = sum(sum((delta .^ 2) .* Dinv)); if E_new < E break; else s = 0.5*s; end end % Bomb out if too many halving steps are required if j == opts.MaxHalves warning('MaxHalves exceeded. Sammon mapping may not converge...'); end % Evaluate termination criterion if abs((E - E_new) / E) < opts.TolFun if display fprintf(1, 'Optimisation terminated - TolFun exceeded.\n'); end break; end % Report progress E = E_new; if display > 1 fprintf(1, 'epoch = %d : E = %12.10f\n', i, E * scale); end end % Fiddle stress to match the original Sammon paper E = E * scale; end function d = euclid(x, y) d = sqrt(sum(x.^2,2)*ones(1,size(y,1))+ones(size(x,1),1)*sum(y.^2,2)'-2*(x*y')); end
github
eulertech/DeepLearningCrudeOilForecast-master
sdecca2.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/sdecca2.m
7,185
utf_8
e53979561adda6a23883da0e72af5bf6
function [P, newY, L, newV, idx]= sdecca2(Y, snn, regularizer, relative) % doing semidefinitve embedding/MVU with output being parameterized by graph % laplacian's eigenfunctions.. % % the algorithm is same as conformal component analysis except that the scaling % factor there is set as 1 % % % function [P, newY, Y] = CDR2(X, Y, NEIGHBORS) implements the % CONFORMAL DIMENSIONALITY REDUCTION of data X. It finds a linear map % of Y -> L*Y such that X and L*Y is related by a conformal mapping. % % No tehtat The algorithm use the formulation of only distances. % % Input: % Y: matrix of d'xN, with each column is a point in R^d' % NEIGHBORS: matrix of KxN, each column is a list of indices (between 1 % and N) to the nearest-neighbor of the corresponding column in X % Output: % P: square of the linear map L, i.e., P = L'*L % newY: transformed data points, i.e., newY = L*Y; % Y: the linear map L itself, i.e., L = L % % The algorithm finds L by solving a semidefinite programming problem. It % calls csdp() SDP solver by default and assumes that it is on the path. % % written by [email protected] % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % Collect the data [erow, ecol, edist] = sparse_nn(snn); irow = int32(erow); icol = int32(ecol); [A, B, g] = mexCCACollectData2(Y, irow, icol, edist, int32(relative)); BG = 2 * sum(B, 2); Q = A ; [V, E] = eig(Q + eye(size(Q))); E = E - eye(size(Q)); E(E < 0) = 0; if ~isreal(diag(E)) E = real(E); V = real(V); S = sqrt(E) * V'; else S = sqrt(E) * V'; end % Put the regularizer in there BG = BG + regularizer * reshape(eye(size(Y, 1)), size(Y, 1) ^ 2, 1); % Formulate the SDP problem [AA, bb, cc] = formulateSDP(S, size(Y, 1), BG); sizeSDP = size(Y, 1) ^ 2 + 1 + size(Y, 1); pars.s = sizeSDP; opts.printlevel = 1; % Solve it using CSDP [xx, yy] = csdp(AA, bb, cc, pars, opts); % The negate of yy is our solution yy = -yy; idx = 0; P = zeros(size(Y, 1)); for col=1:size(Y, 1) for row = col:size(Y, 1) idx = idx + 1; P(row, col) = yy(idx); end end % Convert P to a positive definite matrix P = P + P' - diag(diag(P)); % Transform the original projection to the new projection [V, E] = eig(P); E(E < 0) = 0; L = diag(sqrt(diag(E))) * V'; newY = L * Y; % multiply with Laplacian % Eigendecomposition of the new projection: doing PCA because the % dimensionality of newY or Y is definitely less than the number of % points [newV, newE] = eig(newY * newY'); newE = diag(newE); [dummy, idx] = sort(newE); newY = newV' * newY; newY = newY(idx(end:-1:1),:); return % Function that formulates the SDP problem function [A, b, c]=formulateSDP(S, D, bb) [F0, FI, c] = localformulateSDP(S, D, bb); [A, b, c] = sdpToSeDuMi(F0, FI, c); return % Function that formulates the SDP problem function [F0, FI, c] = localformulateSDP(S, D, b) % Each FI that corresponds to the LMI for the quadratic cost function has % precisely 2 * D^2 nonzero elements. But we need only D^2 storage for tempFidx = zeros(D ^ 2, 3); dimF = (D ^ 2 + 1) + D; idx = 0; for col=1:D for row=col:D idx = idx + 1; lindx1 = sub2ind([D D], row, col); lindx2 = sub2ind([D D], col, row); tempFidx(:,1) = [1:D ^ 2]'; tempFidx(:,2) = D ^ 2 + 1; if col == row tempFidx(:,3) = S(:,lindx1) ; FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row + D^2 + 1 ... % for P being p.s.d ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric row + D^2 + 1; ... % for P being p.s.d ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d ], dimF, dimF); else tempFidx(:,3) = S(:, lindx1) + S(:,lindx2); FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row + D^2 + 1; ... % for P being p.s.d col + D^2 + 1; ... % symmetric ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric col + D^2 + 1; ... % for P being p.s.d row + D^2 + 1; ... % being symmetric ], ... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d 1; % symmetric ], dimF, dimF); end end end idx = idx + 1; % For the F matrix corresponding to t FI{idx} = sparse(D^2 + 1, D^2 + 1, 1, dimF, dimF); % Now for F0 F0 = sparse(1:D^2, 1:D^2, ones(1, D^2), dimF, dimF); % Now for c b = reshape(-b, D, D); b = b * 2 - diag(diag(b)); c = zeros(idx - 1,1); kdx = 0; for col=1:D for row=col:D kdx = kdx + 1; c(kdx) = b(row, col); end end c = [c; 1]; return % Function that convertsthe canonical SDP dual formulation to SeDuMi format function [A, b, c] = sdpToSeDuMi(F0, FI, cc) % Check inputs if nargin < 3 error('Cannot convert SDP formulation to SeDuMi formulation.'); end [m, n] = size(F0); if m ~= n error('F0 matrix must be squared matrix.'); end p = length(cc); if p ~= length(FI) error('FI matrix cellarray must have the same length as b.'); end % Converting objective function of the canonical SDP c = reshape(F0', n * n, 1); % Converting equality constraints of the canonical SDP zz = 0; for idx=1:length(FI) zz= zz + nnz(FI{idx}); end A = spalloc(n * n, p, zz); for idx=1:p temp = reshape(FI{idx}, n * n, 1); lst = find(temp ~= 0); A(lst, idx) = temp(lst); end % We do not need to convert b b = cc; return
github
eulertech/DeepLearningCrudeOilForecast-master
sparse_nn.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/sparse_nn.m
972
utf_8
df5da172f954ec2f53125a04787cf2d3
%SPARSE_NN % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology function [edgesrow, edgescol,edgesdist] = sparse_nn(snn) % turn into sparse nearest neighbor graph snn into edgesrow and edgescol index N = size(snn,1); edgescol = zeros(N+1,1); nnzer = nnz(snn); edgesrow = zeros(nnzer,1); edgesdist = zeros(nnzer,1); edgescol(1) = 0; for jdx=1:N lst = find(snn(:, jdx)>0); %lst = lst(find(lst>jdx)); edgescol(jdx+1) = edgescol(jdx)+length(lst); edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1; edgesdist(edgescol(jdx)+1:edgescol(jdx+1))=snn(lst,jdx); end
github
eulertech/DeepLearningCrudeOilForecast-master
jdqz.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/techniques/jdqz.m
78,986
utf_8
be67a038982588a6ac9cbc2d36f009e8
function varargout=jdqz(varargin) %JDQZ computes a partial generalized Schur decomposition (or QZ % decomposition) of a pair of square matrices or operators. % % LAMBDA=JDQZ(A,B) and JDQZ(A,B) return K eigenvalues of the matrix pair % (A,B), where K=min(5,N) and N=size(A,1) if K has not been specified. % % [X,JORDAN]=JDQZ(A,B) returns the eigenvectors X and the Jordan % structure JORDAN: A*X=B*X*JORDAN. The diagonal of JORDAN contains the % eigenvalues: LAMBDA=DIAG(JORDAN). JORDAN is an K by K matrix with the % eigenvalues on the diagonal and zero or one on the first upper diagonal % elements. The other entries are zero. % % [X,JORDAN,HISTORY]=JDQZ(A,B) returns also the convergence history. % % [X,JORDAN,Q,Z,S,T,HISTORY]=JDQZ(A,B) % If between four and seven output arguments are required, then Q and Z % are N by K orthonormal, S and T are K by K upper triangular such that % they form a partial generalized Schur decomposition: A*Q=Z*S and % B*Q=Z*T. Then LAMBDA=DIAG(S)./DIAG(T) and X=Q*Y with Y the eigenvectors % of the pair (S,T): S*Y=T*Y*JORDAN (see also OPTIONS.Schur). % % JDQZ(A,B) % JDQZ('Afun','Bfun') % The first input argument is either a square matrix (which can be full % or sparse, symmetric or nonsymmetric, real or complex), or a string % containing the name of an M-file which applies a linear operator to the % columns of a given matrix. In the latter case, the M-file, say Afun.m, % must return the dimension N of the problem with N = Afun([],'dimension'). % For example, JDQZ('fft',...) is much faster than JDQZ(F,...), where F is % the explicit FFT matrix. % If another input argument is a square N by N matrix or the name of an % M-file, then B is this argument (regardless whether A is an M-file or a % matrix). If B has not been specified, then B is assumed to be the % identity unless A is an M-file with two output vectors of dimension N % with [AV,BV]=Afun(V), or with AV=Afun(V,'A') and BV=Afun(V,'B'). % % The remaining input arguments are optional and can be given in % practically any order: % % [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ(A,B,K,SIGMA,OPTIONS) % [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ('Afun','Bfun',K,SIGMA,OPTIONS) % % where % % K an integer, the number of desired eigenvalues. % SIGMA a scalar shift or a two letter string. % OPTIONS a structure containing additional parameters. % % If K is not specified, then K = MIN(N,5) eigenvalues are computed. % % If SIGMA is not specified, then the Kth eigenvalues largest in % magnitude are computed. If SIGMA is a real or complex scalar, then the % Kth eigenvalues nearest SIGMA are computed. If SIGMA is column vector % of size (L,1), then the Jth eigenvalue nearest to SIGMA(MIN(J,L)) % is computed for J=1:K. SIGMA is the "target" for the desired eigenvalues. % If SIGMA is one of the following strings, then it specifies the desired % eigenvalues. % % SIGMA Specified eigenvalues % % 'LM' Largest Magnitude % 'SM' Smallest Magnitude (same as SIGMA = 0) % 'LR' Largest Real part % 'SR' Smallest Real part % 'BE' Both Ends. Computes K/2 eigenvalues % from each end of the spectrum (one more % from the high end if K is odd.) % % If 'TestSpace' is 'Harmonic' (see OPTIONS), then SIGMA = 0 is the % default, otherwise SIGMA = 'LM' is the default. % % % The OPTIONS structure specifies certain parameters in the algorithm. % % Field name Parameter Default % % OPTIONS.Tol Convergence tolerance: 1e-8 % norm(r) <= Tol/SQRT(K) % OPTIONS.jmin Minimum dimension search subspace V K+5 % OPTIONS.jmax Maximum dimension search subspace V jmin+5 % OPTIONS.MaxIt Maximum number of iterations. 100 % OPTIONS.v0 Starting space ones+0.1*rand % OPTIONS.Schur Gives schur decomposition 'no' % If 'yes', then X and JORDAN are % not computed and [Q,Z,S,T,HISTORY] % is the list of output arguments. % OPTIONS.TestSpace Defines the test subspace W 'Harmonic' % 'Standard': W=sigma*A*V+B*V % 'Harmonic': W=A*V-sigma*B*V % 'SearchSpace': W=V % W=V is justified if B is positive % definite. % OPTIONS.Disp Shows size of intermediate residuals 'no' % and the convergence history % OPTIONS.NSigma Take as target for the second and 'no' % following eigenvalues, the best % approximate eigenvalues from the % test subspace. % OPTIONS.Pairs Search for conjugated eigenpairs 'no' % OPTIONS.LSolver Linear solver 'GMRES' % OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,.. % OPTIONS.LS_MaxIt Maximum number it. linear solver 5 % OPTIONS.LS_ell ell for BiCGstab(ell) 4 % OPTIONS.Precond Preconditioner (see below) identity. % OPTIONS.Type_Precond Way of using preconditioner 'left' % % For instance % % options=struct('Tol',1.0e-8,'LSolver','BiCGstab','LS_ell',4,'Precond',M); % % changes the convergence tolerance to 1.0e-8, takes BiCGstab as linear % solver, and takes M as preconditioner (for ways of defining M, see below). % % % PRECONDITIONING. The action M-inverse of the preconditioner M (an % approximation of A-lamda*B) on an N-vector V can be defined in the % OPTIONS % % OPTIONS.Precond % OPTIONS.L_Precond same as OPTIONS.Precond % OPTIONS.U_Precond % OPTIONS.P_Precond % % If no preconditioner has been specified (or is []), then M\V=V (M is % the identity). % If Precond is an N by N matrix, say, K, then % M\V = K\V. % If Precond is an N by 2*N matrix, say, K, then % M\V = U\L\V, where K=[L,U], and L and U are N by N matrices. % If Precond is a string, say, 'Mi', then % if Mi(V,'L') and Mi(V,'U') return N-vectors % M\V = Mi(Mi(V,'L'),'U') % otherwise % M\V = Mi(V) or M\V=Mi(V,'preconditioner'). % Note that Precond and A can be the same string. % If L_Precond and U_Precond are strings, say, 'Li' and 'Ui', % respectively, then % M\V=Ui(Li(V)). % If (P_precond,) L_Precond, and U_precond are N by N matrices, say, % (P,) L, and U, respectively, then % M\V=U\L\(P*V) (P*M=L*U) % % OPTIONS.Type_Precond % The preconditioner can be used as explicit left preconditioner % ('left', default), as explicit right preconditioner ('right') or % implicitly ('impl'). % % % JDQZ without input arguments returns the options and its defaults. % % Gerard Sleijpen. % Copyright (c) 2002 % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology global Qschur Zschur Sschur Tschur ... Operator_MVs Precond_Solves ... MinvZ QastMinvZ if nargin==0 possibilities, return, end %%% Read/set parameters [n,nselect,Sigma,kappa,SCHUR,... jmin,jmax,tol0,maxit,V,AV,BV,TS,DISP,PAIRS,JDV0,FIX_tol,track,NSIGMA,... lsolver,LSpar] = ReadOptions(varargin{1:nargin}); Qschur = zeros(n,0); Zschur=zeros(n,0);; MinvZ = zeros(n,0); QastMinvZ=zeros(0,0); Sschur = []; Tschur=[]; history = []; %%% Return if eigenvalueproblem is trivial if n<2 if n==1, Qschur=1; Zschur=1; [Sschur,Tschur]=MV(1); end if nargout == 0, Lambda=Sschur/Tschur, else [varargout{1:nargout}]=output(history,SCHUR,1,Sschur/Tschur); end, return, end %---------- SET PARAMETERS & STRINGS FOR OUTPUT ------------------------- if TS==0, testspace='sigma(1)''*Av+sigma(2)''*Bv'; elseif TS==1, testspace='sigma(2)*Av-sigma(1)*Bv'; elseif TS==2, testspace='v'; elseif TS==3, testspace='Bv'; elseif TS==4, testspace='Av'; end String=['\r#it=%i #MV=%3i, dim(V)=%2i, |r_%2i|=%6.1e ']; %------------------- JDQZ ----------------------------------------------- % fprintf('Scaling with kappa=%6.4g.',kappa) k=0; nt=0; j=size(V,2); nSigma=size(Sigma,1); it=0; extra=0; Zero=[]; target=[]; tol=tol0/sqrt(nselect); INITIATE=1; JDV=0; rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; time=clock; if TS ~=2 while (k<nselect & it<maxit) %%% Initialize target, test space and interaction matrices if INITIATE, % set new target nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0; if j<2 [V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol); rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[]; j=min(jmin,n-k); end if DETECTED & NSIGMA [Ur,Ul,St,Tt] = SortQZ(WAV,WBV,sigma,kappa); y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y; [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); sigma=ScaleEig(theta); USE_OLD=NSIGMA; rKNOWN=1; lit=10; end NEWSHIFT= 1; if DETECTED & TS<2, NEWSHIFT= ~min(target==sigma); end target=sigma; ttarget=sigma; if ischar(ttarget), ttrack=0; else, ttrack=track; end if NEWSHIFT v=V; Av=AV; Bv=BV; W=eval(testspace); %%% V=RepGS(Qschur,V); [AV,BV]=MV(V); %%% more stability?? %%% W=RepGS(Zschur,eval(testspace)); %%% dangerous if sigma~lambda if USE_OLD, W(:,1)=V(:,1); end, W=RepGS(Zschur,W); WAV=W'*AV; WBV=W'*BV; end INITIATE=0; DETECTED=0; JDV=0; end % if INITIATE %%% Solve the preconditioned correction equation if rKNOWN, if JDV, z=W; q=V; extra=extra+1; if DISP, fprintf(' %2i-d proj.\n',k+j-1), end end if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit); nlit=nlit+1; lit=lit+1; it=it+1; EXPAND=1; rKNOWN=0; JDV=0; end % if rKNOWN %%% Expand the subspaces and the interaction matrices if EXPAND [v,zeta]=RepGS([Qschur,V],t); V=[V,v]; [Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv]; w=eval(testspace); w=RepGS([Zschur,W],w); WAV=[WAV,W'*Av;w'*AV]; WBV=[WBV,W'*Bv;w'*BV]; W=[W,w]; j=j+1; EXPAND=0; %%% Check for stagnation if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end end % if EXPAND %%% Solve projected eigenproblem if USE_OLD [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,y); else [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin); end %%% Compute approximate eigenpair and residual y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y; [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); %%%=== an alternative, but less stable way of computing z ===== % beta=Tt(1,1); alpha=St(1,1); theta=[alpha,beta]; % r=RepGS(Zschur,beta*Av-alpha*Bv,0); nr=norm(r); z=W*Ul(:,1); rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end if DISP, %%% display history fprintf(String,it,Operator_MVs,j,nlit,nr), end history=[history;nr,it,Operator_MVs]; %%% save history %%% check convergence if (nr<tol) %%% EXPAND Schur form Qschur=[Qschur,q]; Zschur=[Zschur,z]; Sschur=[[Sschur;zeros(1,k)],Zschur'*Av]; Tschur=[[Tschur;zeros(1,k)],Zschur'*Bv]; Zero=[Zero,0]; k=k+1; if ischar(target), Target(k,:)=[nt,0,0]; else, Target(k,:)=[0,target]; end if DISP, ShowEig(theta,target,k); end if (k>=nselect), break; end; %%% Expand preconditioned Schur matrix MinvZ=M\Zschur UpdateMinvZ; J=[2:j]; j=j-1; Ur=Ur(:,J); Ul=Ul(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul; WAV=St(J,J); WBV=Tt(J,J); rKNOWN=0; DETECTED=1; USE_OLD=0; %%% check for conjugate pair if PAIRS & (abs(imag(theta(1)/theta(2)))>tol) t=ImagVector(q); % t=conj(q); t=t-q*(q'*t); if norm(t)>tol, t=RepGS([Qschur,V],t,0); if norm(t)>200*tol target=ScaleEig(conj(theta)); EXPAND=1; DETECTED=0; if DISP, fprintf('--- Checking for conjugate pair ---\n'), end end end end INITIATE = ( j==0 & DETECTED); elseif DETECTED %%% To detect whether another eigenpair is accurate enough INITIATE=1; end % if (nr<tol) %%% restart if dim(V)> jmax if j==jmax j=jmin; J=[1:j]; Ur=Ur(:,J); Ul=Ul(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul; WAV=St(J,J); WBV=Tt(J,J); end % if j==jmax end % while k end % if TS~=2 if TS==2 Q0=Qschur; ZastQ=[]; % WAV=V'*AV; WBV=V'*BV; while (k<nselect & it<maxit) %%% Initialize target, test space and interaction matrices if INITIATE & ( nSigma>k | NSIGMA), % set new target nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0; if j<2 [V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol); rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[]; j=min(jmin,n-k);; end if DETECTED & NSIGMA [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,sigma,kappa,1); q=RepGS(Zschur,V*Ur(:,1)); [Av,Bv]=MV(q); [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); sigma=ScaleEig(theta); USE_OLD=NSIGMA; rKNOWN=1; lit=10; end target=sigma; ttarget=sigma; if ischar(ttarget), ttrack=0; else, ttrack=track; end if ~DETECTED %%% additional stabilisation. May not be needed %%% V=RepGS(Zschur,V); [AV,BV]=MV(V); %%% end add. stab. WAV=V'*AV; WBV=V'*BV; end DETECTED=0; INITIATE=0; JDV=0; end % if INITIATE %%% Solve the preconditioned correction equation if rKNOWN, if JDV, z=V; q=V; extra=extra+1; if DISP, fprintf(' %2i-d proj.\n',k+j-1), end end if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit); nlit=nlit+1; lit=lit+1; it=it+1; EXPAND=1; rKNOWN=0; JDV=0; end % if rKNOWN %%% expand the subspaces and the interaction matrices if EXPAND [v,zeta]=RepGS([Zschur,V],t); [Av,Bv]=MV(v); WAV=[WAV,V'*Av;v'*AV,v'*Av]; WBV=[WBV,V'*Bv;v'*BV,v'*Bv]; V=[V,v]; AV=[AV,Av]; BV=[BV,Bv]; j=j+1; EXPAND=0; %%% Check for stagnation if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end end % if EXPAND %%% compute approximate eigenpair if USE_OLD [Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,Ur(:,1)); else [Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin); end %%% Compute approximate eigenpair and residual q=V*Ur(:,1); Av=AV*Ur(:,1); Bv=BV*Ur(:,1); [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end if DISP, %%% display history fprintf(String,it,Operator_MVs, j,nlit,nr), end history=[history;nr,it,Operator_MVs]; %%% save history %%% check convergence if (nr<tol) %%% expand Schur form [q,a]=RepGS(Q0,q); a1=a(k+1,1); a=a(1:k,1); %%% ZastQ=Z'*Q0 Q0=[Q0,q]; %%% the final Qschur ZastQ=[ZastQ,Zschur'*q;z'*Q0]; Zschur=[Zschur,z]; Qschur=[Qschur,z]; Sschur=[[Sschur;Zero],a1\(Zschur'*Av-[Sschur*a;0])]; Tschur=[[Tschur;Zero],a1\(Zschur'*Bv-[Tschur*a;0])]; Zero=[Zero,0]; k=k+1; if ischar(target), Target(k,:)=[nt,0,0]; else, Target(k,:)=[0,target]; end if DISP, ShowEig(theta,target,k); end if (k>=nselect), break; end; UpdateMinvZ; J=[2:j]; j=j-1; rKNOWN=0; DETECTED=1; Ul=Ul(:,J); V=V*Ul; AV=AV*Ul; BV=BV*Ul; WAV=Ul'*WAV*Ul; WBV=Ul'*WBV*Ul; Ul=eye(j); Ur=Ul; %%% check for conjugate pair if PAIRS & (abs(imag(theta(2)/theta(1)))>tol) t=ImagVector(q); if norm(t)>tol, %%% t perp Zschur, t in span(Q0,imag(q)) t=t-Q0*(ZastQ\(Zschur'*t)); if norm(t)>100*tol target=ScaleEig(conj(theta)); EXPAND=1; DETECTED=0; USE_OLD=0; if DISP, fprintf('--- Checking for conjugate pair ---\n'), end end end end INITIATE = ( j==0 & DETECTED); elseif DETECTED %%% To detect whether another eigenpair is accurate enough INITIATE=1; end % if (nr<tol) %%% restart if dim(V)> jmax if j==jmax j=jmin; J=[1:j]; Ur=Ur(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; WAV=Ur'*WAV*Ur; WBV=Ur'*WBV*Ur; Ur=eye(j); end % if jmax end % while k Qschur=Q0; end time_needed=etime(clock,time); if JDV0 & extra>0 & DISP fprintf('\n\n# j-dim. proj.: %2i\n\n',extra) end I=CheckSortSchur(Sigma,kappa); Target(1:length(I),:)=Target(I,:); XKNOWN=0; if nargout == 0 if ~DISP eigenvalues=diag(Sschur)./diag(Tschur) % Result(eigenvalues) return, end else Jordan=[]; X=zeros(n,0); if SCHUR ~= 1 if k>0 [Z,D,Jor]=FindJordan(Sschur,Tschur,SCHUR); DT=abs(diag(D)); DS=abs(diag(Jor)); JT=find(DT<=tol & DS>tol); JS=find(DS<=tol & DT<=tol); msg=''; DT=~isempty(JT); DS=~isempty(JS); if DT msg1='The eigenvalues'; msg2=sprintf(', %i',JT); msg=[msg1,msg2,' are numerically ''Inf''']; end, if DS msg1='The pencil is numerically degenerated in the directions'; msg2=sprintf(', %i',JS); if DT, msg=[msg,sprintf('\n\n')]; end, msg=[msg,msg1,msg2,'.']; end, if (DT | DS), warndlg(msg,'Unreliable directions'), end Jordan=Jor/D; X=Qschur*Z; XKNOWN=1; end end [varargout{1:nargout}]=output(history,SCHUR,X,Jordan); end %-------------- display results ----------------------------------------- if DISP & size(history,1)>0 rs=history(:,1); mrs=max(rs); if mrs>0, rs=rs+0.1*eps*mrs; subplot(2,1,1); t=history(:,2); plot(t,log10(rs),'*-',t,log10(tol)+0*t,':') legend('log_{10} || r_{#it} ||_2') String=sprintf('The test subspace is computed as %s.',testspace); title(String) subplot(2,1,2); t=history(:,3); plot(t,log10(rs),'-*',t,log10(tol)+0*t,':') legend('log_{10} || r_{#MV} ||_2') String=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',... jmin,jmax,tol); title(String) String=sprintf('Correction equation solved with %s.',lsolver); xlabel(String), date=fix(clock); String=sprintf('%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6)); ax=axis; text(0.2*ax(1)+0.8*ax(2),1.2*ax(3)-0.2*ax(4),String) drawnow end Result(Sigma,Target,diag(Sschur),diag(Tschur),tol) end %------------------------ TEST ACCURACY --------------------------------- if k>nselect & DISP fprintf('\n%i additional eigenpairs have been detected.\n',k-nselect) end if k<nselect & DISP fprintf('\nFailed to detect %i eigenpairs.\n',nselect-k) end if (k>0) & DISP Str='time_needed'; texttest(Str,eval(Str)) fprintf('\n%39s: %9i','Number of Operator actions',Operator_MVs) if Precond_Solves fprintf('\n%39s: %9i','Number of preconditioner solves',Precond_Solves) end if 1 if SCHUR ~= 1 & XKNOWN % Str='norm(Sschur*Z-Tschur*Z*Jordan)'; texttest(Str,eval(Str),tol0) ok=1; eval('[AX,BX]=MV(X);','ok=0;') if ~ok, for j=1:size(X,2), [AX(:,j),BX(:,j)]=MV(X(:,j)); end, end Str='norm(AX*D-BX*Jor)'; texttest(Str,eval(Str),tol0) end ok=1; eval('[AQ,BQ]=MV(Qschur);','ok=0;') if ~ok, for j=1:size(Qschur,2), [AQ(:,j),BQ(:,j)]=MV(Qschur(:,j)); end, end if kappa == 1 Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str),tol0) else Str='norm(AQ-Zschur*Sschur)/kappa'; texttest(Str,eval(Str),tol0) end Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str),tol0) I=eye(k); Str='norm(Qschur''*Qschur-I)'; texttest(Str,eval(Str)) Str='norm(Zschur''*Zschur-I)'; texttest(Str,eval(Str)) nrmSschur=max(norm(Sschur),1.e-8); nrmTschur=max(norm(Tschur),1.e-8); Str='norm(tril(Sschur,-1))/nrmSschur'; texttest(Str,eval(Str)) Str='norm(tril(Tschur,-1))/nrmTschur'; texttest(Str,eval(Str)) end fprintf('\n==================================================\n') end if k==0 disp('no eigenvalue could be detected with the required precision') end return %%%======== END JDQZ ==================================================== %%%====================================================================== %%%======== PREPROCESSING =============================================== %%%====================================================================== %%%======== ARNOLDI (for initial spaces) ================================ function [V,AV,BV]=Arnoldi(v,Av,Bv,sigma,jmin,nselect,tol) % Apply Arnoldi with M\(A*sigma(1)'+B*sigma(2)'), to construct an % initial search subspace % global Qschur if ischar(sigma), sigma=[0,1]; end [n,j]=size(v); k=size(Qschur,2); jmin=min(jmin,n-k); if j==0 & k>0 v=RepGS(Qschur,rand(n,1)); [Av,Bv]=MV(v); j=1; end V=v; AV=Av; BV=Bv; while j<jmin; v=[Av,Bv]*sigma'; v0=SolvePrecond(v); if sigma(1)==0 & norm(v0-v)<tol, %%%% then precond=I and target = 0: apply Arnoldi with A sigma=[1,0]; v0=Av; end v=RepGS([Qschur,V],v0); V=[V,v]; [Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv]; j=j+1; end % while return %%%======== END ARNOLDI ================================================= %%%====================================================================== %%%======== POSTPROCESSING ============================================== %%%====================================================================== %%%======== SORT QZ DECOMPOSITION INTERACTION MATRICES ================== function I=CheckSortSchur(Sigma,kappa) % I=CheckSortSchur(Sigma) % Scales Qschur, Sschur, and Tschur such that diag(Tschur) in [0,1] % Reorders the Partial Schur decomposition such that the `eigenvalues' % (diag(S),diag(T)) appear in increasing chordal distance w.r.t. to % Sigma. % If diag(T) is non-singular then Lambda=diag(S)./diag(T) are the % eigenvalues. global Qschur Zschur Sschur Tschur k=size(Sschur,1); if k==0, I=[]; return, end % [AQ,BQ]=MV(Qschur); % Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str)) % Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str)) %--- scale such that diag(Tschur) in [0,1] ---- [Tschur,D]=ScaleT(Tschur); Sschur=D\Sschur; % kappa=max(norm(Sschur,inf)/norm(Tschur,inf),1); s=diag(Sschur); t=diag(Tschur); I=(1:k)'; l=size(Sigma,1); for j=1:k J0=(j:k)'; J=SortEig(s(I(J0)),t(I(J0)),Sigma(min(j,l),:),kappa); I(J0)=I(J0(J)); end if ~min((1:k)'==I) [Q,Z,Sschur,Tschur]=SwapQZ(eye(k),eye(k),Sschur,Tschur,I); [Tschur,D2]=ScaleT(Tschur); Sschur=D2\Sschur; Qschur=Qschur*Q; Zschur=Zschur*(D*Z*D2); else Zschur=Zschur*D; end return %======================================================================== function [T,D]=ScaleT(T) % scale such that diag(T) in [0,1] ---- n=sign(diag(T)); n=n+(n==0); D=diag(n); T=D\T; IT=imag(T); RT=real(T); T=RT+IT.*(abs(IT)>eps*abs(RT))*sqrt(-1); return %%%======== COMPUTE SORTED JORDAN FORM ================================== function [X,D,Jor]=FindJordan(S,T,SCHUR) % [X,D,J]=FINDJORDAN(S,T) % For S and T k by k upper triangular matrices % FINDJORDAN computes the Jordan decomposition. % X is a k by k matrix of eigenvectors and principal vectors % D and J are k by matrices, D is diagonal, J is Jordan % such that S*X*D=T*X*J. (diag(D),diag(J)) are the eigenvalues. % If D is non-singular then Lambda=diag(J)./diag(D) % are the eigenvalues. % coded by Gerard Sleijpen, May, 2002 k=size(S,1); s=diag(S); t=diag(T); n=sign(t); n=n+(n==0); D=sqrt(conj(s).*s+conj(t).*t).*n; S=diag(D)\S; T=diag(D)\T; D=diag(diag(T)); if k<1, if k==0, X=[]; D=[]; Jor=[]; end if k==1, X=1; Jor=s; end return end tol=k*(norm(S,1)+norm(T,1))*eps; [X,Jor,I]=PseudoJordan(S,T,tol); if SCHUR == 0 for l=1:length(I)-1 if I(l)<I(l+1)-1, J=[I(l):I(l+1)-1]; [U,JJor]=JordanBlock(Jor(J,J),tol); X(:,J)=X(:,J)*U; Jor(J,J)=JJor; end end end Jor=Jor+diag(diag(S)); Jor=Jor.*(abs(Jor)>tol); return %================================================== function [X,Jor,J]=PseudoJordan(S,T,delta) % Computes a pseudo-Jordan decomposition for the upper triangular % matrices S and T with ordered diagonal elements. % S*X*(diag(diag(T)))=T*X*(diag(diag(S))+Jor) % with X(:,i:j) orthonormal if its % columns span an invariant subspace of (S,T). k=size(S,1); s=diag(S); t=diag(T); Jor=zeros(k); X=eye(k); J=1; for i=2:k I=[1:i]; C=t(i,1)*S(I,I)-s(i,1)*T(I,I); C(i,i)=norm(C,inf); if C(i,i)>0 tol=delta*C(i,i); for j=i:-1:1 if j==1 | abs(C(j-1,j-1))>tol, break; end end e=zeros(i,1); e(i,1)=1; if j==i J=[J,i]; q=C\e; X(I,i)=q/norm(q); else q=X(I,j:i-1); q=[C,T(I,I)*q;q',zeros(i-j)]\[e;zeros(i-j,1)]; q=q/norm(q(I,1)); X(I,i)=q(I,1); Jor(j:i-1,i)=-q(i+1:2*i-j,1); end end end J=[J,k+1]; return %================================================== function [X,Jor,U]=JordanBlock(A,tol) % If A is nilpotent, then A*X=X*Jor with % Jor a Jordan block % k=size(A,1); Id=eye(k); U=Id; aa=A; j=k; jj=[]; J=1:k; while j>0 [u,s,v]=svd(aa); U(:,J)=U(:,J)*v; sigma=diag(s); delta=tol; J=find(sigma<delta); if isempty(J),j=0; else, j=min(J)-1; end jj=[jj,j]; if j==0, break, end aa=v'*u*s; J=1:j; aa=aa(J,J); end Jor=U'*A*U; Jor=Jor.*(abs(Jor)>tol); l=length(jj); jj=[jj(l:-1:1),k]; l2=jj(2)-jj(1); J=jj(1)+(1:l2); JX=Id(:,J); X=Id; for j=2:l l1=l2+1; l2=jj(j+1)-jj(j); J2=l1:l2; J=jj(j)+(1:l2); JX=Jor*JX; D=diag(sqrt(diag(JX'*JX))); JX=JX/D; [Q,S,V]=svd(JX(J,:)); JX=[JX,Id(:,J)*Q(:,J2)]; X(:,J)=JX; end J=[]; for i=1:l2 for k=l:-1:1 j=jj(k)+i; if j<=jj(k+1), J=[J,j]; end end end X=X(:,J); Jor=X\(Jor*X); X=U*X; Jor=Jor.*(abs(Jor)>100*tol); return %%%======== END JORDAN FORM ============================================= %%%======== OUTPUT ====================================================== function varargout=output(history,SCHUR,X,Lambda) global Qschur Zschur Sschur Tschur if nargout == 1, varargout{1}=diag(Sschur)./diag(Tschur); return, end if nargout > 2, varargout{nargout}=history; end if nargout < 6 & SCHUR == 1 if nargout >1, varargout{1}=Qschur; varargout{2}=Zschur; end if nargout >2, varargout{3}=Sschur; end if nargout >3, varargout{4}=Tschur; end end %-------------- compute eigenpairs -------------------------------------- if SCHUR ~= 1 varargout{1}=X; varargout{2}=Lambda; if nargout >3, varargout{3}=Qschur; varargout{4}=Zschur; end if nargout >4, varargout{5}=Sschur; end if nargout >5, varargout{6}=Tschur; end end return %%%====================================================================== %%%======== UPDATE PRECONDITIONED SCHUR VECTORS ========================= %%%====================================================================== function UpdateMinvZ global Qschur Zschur MinvZ QastMinvZ [n,k]=size(Qschur); if k==1, MinvZ=zeros(n,0); QastMinvZ = []; end Minv_z=SolvePrecond(Zschur(:,k)); QastMinvZ=[[QastMinvZ;Qschur(:,k)'*MinvZ],Qschur'*Minv_z]; MinvZ=[MinvZ,Minv_z]; return %%%====================================================================== %%%======== SOLVE CORRECTION EQUATION =================================== %%%====================================================================== function [t,xtol]=SolvePCE(theta,q,z,r,lsolver,par,nit) global Qschur Zschur Q=[Qschur,q]; Z=[Zschur,z]; switch lsolver case 'exact' [t,xtol] = exact(theta,Q,Z,r); case {'gmres','cgstab','olsen'} [MZ,QMZ]=FormPM(q,z); %%% solve preconditioned system [t,xtol] = feval(lsolver,theta,Q,Z,MZ,QMZ,r,spar(par,nit)); end return %------------------------------------------------------------------------ function [MZ,QMZ]=FormPM(q,z) % compute vectors and matrices for skew projection global Qschur MinvZ QastMinvZ Minv_z=SolvePrecond(z); QMZ=[QastMinvZ,Qschur'*Minv_z;q'*MinvZ,q'*Minv_z]; MZ=[MinvZ,Minv_z]; return %%%====================================================================== %%%======== LINEAR SOLVERS ============================================== %%%====================================================================== function [x,xtol] = exact(theta,Q,Z,r) % produces the exact solution if matrices are given % Is only feasible for low dimensional matrices % Only of interest for experimental purposes % global Operator_A Operator_B n=size(r,1); if ischar(Operator_A) [MZ,QMZ]=FormPM(Q(:,end),Z(:,end)); if n>200 [x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'cgstab',[1.0e-10,500,4]); else [x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'gmres',[1.0e-10,100]); end return end k=size(Q,2); Aug=[theta(2)*Operator_A-theta(1)*Operator_B,Z;Q',zeros(k,k)]; x=Aug\[r;zeros(k,1)]; x([n+1:n+k],:)=[]; xtol=1; % L=eig(full(Aug)); plot(real(L),imag(L),'*'), pause %%% [At,Bt]=MV(x); At=theta(2)*At-theta(1)*Bt; %%% xtol=norm(r-At+Z*(Z'*At))/norm(r); return %%%===== Iterative methods ============================================== function [r,xtol] = olsen(theta,Q,Z,MZ,M,r,par) % returns the preconditioned residual as approximate solution % May be sufficient in case of an excellent preconditioner r=SkewProj(Q,MZ,M,SolvePrecond(r)); xtol=0; return %------------------------------------------------------------------------ function [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par) % BiCGstab(ell) with preconditioning % [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner % % This function is specialized for use in JDQZ. % integer nmv: number of matrix multiplications % rnrm: relative residual norm % % par=[tol,mxmv,ell] where % integer m: max number of iteration steps % real tol: residual reduction % % rnrm: obtained residual reduction % % -- References: ETNA % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization -- % global Precond_Type tol=par(1); max_it=par(2); l=par(3); n=size(r,1); rnrm=1; nmv=0; if max_it < 2 | tol>=1, x=r; return, end %%% 0 step of bicgstab eq. 1 step of bicgstab %%% Then x is a multiple of b TP=Precond_Type; if TP==0, r=SkewProj(Q,MZ,M,SolvePrecond(r)); tr=r; else, tr=RepGS(Z,r); end rnrm=norm(r); snrm=rnrm; tol=tol*snrm; sigma=1; omega=1; x=zeros(n,1); u=zeros(n,1); J1=2:l+1; %%% HIST=[0,1]; if TP <2 %% explicit preconditioning % -- Iteration loop while (nmv < max_it) sigma=-omega*sigma; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; u(:,j+1)=PreMV(theta,Q,MZ,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; r=r-alp*u(:,2:j+1); r(:,j+1)=PreMV(theta,Q,MZ,M,r(:,j)); x=x+alp*u(:,1); G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1)); if rnrm<tol, l=j; J1=2:l+1; r=r(:,1:l+1); break, end end nmv = nmv+2*l; for i=2:l+1 G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)'; end if TP, g=Z'*r; G=G-g'*g; end d=G(J1,1); gamma=G(J1,J1)\d; rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space %%% HIST=[HIST;[nmv,rnrm/snrm]]; x=x+r(:,1:l)*gamma; if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u omega=gamma(l,1); gamma=[1;-gamma]; u=u*gamma; r=r*gamma; if TP, g=g*gamma; r=r-Z*g; end % rnrm = norm(r); end else %% implicit preconditioning I=eye(2*l); v0=I(:,1:l); s0=I(:,l+1:2*l); y0=zeros(2*l,1); V=zeros(n,2*l); while (nmv < max_it) sigma=-omega*sigma; y=y0; v=v0; s=s0; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; if j>1, %%% collect the updates for x in l-space v(:,1:j-1)=s(:,1:j-1)-bet*v(:,1:j-1); end [u(:,j+1),V(:,j)]=PreMV(theta,Q,MZ,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; r=r-alp*u(:,2:j+1); if j>1, s(:,1:j-1)=s(:,1:j-1)-alp*v(:,2:j); end [r(:,j+1),V(:,l+j)]=PreMV(theta,Q,MZ,M,r(:,j)); y=y+alp*v(:,1); G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1)); if rnrm<tol, l=j; J1=2:l+1; s=s(:,1:l); break, end end nmv = nmv+2*l; for i=2:l+1 G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)'; end g=Z'*r; G=G-g'*g; %%% but, do the orth to Z implicitly d=G(J1,1); gamma=G(J1,J1)\d; rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space x=x+V*(y+s*gamma); %%% HIST=[HIST;[nmv,rnrm/snrm]]; if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u omega=gamma(l,1); gamma=[1;-gamma]; u=u*gamma; r=r*gamma; g=g*gamma; r=r-Z*g; %%% Do the orth to Z explicitly %%% In exact arithmetic not needed, but %%% appears to be more stable. end end if TP==1, x=SkewProj(Q,MZ,M,SolvePrecond(x)); end rnrm = rnrm/snrm; %%% plot(HIST(:,1),log10(HIST(:,2)+eps),'*'), drawnow return %---------------------------------------------------------------------- function [v,rnrm] = gmres0(theta,Q,Z,MZ,M,v,par) % GMRES % [x,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner % % If used as implicit preconditioner then FGMRES. % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % rnrm: obtained residual reduction % % -- References: Saad & Schultz SISC 1986 % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization global Precond_Type tol=par(1); max_it=par(2); n = size(v,1); rnrm = 1; j=0; if max_it < 2 | tol>=1, return, end %%% 0 step of gmres eq. 1 step of gmres %%% Then x is a multiple of b H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)]; TP=Precond_Type; TP=Precond_Type; if TP==0 v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0; else v=RepGS(Z,v); end V = [v]; tol = tol * rnrm; y = [ rnrm ; zeros(max_it,1) ]; while (j < max_it) & (rnrm > tol), j=j+1; [v,w]=PreMV(theta,Q,MZ,M,v); if TP if TP == 2, W=[W,w]; end v=RepGS(Z,v,0); end [v,h] = RepGS(V,v); H(1:size(h,1),j) = h; V = [V, v]; for i = 1:j-1, a = Rot(:,i); H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j); end J=[j, j+1]; a=H(J,j); if a(2) ~= 0 cs = norm(a); a = a/cs; Rot(:,j) = a; H(J,j) = [cs; 0]; y(J) = [a'; -a(2) a(1)]*y(J); end rnrm = abs(y(j+1)); end J=[1:j]; if TP == 2 v = W(:,J)*(H(J,J)\y(J)); else v = V(:,J)*(H(J,J)\y(J)); end if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end return %%%====================================================================== function [v,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % GMRES % [x,nmv,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner. % % If used as implicit preconditioner, then FGMRES. % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Saad % Same as gmres0. However this variant uses MATLAB built-in functions % slightly more efficient (see Sleijpen and van den Eshof). % % % Gerard Sleijpen ([email protected]) % Copyright (c) 2002, Gerard Sleijpen global Precond_Type % -- Initialization tol=par(1); max_it=par(2); n = size(v,1); j=0; if max_it < 2 | tol>=1, rnrm=1; return, end %%% 0 step of gmres eq. 1 step of gmres %%% Then x is a multiple of b H = zeros(max_it +1,max_it); Gamma=1; rho=1; TP=Precond_Type; if TP==0 v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0; else v=RepGS(Z,v); rho0=1; end V = zeros(n,0); W=zeros(n,0); tol0 = 1/(tol*tol); %% HIST=1; while (j < max_it) & (rho < tol0) V=[V,v]; j=j+1; [v,w]=PreMV(theta,Q,MZ,M,v); if TP if TP == 2, W=[W,w]; end v=RepGS(Z,v,0); end [v,h] = RepGS(V,v); H(1:size(h,1),j)=h; gamma=H(j+1,j); if gamma==0, break %%% Lucky break-down else gamma= -Gamma*h(1:j)/gamma; Gamma=[Gamma,gamma]; rho=rho+gamma'*gamma; end %% HIST=[HIST;(gamma~=0)/sqrt(rho)]; end if gamma==0; %%% Lucky break-down e1=zeros(j,1); e1(1)=rho0; rnrm=0; if TP == 2 v=W*(H(1:j,1:j)\e1); else v=V*(H(1:j,1:j)\e1); end else %%% solve in least square sense e1=zeros(j+1,1); e1(1)=rho0; rnrm=1/sqrt(rho); if TP == 2 v=W*(H(1:j+1,1:j)\e1); else v=V*(H(1:j+1,1:j)\e1); end end if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end %% HIST=log10(HIST+eps); J=[0:size(HIST,1)-1]'; %% plot(J,HIST(:,1),'*'); drawnow return %%%======== END SOLVE CORRECTION EQUATION =============================== %%%====================================================================== %%%======== BASIC OPERATIONS ============================================ %%%====================================================================== function [Av,Bv]=MV(v) % [y,z]=MV(x) % y=A*x, z=B*x % y=MV(x,theta) % y=(A-theta*B)*x % global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params Bv=v; switch Operator_Form case 1 % both Operator_A and B are strings Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=feval(Operator_B,Operator_Params{:}); case 2 Operator_Params{1}=v; [Av,Bv]=feval(Operator_A,Operator_Params{:}); case 3 Operator_Params{1}=v; Operator_Params{2}='A'; Av=feval(Operator_A,Operator_Params{:}); Operator_Params{2}='B'; Bv=feval(Operator_A,Operator_Params{:}); case 4 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=Operator_B*v; case 5 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); case 6 Av=Operator_A*v; Operator_Params{1}=v; Bv=feval(Operator_B,Operator_Params{:}); case 7 Av=Operator_A*v; Bv=Operator_B*v; case 8 Av=Operator_A*v; end Operator_MVs = Operator_MVs +size(v,2); % [Av(1:5,1),Bv(1:5,1)], pause return %------------------------------------------------------------------------ function y=SolvePrecond(y); global Precond_Form Precond_L Precond_U Precond_P Precond_Params Precond_Solves switch Precond_Form case 0, case 1, Precond_Params{1}=y; y=feval(Precond_L,Precond_Params{:}); case 2, Precond_Params{1}=y; Precond_Params{2}='preconditioner'; y=feval(Precond_L,Precond_Params{:}); case 3, Precond_Params{1}=y; Precond_Params{1}=feval(Precond_L,Precond_Params{:}); y=feval(Precond_U,Precond_Params{:}); case 4, Precond_Params{1}=y; Precond_Params{2}='L'; Precond_Params{1}=feval(Precond_L,Precond_Params{:}); Precond_Params{2}='U'; y=feval(Precond_L,Precond_Params{:}); case 5, y=Precond_L\y; case 6, y=Precond_U\(Precond_L\y); case 7, y=Precond_U\(Precond_L\(Precond_P*y)); end if Precond_Form Precond_Solves = Precond_Solves +size(y,2); end %% y(1:5,1), pause return %------------------------------------------------------------------------ function [v,u]=PreMV(theta,Q,Z,M,v) % v=Atilde*v global Precond_Type if Precond_Type u=SkewProj(Q,Z,M,SolvePrecond(v)); [v,w]=MV(u); v=theta(2)*v-theta(1)*w; else [v,u]=MV(v); u=theta(2)*v-theta(1)*u; v=SkewProj(Q,Z,M,SolvePrecond(u)); end return %------------------------------------------------------------------------ function r=SkewProj(Q,Z,M,r); if ~isempty(Q), r=r-Z*(M\(Q'*r)); end return %------------------------------------------------------------------------ function ppar=spar(par,nit) k=size(par,2)-2; ppar=par(1,k:k+2); if k>1 if nit>k ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k)); else ppar(1,1)=par(1,max(nit,1)); end end ppar(1,1)=max(ppar(1,1),1.0e-8); return %------------------------------------------------------------------------ function u=ImagVector(u) % computes "essential" imaginary part of a vector maxu=max(u); maxu=maxu/abs(maxu); u=imag(u/maxu); return %------------------------------------------------------------------------ function Sigma=ScaleEig(Sigma) % % n=sign(Sigma(:,2)); n=n+(n==0); d=sqrt((Sigma.*conj(Sigma))*[1;1]).*n; Sigma=diag(d)\Sigma; return %%%======== COMPUTE r AND z ============================================= function [r,z,nrm,theta]=Comp_rz(E,kappa) % % [r,z,nrm,theta]=Comp_rz(E) % computes the direction r of the minimal residual, % the left projection vector z, % the approximate eigenvalue theta % % [r,z,nrm,theta]=Comp_rz(E,kappa) % kappa is a scaling factor. % % coded by Gerard Sleijpen, version Januari 7, 1998 if nargin == 1 kappa=norm(E(:,1))/norm(E(:,2)); kappa=2^(round(log2(kappa))); end if kappa ~=1, E(:,1)=E(:,1)/kappa; end [Q,sigma,u]=svd(E,0); %%% E*u=Q*sigma, sigma(1,1)>sigma(2,2) r=Q(:,2); z=Q(:,1); nrm=sigma(2,2); % nrm=nrm/sigma(1,1); nrmz=sigma(1,1) u(1,:)=u(1,:)/kappa; theta=[-u(2,2),u(1,2)]; return %%%======== END computation r and z ===================================== %%%====================================================================== %%%======== Orthogonalisation =========================================== %%%====================================================================== function [V,R]=RepGS(Z,V,gamma) % % Orthonormalisation using repeated Gram-Schmidt % with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion % % Q=RepGS(V) % The n by k matrix V is orthonormalized, that is, % Q is an n by k orthonormal matrix and % the columns of Q span the same space as the columns of V % (in fact the first j columns of Q span the same space % as the first j columns of V for all j <= k). % % Q=RepGS(Z,V) % Assuming Z is n by l orthonormal, V is orthonormalized against Z: % [Z,Q]=RepGS([Z,V]) % % Q=RepGS(Z,V,gamma) % With gamma=0, V is only orthogonalized against Z % Default gamma=1 (the same as Q=RepGS(Z,V)) % % [Q,R]=RepGS(Z,V,gamma) % if gamma == 1, V=[Z,Q]*R; else, V=Z*R+Q; end % coded by Gerard Sleijpen, March, 2002 % if nargin == 1, V=Z; Z=zeros(size(V,1),0); end if nargin <3, gamma=1; end [n,dv]=size(V); [m,dz]=size(Z); if gamma, l0=min(dv+dz,n); else, l0=dz; end R=zeros(l0,dv); if dv==0, return, end if dz==0 & gamma==0, return, end % if m~=n % if m<n, Z=[Z;zeros(n-m,dz)]; end % if m>n, V=[V;zeros(m-n,dv)]; n=m; end % end if (dz==0 & gamma) j=1; l=1; J=1; q=V(:,1); nr=norm(q); R(1,1)=nr; while nr==0, q=rand(n,1); nr=norm(q); end, V(:,1)=q/nr; if dv==1, return, end else j=0; l=0; J=[]; end while j<dv, j=j+1; q=V(:,j); nr_o=norm(q); nr=eps*nr_o; if dz>0, yz=Z'*q; q=q-Z*yz; end if l>0, y=V(:,J)'*q; q=q-V(:,J)*y; end nr_n=norm(q); while (nr_n<0.5*nr_o & nr_n > nr) if dz>0, sz=Z'*q; q=q-Z*sz; yz=yz+sz; end if l>0, s=V(:,J)'*q; q=q-V(:,J)*s; y=y+s; end nr_o=nr_n; nr_n=norm(q); end if dz>0, R(1:dz,j)=yz; end if l>0, R(dz+J,j)=y; end if ~gamma V(:,j)=q; elseif l+dz<n, l=l+1; if nr_n <= nr % expand with a random vector % if nr_n==0 V(:,l)=RepGS([Z,V(:,J)],rand(n,1)); % else % which can be numerical noice % V(:,l)=q/nr_n; % end else V(:,l)=q/nr_n; R(dz+l,j)=nr_n; end J=[1:l]; end end % while j if gamma & l<dv, V=V(:,J); end return %%%======== END Orthogonalisation ====================================== %%%====================================================================== %%%======== Sorts Schur form ============================================ %%%====================================================================== function [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u) % % [Q,Z,S,T]=SortQZ(A,B,tau) % A and B are k by k matrices, tau is a complex pair [alpha,beta]. % SortQZ computes the qz-decomposition of (A,B) with prescribed % ordering: A*Q=Z*S, B*Q=Z*T; % Q and Z are unitary k by k matrices, % S and T are upper triangular k by k matrices. % The ordering is as follows: % (diag(S),diag(T)) are the eigenpairs of (A,B) ordered % with increasing "chordal distance" w.r.t. tau. % % If tau is a scalar then [tau,1] is used. % Default value for tau is tau=0, i.e., tau=[0,1]. % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa) % kappa scales A first: A/kappa. Default kappa=1. % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma) % Sorts the first MAX(gamma,1) elements. Default: gamma=k % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u) % Now, with ordering such that angle u and Q(:,1) is less than 45o, % and, except for the first pair, (diag(S),diag(T)) are % with increasing "chordal distance" w.r.t. tau. % If such an ordering does not exist, ordering is as without u. % % coded by Gerard Sleijpen, version April, 2002 k=size(A,1); if k==1, Q=1; Z=1; S=A;T=B; return, end kk=k-1; if nargin < 3, tau=[0,1]; end if nargin < 4, kappa=1; end if nargin > 4, kk=max(1,min(gamma,k-1)); end %% kappa=max(norm(A,inf)/max(norm(B,inf),1.e-12),1); %% kappa=2^(round(log2(kappa))); %%%------ compute the qz factorization ------- [S,T,Z,Q]=qz(A,B); Z=Z'; % kkappa=max(norm(A,inf),norm(B,inf)); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) %%%------ scale the eigenvalues -------------- t=diag(T); n=sign(t); n=n+(n==0); D=diag(n); Q=Q/D; S=S/D; T=T/D; %%%------ sort the eigenvalues --------------- I=SortEig(diag(S),real(diag(T)),tau,kappa); %%%------ swap the qz form ------------------- [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk)); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) if nargin < 6 | size(u,2) ~= 1 return else %%% repeat SwapQZ if angle is too small kk=min(size(u,1),k); J=1:kk; u=u(J,1)'*Q(J,:); if abs(u(1,1))>0.7, return, end for j=2:kk J=1:j; if norm(u(1,J))>0.7 J0=[j,1:j-1]; [Qq,Zz,Ss,Tt]=SwapQZ(eye(j),eye(j),S(J,J),T(J,J),J0); if abs(u(1,J)*Qq(:,1))>0.71 Q(:,J)=Q(:,J)*Qq; Z(:,J)=Z(:,J)*Zz; S(J,J)=Ss; S(J,j+1:k)=Zz'*S(J,j+1:k); T(J,J)=Tt; T(J,j+1:k)=Zz'*T(J,j+1:k); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) fprintf(' Took %2i:%6.4g\n',j,S(1,1)./T(1,1)) return end end end disp([' Selection problem: took ',num2str(1)]) return end %%%====================================================================== function I=SortEig(s,t,sigma,kappa); % % I=SortEig(S,T,SIGMA) sorts the indices of [S,T] as prescribed by SIGMA % S and T are K-vectors. % % If SIGMA=[ALPHA,BETA] is a complex pair then % if CHORDALDISTANCE % sort [S,T] with increasing chordal distance w.r.t. SIGMA. % else % sort S./T with increasing distance w.r.t. SIGMA(1)/SIGMA(2) % % The chordal distance D between a pair A and a pair B is % defined as follows. % Scale A by a scalar F such that NORM(F*A)=1. % Scale B by a scalar G such that NORM(G*B)=1. % Then D(A,B)=SQRT(1-ABS((F*A)*(G*B)')). % % I=SortEig(S,T,SIGMA,KAPPA). Kappa is a caling that effects the % chordal distance: [S,KAPPA*T] w.r.t. [SIGMA(1),KAPPA*SIGMA(2)]. % coded by Gerard Sleijpen, version April 2002 global CHORDALDISTANCE if ischar(sigma) warning off, s=s./t; warning on switch sigma case 'LM' [s,I]=sort(-abs(s)); case 'SM' [s,I]=sort(abs(s)); case 'LR'; [s,I]=sort(-real(s)); case 'SR'; [s,I]=sort(real(s)); case 'BE'; [s,I]=sort(real(s)); I=twistdim(I,1); end elseif CHORDALDISTANCE if kappa~=1, t=kappa*t; sigma(2)=kappa*sigma(2); end n=sqrt(s.*conj(s)+t.*t); [s,I]=sort(-abs([s,t]*sigma')./n); else warning off, s=s./t; warning on if sigma(2)==0; [s,I]=sort(-abs(s)); else, [s,I]=sort(abs(s-sigma(1)/sigma(2))); end end return %------------------------------------------------------------------------ function t=twistdim(t,k) d=size(t,k); J=1:d; J0=zeros(1,2*d); J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J); if k==1, t=t(I,:); else, t=t(:,I); end return %%%====================================================================== function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I) % [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P) % QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular. % P is the first part of a permutation of (1:K)'. % % Then Q and Z are K by K unitary, S and T are K by K upper triangular, % such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have % A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where % LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT). % % Computation uses Givens rotations. % % coded by Gerard Sleijpen, version October 12, 1998 kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end while j<=kk i=I(j); for k = i-1:-1:j, %%% i>j, move ith eigenvalue to position j J = [k,k+1]; q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J); if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G; end if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end if q(2) ~= 0 q=q/norm(q); G = [q';q(2),-q(1)]; Z(:,J) = Z(:,J)*G'; S(J,:) = G*S(J,:); T(J,:) = G*T(J,:); end T(k+1,k) = 0; S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %------------------------------------------------------------------------ function [Q,Z,S,T]=SwapQZ0(Q,Z,S,T,I) % % [Q,Z,S,T]=sortqz0(A,B,s,t,k) % A and B are k by k matrices, t and s are k vectors such that % (t(i),s(i)) eigenpair (A,B), i.e. t(i)*A-s(i)*B singular. % Computes the Schur form with a ordering prescribed by (t,s): % A*Q=Z*S, B*Q=Z*T such that diag(S)./diag(T)=s./t. % Computation uses Householder reflections. % % coded by Gerard Sleijpen, version October 12, 1997 k=size(S,1); s=diag(S); t=diag(T); s=s(I,1); t=t(I,1); for i=1:k-1 %%% compute q s.t. C*q=(t(i,1)*S-s(i,1)*T)*q=0 C=t(i,1)*S(i:k,i:k)-s(i,1)*T(i:k,i:k); [q,r,p]=qr(C); %% C*P=Q*R %% check whether last but one diag. elt r nonzero j=k-i; while abs(r(j,j))<eps*norm(r); j=j-1; end; j=j+1; r(j,j)=1; e=zeros(j,1); e(j,1)=1; q=p*([r(1:j,1:j)\e;zeros(k-i+1-j,1)]); q=q/norm(q);%% C*q %%% end computation q z=conj(s(i,1))*S(i:k,i:k)*q+conj(t(i,1))*T(i:k,i:k)*q; z=z/norm(z); a=q(1,1); if a ~=0, a=abs(a)/a; q=a*q; end a=z(1,1); if a ~=0, a=abs(a)/a; z=a*z; end q(1,1)=q(1,1)+1; q=q/norm(q); q=[zeros(i-1,1);q]; z(1,1)=z(1,1)+1; z=z/norm(z); z=[zeros(i-1,1);z]; S=S-(S*q)*(2*q)'; S=S-(2*z)*(z'*S); T=T-(T*q)*(2*q)'; T=T-(2*z)*(z'*T); Q=Q-(Q*q)*(2*q)'; Z=Z-(Z*z)*(2*z)'; end return %%%======== END sort QZ decomposition interaction matrices ============== %%%====================================================================== %%%======== INITIALIZATION ============================================== %%%====================================================================== function MyClear global Operator_Form Operator_A Operator_B Operator_Params ... Precond_L Precond_U Precond_P Precond_Params ... Precond_Form Precond_Type ... Operator_MVs Precond_Solves ... CHORDALDISTANCE ... Qschur Zschur Sschur Tschur ... MinvZ QastMinvZ return %%%====================================================================== function [n,nselect,Sigma,kappa,SCHUR,... jmin,jmax,tol,maxit,V,AV,BV,TS,DISP,PAIRS,JDV,FIX,track,NSIGMA,... lsolver,par] = ReadOptions(varargin) % Read options and set defaults global Operator_Form Operator_A Operator_B Operator_Params ... Precond_Form Precond_L Precond_U Precond_P Precond_Params ... CHORDALDISTANCE Operator_A = varargin{1}; n=CheckMatrix(Operator_A,1); % defaults %%%% search for 'xx' in fieldnames nselect0= 5; maxit = 200; %%%% 'ma' SCHUR = 0; %%%% 'sch' tol = 1e-8; %%%% 'to' DISP = 0; %%%% 'di' p0 = 5; %%% jmin=nselect+p0 %%%% 'jmi' p1 = 5; %%% jmax=jmin+p1 %%%% 'jma' TS = 1; %%%% 'te' PAIRS = 0; %%%% 'pai' JDV = 0; %%%% 'av' track = 1e-4; %%%% 'tr' FIX = 1000; %%%% 'fix' NSIGMA = 0; %%%% 'ns' CHORD = 1; %%%% 'ch' lsolver = 'gmres'; %%%% 'lso' ls_maxit= 200; %%%% 'ls_m' ls_tol = [0.7,0.49]; %%%% 'ls_t' ell = 4; %%%% 'ls_e' TP = 0; %%%% 'ty' L = []; %%%% 'l_' U = []; %%%% 'u_' P = []; %%%% 'p_' kappa = 1; %%%% 'sca' V0 = 'ones(n,1)+rand(n,1)'; %%%% 'v0' %% initiation nselect=[]; Sigma=[]; options=[]; Operator_B=[]; jmin=-1; jmax=-1; V=[]; AV=[]; BV=[]; par=[]; %------------------------------------------------ %------- Find quantities ------------------------ %------------------------------------------------ jj=[]; for j = 2:nargin if isstruct(varargin{j}) options = varargin{j}; elseif ischar(varargin{j}) s=varargin{j}; if exist(s)==2 & isempty(Operator_B) Operator_B=s; elseif length(s) == 2 & isempty(Sigma) s=upper(s); switch s case {'LM','SM','LR','SR','BE'}, Sigma=s; otherwise jj=[jj,j]; end else jj=[jj,j]; end elseif min([n,n]==size(varargin{j})) & isempty(Operator_B) Operator_B=varargin{j}; elseif length(varargin{j}) == 1 s = varargin{j}; if isempty(nselect) & isreal(s) & (s == fix(s)) & (s > 0) nselect = min(n,s); elseif isempty(Sigma) Sigma = s; else jj=[jj,j]; end elseif min(size(varargin{j}))==1 & isempty(Sigma) Sigma = varargin{j}; if size(Sigma,1)==1, Sigma=Sigma'; end elseif min(size(varargin{j}))==2 & isempty(Sigma) Sigma = varargin{j}; if size(Sigma,2)>2 , Sigma=Sigma'; end else jj=[jj,j]; end end %------- find parameters for operators ----------- Operator_Params=[]; Operator_Params{2}=''; k=length(jj); if k>0 Operator_Params(3:k+2)=varargin(jj); if ~ischar(Operator_A) msg=sprintf(', %i',jj); msg=sprintf('Input argument, number%s, not recognized.',msg); button=questdlg(msg,'Input arguments','Ignore','Stop','Ignore'); if strcmp(button,'Stop'), n=-1; return, end end end %------- operator B ----------------------------- if isempty(Operator_B) if ischar(Operator_A) Operator_Form=2; % or Operator_Form=3, or Operator_Form=5; else Operator_Form=8; end else if ischar(Operator_B) if ischar(Operator_A), Operator_Form=1; else, Operator_Form=6; end elseif ischar(Operator_A) Operator_Form=4; else Operator_Form=7; end end if n<2, return, end %------- number of eigs to be computed ---------- if isempty(nselect), nselect=min(n,nselect0); end %------------------------------------------------ %------- Analyse Options ------------------------ %------------------------------------------------ fopts = []; if ~isempty(options), fopts = fieldnames(options); end %------- preconditioner ------------------------- Precond_L=findfield(options,fopts,'pr',[]); [L,ok]=findfield(options,fopts,'l_',Precond_L); if ok & ~isempty(Precond_L), msg =sprintf('A preconditioner is defined in'); msg =[msg,sprintf('\n''Precond'', but also in ''L_precond''.')]; msg=[msg,sprintf('\nWhat is the correct one?')]; button=questdlg(msg,'Preconditioner','L_Precond','Precond','L_Precond'); if strcmp(button,'L_Precond'), Precond_L = L; end else Precond_L = L; end if ~isempty(Precond_L) Precond_U=findfield(options,fopts,'u_',[]); Precond_P=findfield(options,fopts,'p_',[]); end Precond_Params=[]; Precond_Params{2}=''; Params=findfield(options,fopts,'par',[]); [l,k]=size(Params); if k>0, if iscell(Params), Precond_Params(3:k+2)=Params; else, Precond_Params{3}=Params; end end TP=findfield(options,fopts,'ty',TP); n=SetPrecond(n,TP); if n<2, return, end %------- max, min dimension search subspace ------ jmin=min(n,findfield(options,fopts,'jmi',jmin)); jmax=min(n,findfield(options,fopts,'jma',jmax)); if jmax < 0 if jmin<0, jmin=min(n,nselect+p0); end jmax=min(n,jmin+p1); else if jmin<0, jmin=max(1,jmax-p1); end end maxit=findfield(options,fopts,'ma',maxit); %------- initial search subspace ---------------- V=findfield(options,fopts,'v',[]); [m,d]=size(V); if m~=n if m>n, V = V(1:n,:); end if m<n, V = [V;0.001*rand(n-m-1,d)]; end end V=orth(V); [m,d]=size(V); if d==0, nr=0; while nr==0, V=eval(V0); nr=norm(V); V=V/nr; end, end %------- Check definition B, Compute AV, BV ----- [AV,BV,n]=CheckDimMV(V); if n<2, return, end %------- Other options -------------------------- tol=findfield(options,fopts,'to',tol); kappa = findfield(options,fopts,'sca',kappa); kappa = abs(kappa(1,1)); if kappa==0, kappa=1; end PAIRS = findfield(options,fopts,'pai',PAIRS,[0,1]); SCHUR = findfield(options,fopts,'sch',SCHUR,[0,1,0.5]); DISP = findfield(options,fopts,'di',DISP,[0,1]); JDV = findfield(options,fopts,'av',JDV,[0,1]); track = max(abs(findfield(options,fopts,'tr',track,[0,track,inf])),0); NSIGMA = findfield(options,fopts,'ns',NSIGMA,[0,1]); FIX = max(abs(findfield(options,fopts,'fix',0,[0,FIX,inf])),0); CHORDALDISTANCE = findfield(options,fopts,'ch',CHORD,[0,1]); [TS0,ok] = findfield(options,fopts,'te',TS); if ok & ischar(TS0) if strncmpi(TS0,'st',2), TS=0; %% 'standard' elseif strncmpi(TS0,'ha',2), TS=1; %% 'harmonic' elseif strncmpi(TS0,'se',2), TS=2; %% 'searchspace' elseif strncmpi(TS0,'bv',2), TS=3; elseif strncmpi(TS0,'av',2), TS=4; end else TS=max(0,min(4,round(TS0(1,1)))); end %------- set targets ---------------- if isempty(Sigma) if TS==1, Sigma=[0,1]; else, Sigma = 'LM'; end elseif ischar(Sigma) switch Sigma case {'LM','LR','SR','BE','SM'} if ~ok, TS=3; end end else [k,l]=size(Sigma); if l==1, Sigma=[Sigma,ones(k,1)]; l=2; end Sigma=ScaleEig(Sigma); end if ischar(Sigma) & TS<2 msg1=sprintf(' The choice sigma = ''%s'' does not match the\n',Sigma); msg2=sprintf(' selected test subspace. Specify a numerical\n'); msg3=sprintf(' value for sigma (e.g. sigma = '); msg4=''; switch Sigma case {'LM','LR'} msg4=sprintf('[1,0]'); case {'SM','SR','BE'} msg4=sprintf(' [0,1]'); end msg5=sprintf('),\n or continue with ''TestSpace''=''B*V''.'); msg=[msg1,msg2,msg3,msg4,msg5]; button=questdlg(msg,'Targets and test subspaces','Continue','Stop','Continue'); if strcmp(button,'Continue'), TS=3; else, n=-1; return, end end %------- linear solver -------------------------- lsolver = findfield(options,fopts,'lso',lsolver); method=strvcat('exact','olsen','iluexact','gmres','cgstab','bicgstab'); j=strmatch(lower(lsolver),method); if isempty(j), msg=['The linear solver ''',lsolver,''' is not included.']; msg=[msg,sprintf('\nIs GMRES ok?')]; button=questdlg(msg,'Linear solver','Yes','No','Yes'); if strcmp(button,'Yes'), j=4; ls_maxit=5; else, n=-1; return, end end if j==1, lsolver='exact'; Precond_Form = 0; elseif j==2 | j==3, lsolver='olsen'; elseif j==4, lsolver='gmres'; ls_maxit=5; else, lsolver='cgstab'; ls_tol=1.0e-10; end ls_maxit= findfield(options,fopts,'ls_m',ls_maxit); ls_tol = findfield(options,fopts,'ls_t',ls_tol); ell = findfield(options,fopts,'ls_e',ell); par=[ls_tol,ls_maxit,ell]; %----- Display the parameters that are used ---------------- if DISP fprintf('\n'),fprintf('PROBLEM\n') switch Operator_Form case {1,4,6,7} fprintf('%13s: %s\n','A',StrOp(Operator_A)); fprintf('%13s: %s\n','B',StrOp(Operator_B)); case 2 fprintf('%13s: ''%s'' ([Av,Bv] = %s(v))\n','A,B',Operator_A,Operator_A); case 3 fprintf('%13s: ''%s''\n','A,B',Operator_A); fprintf('%15s(Av = %s(v,''A''), Bv = %s(v,''B''))\n',... '',Operator_A,Operator_A); case {5,8} fprintf('%13s: %s\n','A',StrOp(Operator_A)); fprintf('%13s: %s\n','B','Identity (B*v = v)'); end fprintf('%13s: %i\n','dimension',n); fprintf('%13s: %i\n\n','nselect',nselect); if length(jj)>0 & (ischar(Operator_A) | ischar(Operator_B)) msgj=sprintf(', %i',jj); msgo=''; if ischar(Operator_A), msgo=sprintf(' ''%s''',Operator_A); end if ischar(Operator_B), msgo=sprintf('%s ''%s''.',msgo,Operator_B); end fprintf(' The JDQZ input arguments, number%s, are\n',msgj) fprintf(' taken as input parameters 3:%i for%s.\n\n',length(jj)+2,msgo); end fprintf('TARGET\n') if ischar(Sigma) fprintf('%13s: ''%s''\n','sigma',Sigma) else fprintf('%13s: %s\n','sigma',mydisp(Sigma(1,:))) for j=2:size(Sigma,1), fprintf('%13s: %s\n','',mydisp(Sigma(j,:))) end end fprintf('\nOPTIONS\n') fprintf('%13s: %g\n','Schur',SCHUR) fprintf('%13s: %g\n','Tol',tol) fprintf('%13s: %i\n','Disp',DISP) fprintf('%13s: %i\n','jmin',jmin) fprintf('%13s: %i\n','jmax',jmax) fprintf('%13s: %i\n','MaxIt',maxit) fprintf('%13s: %s\n','v0',StrOp(V)) fprintf('%13s: %i\n','Pairs',PAIRS) fprintf('%13s: %i\n','AvoidStag',JDV) fprintf('%13s: %i\n','NSigma',NSIGMA) fprintf('%13s: %g\n','Track',track) fprintf('%13s: %g\n','FixShift',FIX) fprintf('%13s: %i\n','Chord',CHORDALDISTANCE) fprintf('%13s: ''%s''\n','LSolver',lsolver) str=sprintf('%g ',ls_tol); fprintf('%13s: [ %s]\n','LS_Tol',str) fprintf('%13s: %i\n','LS_MaxIt',ls_maxit) if strcmp(lsolver,'cgstab') fprintf('%13s: %i\n','LS_ell',ell) end DisplayPreconditioner(n); fprintf('\n') switch TS case 0, str='Standard, W = alpha''*A*V + beta''*B*V'; case 1, str='Harmonic, W = beta*A*V - alpha*B*V'; case 2, str='SearchSpace, W = V'; case 3, str='Petrov, W = B*V'; case 4, str='Petrov, W = A*V'; end fprintf('%13s: %s\n','TestSpace',str); fprintf('\n\n'); end return %------------------------------------------------------------------------ function msg=StrOp(Op) if ischar(Op) msg=sprintf('''%s''',Op); elseif issparse(Op), [n,k]=size(Op); msg=sprintf('[%ix%i sparse]',n,k); else, [n,k]=size(Op); msg=sprintf('[%ix%i double]',n,k); end return %------------------------------------------------------------------------ function DisplayPreconditioner(n) global Precond_Form Precond_Type ... Precond_L Precond_U Precond_P FP=Precond_Form; switch Precond_Form case 0, fprintf('%13s: %s\n','Precond','No preconditioner'); case {1,2,5} fprintf('%13s: %s','Precond',StrOp(Precond_L)); if FP==2, fprintf(' (M\\v = %s(v,''preconditioner''))',Precond_L); end fprintf('\n') case {3,4,6,7} fprintf('%13s: %s\n','L precond',StrOp(Precond_L)); fprintf('%13s: %s\n','U precond',StrOp(Precond_U)); if FP==7, fprintf('%13s: %s\n','P precond',StrOp(Precond_P)); end if FP==4,fprintf('%15s(M\\v = %s(%s(v,''L''),''U''))\n',... '',Precond_L,Precond_L); end end if FP switch Precond_Type case 0, str='explicit left'; case 1, str='explicit right'; case 2, str='implicit'; end fprintf('%15sTo be used as %s preconditioner.\n','',str) end return %------------------------------------------------------------------------ function possibilities fprintf('\n') fprintf('PROBLEM\n') fprintf(' A: [ square matrix | string ]\n'); fprintf(' B: [ square matrix {identity} | string ]\n'); fprintf(' nselect: [ positive integer {5} ]\n\n'); fprintf('TARGET\n') fprintf(' sigma: [ vector of scalars | \n'); fprintf(' pair of vectors of scalars |\n'); fprintf(' {''LM''} | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n'); fprintf('OPTIONS\n'); fprintf(' Schur: [ yes | {no} ]\n'); fprintf(' Tol: [ positive scalar {1e-8} ]\n'); fprintf(' Disp: [ yes | {no} ]\n'); fprintf(' jmin: [ positive integer {nselect+5} ]\n'); fprintf(' jmax: [ positive integer {jmin+5} ]\n'); fprintf(' MaxIt: [ positive integer {200} ]\n'); fprintf(' v0: '); fprintf('[ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n'); fprintf(' TestSpace: '); fprintf('[ Standard | {Harmonic} | SearchSpace | BV | AV ]\n'); fprintf(' Pairs: [ yes | {no} ] \n'); fprintf(' AvoidStag: [ yes | {no} ]\n'); fprintf(' Track: [ {yes} | no non-negative scalar {1e-4} ]\n'); fprintf(' NSigma: [ yes | {no} ]\n'); fprintf(' FixShift: [ yes | {no} | non-negative scalar {1e+3} ]\n'); fprintf(' Chord: [ {yes} | no ]\n'); fprintf(' Scale: [ positive scalar {1} ]\n'); fprintf(' LSolver: [ {gmres} | bicgstab ]\n'); fprintf(' LS_Tol: [ row of positive scalar {[0.7,0.49]} ]\n'); fprintf(' LS_MaxIt: [ positive integer {5} ]\n'); fprintf(' LS_ell: [ positive integer {4} ]\n'); fprintf(' Precond: '); fprintf('[ n by n matrix {identity} | n by 2n matrix | string ]\n'); fprintf(' L_Precond: same as ''Precond''\n'); fprintf(' U_Precond: [ n by n matrix {identity} | string ]\n'); fprintf(' P_Precond: [ n by n matrix {identity} ]\n'); fprintf(' Type_Precond: [ {left} | right | implicit ]\n'); fprintf('\n') return %------------------------------------------------------------------------ function x = boolean(x,gamma,string) %Y = BOOLEAN(X,GAMMA,STRING) % GAMMA(1) is the default. % If GAMMA is not specified, GAMMA = 0. % STRING is a cell of accepted strings. % If STRING is not specified STRING = {'n' 'y'} % STRING{I} and GAMMA(I) are accepted expressions for X % If X=GAMMA(I) then Y=X. If the first L characters % of X matches those of STRING{I}, then Y=GAMMA(I+1). % Here L=SIZE({STRING{1},2). % For other values of X, Y=GAMMA(1); if nargin < 2, gamma=[0,0,1]; end if nargin < 3, string={'n' 'y'}; end if ischar(x) l=size(string{1},2); i=min(find(strncmpi(x,string,l))); if isempty(i), i=0; end, x=gamma(i+1); elseif max((gamma-x)==0) elseif gamma(end) == inf else, x=gamma(1); end return %------------------------------------------------------------------------ function [a,ok]=findfield(options,fopts,str,default,gamma,stri) % Searches the fieldnames in FOPTS for the string STR. % The field is detected if only the first part of the fieldname % matches the string STR. The search is case insensitive. % If the field is detected, then OK=1 and A is the fieldvalue. % Otherwise OK=0 and A=DEFAULT l=size(str,2); j=min(find(strncmpi(str,fopts,l))); if ~isempty(j) a=getfield(options,char(fopts(j,:))); ok=1; if nargin == 5, a = boolean(a,[default,gamma]); elseif nargin == 6, a = boolean(a,[default,gamma],stri); end elseif nargin>3 a=default; ok=0; else a=[]; ok=0; end return %%%====================================================================== function n=CheckMatrix(A,gamma) if ischar(A), n=-1; if exist(A) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',A); errordlg(msg,'MATRIX'),n=-2; end if n==-1 & gamma, eval('n=feval(A,[],''dimension'');','n=-1;'), end else, [n,n] = size(A); if any(size(A) ~= n) msg=sprintf(' The operator must be a square matrix or a string. '); errordlg(msg,'MATRIX'),n=-3; end end return %------------------------------------------------------------------------ function [Av,Bv,n]=CheckDimMV(v) % [Av,Bv]=CheckDimMV(v) % Av=A*v, Bv=B*v Checks correctness operator definitions global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params [n,k]=size(v); if k>1, V=v(:,2:k); v=v(:,1); end Bv=v; switch Operator_Form case 1 % both Operator_A and B are strings Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=feval(Operator_B,Operator_Params{:}); case 2 %%% or Operator_Form=3 or Operator_Form=5??? Operator_Params{1}=v; eval('[Av,Bv]=feval(Operator_A,Operator_Params{:});','Operator_Form=3;') if Operator_Form==3, ok=1; Operator_Params{2}='A'; eval('Av=feval(Operator_A,Operator_Params{:});','ok=0;') if ok, Operator_Params{2}='B'; eval('Bv=feval(Operator_A,Operator_Params{:});','ok=0;'), end if ~ok, Operator_Form=5; Operator_Params{2}=''; Av=feval(Operator_A,Operator_Params{:}); end end case 3 Operator_Params{1}=v; Operator_Params{2}='A'; Av=feval(Operator_A,Operator_Params{:}); Operator_Params{2}='B'; Bv=feval(Operator_A,Operator_Params{:}); case 4 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=Operator_B*v; case 5 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); case 6 Av=Operator_A*v; Operator_Params{1}=v; Bv=feval(Operator_B,Operator_Params{:}); case 7 Av=Operator_A*v; Bv=Operator_B*v; case 8 Av=Operator_A*v; end Operator_MVs = 1; ok_A=min(size(Av)==size(v)); ok_B=min(size(Bv)==size(v)); if ok_A & ok_B if k>1, ok=1; eval('[AV,BV]=MV(V);','ok=0;') if ok Av=[Av,AV]; Bv=[Bv,BV]; else for j=2:k, [Av(:,j),Bv(:,j)]=MV(V(:,j-1)); end end end return end if ~ok_A Operator=Operator_A; elseif ~ok_B Operator=Operator_B; end msg=sprintf(' %s does not produce a vector of size %d',Operator,n) errordlg(msg,'MATRIX'), n=-1; return %------------------------------------------------------------------------ function n=SetPrecond(n,TP) % finds out how the preconditioners are defined (Precond_Form) % and checks consistency of the definitions. % % If M is the preconditioner then P*M=L*U. Defaults: L=U=P=I. % % Precond_Form % 0: no L % 1: L M-file, no U, L ~= A % 2: L M-file, no U, L == A % 3: L M-file, U M-file, L ~= A, U ~= A, L ~=U % 4: L M-file, U M-file, L == U % 5: L matrix, no U % 6: L matrix, U matrix no P % 7: L matrix, U matrix, P matrix % % Precond_Type % 0: Explicit left % 1: Explicit right % 2: Implicit % global Operator_A ... Precond_Form Precond_Solves ... Precond_Type ... Precond_L Precond_U Precond_P Precond_Params Precond_Type = 0; if ischar(TP) TP=lower(TP(1,1)); switch TP case 'l' Precond_Type = 0; case 'r' Precond_Type = 1; case 'i' Precond_Type = 2; end else Precond_Type=max(0,min(fix(TP),2)); end Precond_Solves = 0; % Set type preconditioner Precond_Form=0; if isempty(Precond_L), return, end if ~isempty(Precond_U) & ischar(Precond_L)~=ischar(Precond_U) msg=sprintf(' L and U should both be strings or matrices'); errordlg(msg,'PRECONDITIONER'), n=-1; return end if ~isempty(Precond_P) & (ischar(Precond_P) | ischar(Precond_L)) msg=sprintf(' P can be specified only if P, L and U are matrices'); errordlg(msg,'PRECONDITIONER'), n=-1; return end tp=1+4*~ischar(Precond_L)+2*~isempty(Precond_U)+~isempty(Precond_P); if tp==1, tp = tp + strcmp(Precond_L,Operator_A); end if tp==3, tp = tp + strcmp(Precond_L,Precond_U); end if tp==3 & strcmp(Precond_U,Operator_A) msg=sprintf(' If L and A use the same M-file,') msg=[msg,sprintf('\n then so should U.')]; errordlg(msg,'PRECONDITIONER'), n=-1; return end if tp>5, tp=tp-1; end, Precond_Form=tp; % Check consistency definitions if tp<5 & exist(Precond_L) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_L); errordlg(msg,'PRECONDITIONER'), n=-1; return end ok=1; if tp == 2 Precond_Params{1}=zeros(n,1); Precond_Params{2}='preconditioner'; eval('v=feval(Operator_A,Precond_Params{:});','ok=0;') if ~ok msg='Preconditioner and matrix use the same M-file'; msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)]; msg=[msg,'Therefore the preconditioner is called as']; msg=[msg,sprintf('\n\n\tw=%s(v,''preconditioner'')\n\n',Precond_L)]; msg=[msg,sprintf('Put this "switch" in ''%s.m''.',Precond_L)]; end end if tp == 4 | ~ok ok1=1; Precond_Params{1}=zeros(n,1); Precond_Params{2}='L'; eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;') Precond_Params{2}='U'; eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;') if ok1 Precond_Form = 4; Precond_U = Precond_L; ok=1; else if tp == 4 msg='L and U use the same M-file'; msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)]; msg=[msg,'Therefore L and U are called']; msg=[msg,sprintf(' as\n\n\tw=%s(v,''L'')',Precond_L)]; msg=[msg,sprintf(' \n\tw=%s(v,''U'')\n\n',Precond_L)]; msg=[msg,sprintf('Check the dimensions and/or\n')]; msg=[msg,sprintf('put this "switch" in ''%s.m''.',Precond_L)]; end errordlg(msg,'PRECONDITIONER'), n=-1; return end end if tp==1 | tp==3 Precond_Params{1}=zeros(n,1); Precond_Params{2}=''; eval('v=feval(Precond_L,Precond_Params{:});','ok=0') if ~ok msg=sprintf('''%s'' should produce %i-vectors',Precond_L,n); errordlg(msg,'PRECONDITIONER'), n=-1; return end end if tp==3 if exist(Precond_U) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_U); errordlg(msg,'PRECONDITIONER'), n=-1; return else Precond_Params{1}=zeros(n,1); Precond_Params{2}=''; eval('v=feval(Precond_U,Precond_Params{:});','ok=0') if ~ok msg=sprintf('''%s'' should produce %i-vectors',Precond_U,n); errordlg(msg,'PRECONDITIONER'), n=-1; return end end end if tp==5 if min([n,2*n]==size(Precond_L)) Precond_U=Precond_L(:,n+1:2*n); Precond_L=Precond_L(:,1:n); Precond_Form=6; elseif min([n,3*n]==size(Precond_L)) Precond_U=Precond_L(:,n+1:2*n); Precond_P=Precond_L(:,2*n+1:3*n); Precond_L=Precond_L(:,1:n); Precond_Form=7; elseif ~min([n,n]==size(Precond_L)) msg=sprintf('The preconditioning matrix\n'); msg2=sprintf('should be %iX%i or %ix%i ([L,U])\n',n,n,n,2*n); msg3=sprintf('or %ix%i ([L,U,P])\n',n,3*n); errordlg([msg,msg2,msg3],'PRECONDITIONER'), n=-1; return end end if tp==6 & ~min([n,n]==size(Precond_L) & [n,n]==size(Precond_U)) msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1; errordlg(msg,'PRECONDITIONER'), n=-1; return end if tp==7 & ~min([n,n]==size(Precond_L) & ... [n,n]==size(Precond_U) & [n,n]==size(Precond_P)) msg=sprintf('L, U, and P should all be %iX%i.',n,n); n=-1; errordlg(msg,'PRECONDITIONER'), n=-1; return end return %%%====================================================================== %%%========= DISPLAY FUNCTIONS =========================================== %%%====================================================================== function Result(Sigm,Target,S,T,tol) if nargin == 1 fprintf('\n\n %20s\n','Eigenvalues') for j=1:size(Sigm,1), fprintf('%2i %s\n',j,mydisp(Sigm(j,:),5)) end return end fprintf('\n\n%17s %25s%18s\n','Targets','Eigenvalues','RelErr/Cond') for j=1:size(S,1), l=Target(j,1); s=S(j,:); t=T(j,:); lm=mydisp(s/t,5); if l>0 fprintf('%2i %8s ''%s'' %9s %23s',j,'',Sigm(l,:),'',lm) else fprintf('%2i %23s %23s',j,mydisp(Target(j,2:3),5),lm) end re=1-tol/abs(t); if re>0, re=(1+tol/abs(s))/re; re=min(re-1,1); else, re=1; end if re>0.999, fprintf(' 1\n'), else, fprintf(' %5.0e\n',re), end end return %------------------------------------------------------------------------ function s=mydisp(lambda,d) if nargin <2, d=4; end if size(lambda,2)==2, if lambda(:,2)==0, s='Inf'; return, end lambda=lambda(:,1)/lambda(:,2); end a=real(lambda); b=imag(lambda); if max(a,b)==inf, s='Inf'; return, end e=0; if abs(a)>0; e= floor(log10(abs(a))); end if abs(b)>0; e= max(e,floor(log10(abs(b)))); end p=10^d; q=p/(10^e); a=round(a*q)/p; b=round(b*q)/p; st=['%',num2str(d+2),'.',num2str(d),'f']; ab=abs(b)==0; if ab, str=[''' ']; else, str=['''(']; end if a>=0, str=[str,'+']; a=abs(a); end, str=[str,st]; if ab, str=[str,'e']; else if b>=0, str=[str,'+']; b=abs(b); end, str=[str,st,'i)e']; end if e>=0, str=[str,'+']; else, str=[str,'-']; e=-e; end if e<10, str=[str,'0%i''']; else, str=[str,'%i''']; end if ab, s=eval(sprintf(str,a,e)); else, s=eval(sprintf(str,a,b,e)); end return %%%====================================================================== function ShowEig(theta,target,k) if ischar(target) fprintf('\n target=''%s'', ',target) else fprintf('\n target=%s, ',mydisp(target,5)) end fprintf('lambda_%i=%s\n',k,mydisp(theta,5)); return %%%====================================================================== function texttest(s,nr,gamma) if nargin<3, gamma=100*eps; end if nr > gamma % if nr>100*eps fprintf('\n %35s is: %9.3g\t',s,nr) end return %%%======================================================================
github
eulertech/DeepLearningCrudeOilForecast-master
lnst.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/lnst.m
891
utf_8
93ca6136f90181897631256d58517558
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function lnst(hs,he) ls=get(he,'value'); switch ls case 1 set(hs,'LineStyle','-','marker','x','color','b'); case 2 set(hs,'LineStyle','-','marker','o','color','r'); case 3 set(hs,'LineStyle','none','marker','o','color','b'); case 4 set(hs,'LineStyle','-','marker','none','color','g'); case 5 set(hs,'LineStyle','--','marker','d','color','b'); end drawnow;
github
eulertech/DeepLearningCrudeOilForecast-master
scatter12n.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/scatter12n.m
1,348
utf_8
65c091a54cbbe59f0a7ddef27fcc2c3f
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function scatter12n(name,data,labels) ld=length(data(1,:)); if ld==2 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb scatter(data(:,1),data(:,2),5,labels); % else % scatter(data(:,1),data(:,2),5); % end title(name); else if ld==1 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb scatter(data(:,1),zeros(length(data(:,1)),1),5,labels); % else % scatter(data(:,1),zeros(length(data(:,1)),1),5); % end title(name); else %if handles.islb scattern(name,data,labels); % else % scattern('Result of dimensionality reduction',data); % end end end
github
eulertech/DeepLearningCrudeOilForecast-master
not_calculated.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/not_calculated.m
7,818
utf_8
07c7ebdd2ecb821df6d1b4ccd5f47662
function varargout = not_calculated(varargin) % NOT_CALCULATED M-file for not_calculated.fig % NOT_CALCULATED by itself, creates a new NOT_CALCULATED or raises the % existing singleton*. % % H = NOT_CALCULATED returns the handle to a new NOT_CALCULATED or the handle to % the existing singleton*. % % NOT_CALCULATED('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NOT_CALCULATED.M with the given input arguments. % % NOT_CALCULATED('Property','Value',...) creates a new NOT_CALCULATED or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before not_calculated_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to not_calculated_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help not_calculated % Last Modified by GUIDE v2.5 30-Jul-2008 11:02:27 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @not_calculated_OpeningFcn, ... 'gui_OutputFcn', @not_calculated_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before not_calculated is made visible. function not_calculated_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to not_calculated (see VARARGIN) % Choose default command line output for not_calculated handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes not_calculated wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = not_calculated_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
eulertech/DeepLearningCrudeOilForecast-master
choose_method.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/choose_method.m
5,483
utf_8
7fcb2ff0eb7f662fc75d652d9c440d65
function varargout = choose_method(varargin) % CHOOSE_METHOD M-file for choose_method.fig % CHOOSE_METHOD, by itself, creates a new CHOOSE_METHOD or raises the existing % singleton*. % % H = CHOOSE_METHOD returns the handle to a new CHOOSE_METHOD or the handle to % the existing singleton*. % % CHOOSE_METHOD('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CHOOSE_METHOD.M with the given input arguments. % % CHOOSE_METHOD('Property','Value',...) creates a new CHOOSE_METHOD or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before choose_method_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to choose_method_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help choose_method % Last Modified by GUIDE v2.5 25-Jul-2008 10:40:42 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @choose_method_OpeningFcn, ... 'gui_OutputFcn', @choose_method_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before choose_method is made visible. function choose_method_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to choose_method (see VARARGIN) % Choose default command line output for choose_method handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes choose_method wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = choose_method_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) vl=get(hObject,'Value'); switch vl case 1 str='CorrDim'; case 2 str='NearNbDim'; case 3 str='GMST'; case 4 str='PackingNumbers'; case 5 str='EigValue'; case 6 str='MLE'; end set(handles.str,'string',str); drawnow; % --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_Callback(hObject, eventdata, handles) % hObject handle to str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str as text % str2double(get(hObject,'String')) returns contents of str as a double % --- Executes during object creation, after setting all properties. function str_CreateFcn(hObject, eventdata, handles) % hObject handle to str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1);
github
eulertech/DeepLearningCrudeOilForecast-master
load_data_1_var.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/load_data_1_var.m
4,902
utf_8
5b70e8dd70f9e4386ea769372ed55ffe
function varargout = load_data_1_var(varargin) % LOAD_DATA_1_VAR M-file for load_data_1_var.fig % LOAD_DATA_1_VAR, by itself, creates a new LOAD_DATA_1_VAR or raises the existing % singleton*. % % H = LOAD_DATA_1_VAR returns the handle to a new LOAD_DATA_1_VAR or the handle to % the existing singleton*. % % LOAD_DATA_1_VAR('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA_1_VAR.M with the given input arguments. % % LOAD_DATA_1_VAR('Property','Value',...) creates a new LOAD_DATA_1_VAR or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_1_var_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_1_var_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data_1_var % Last Modified by GUIDE v2.5 23-Jul-2008 17:31:19 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_1_var_OpeningFcn, ... 'gui_OutputFcn', @load_data_1_var_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data_1_var is made visible. function load_data_1_var_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data_1_var (see VARARGIN) % Choose default command line output for load_data_1_var handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes load_data_1_var wait for user response (see UIRESUME) uiwait(handles.figure1); % uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_1_var_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function cn_Callback(hObject, eventdata, handles) % hObject handle to cn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of cn as text % str2double(get(hObject,'String')) returns contents of cn as a double % --- Executes during object creation, after setting all properties. function cn_CreateFcn(hObject, eventdata, handles) % hObject handle to cn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.i,'value') set(handles.cn,'Enable','on'); set(handles.cnt,'ForegroundColor',[0 0 0]); else set(handles.cn,'Enable','off'); set(handles.cnt,'ForegroundColor',[0.4 0.4 0.4]); end
github
eulertech/DeepLearningCrudeOilForecast-master
plotn.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/plotn.m
4,103
utf_8
e9c0840dca614923d10952e9b37f06c5
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function plotn(name,data) % plot if dimensionality>=3 % format: plotn(name,data) % name - text that will be dispayed as name of figure % data - multidimentional data, row - is one datapoint bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961]; bgc1=[1 1 1]; bgc1=bgc; % if length(varargin)==1 % labels=varargin{1}; % islb=true; % else islb=false; % end hf=figure; set(hf,'name',name,'NumberTitle','off'); set(hf,'units','normalized'); set(hf,'position',[0.1 0.1 0.7 0.75]); set(hf,'color',bgc); ha=axes; set(ha,'units','normalized'); set(ha,'position',[0.1 0.1 0.8 0.7]); % if islb % hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha); % else hs=plot3(data(:,1),data(:,2),data(:,3),'x-','parent',ha); % end set(hs,'UserData',data); % memorize data in userdata of plot % title as text contol: xc=0.5; yc=0.94; dx=0.8; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', name,... 'units','normalized',... 'fontunits','normalized',... 'HorizontalAlignment','center',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % dimensionality text xc=0.5; yc=0.9; dx=0.2; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', ['dimensionality=' num2str(length(data(1,:)))],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % edits: xc=0.5; yc=0.86; dy=0.04; dytx=0.03; x0=0.03; dxg=0.03; xt=x0; for cc=1:3 switch cc case 1 ls='X'; case 2 ls='Y'; case 3 ls='Z'; end dx1=0.07; uicontrol('Style', 'text',... 'parent',hf,... 'String', [ls ' ' 'data:'],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'edit',... 'parent',hf,... 'String', num2str(cc),... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xt=xt+dx1+0.005; dx1=0.065; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'column',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; xt=xt+dxg; end dx1=0.1; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'line style:',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'popupmenu',... 'parent',hf,... 'String', '1|2|3|4|5',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['lnst(' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xlabel(ha,'X'); ylabel(ha,'Y'); zlabel(ha,'Z'); set(hf,'Toolbar','figure');
github
eulertech/DeepLearningCrudeOilForecast-master
scattern.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/scattern.m
3,651
utf_8
bf506a19215a7e0b4cb62da12fa09d16
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function scattern(name,data,varargin) % scatter plot if dimensionality>=3 % format: scattern(name,data) % name - text that will be dispayed as name of figure % data - multidimentional data, row - is one datapoint % scattern(name,data,labels) - if labels spacified, used for color of points bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961]; bgc1=[1 1 1]; bgc1=bgc; if length(varargin)==1 labels=varargin{1}; islb=true; else islb=false; end hf=figure; set(hf,'name',name,'NumberTitle','off'); set(hf,'units','normalized'); set(hf,'position',[0.1 0.1 0.7 0.75]); set(hf,'color',bgc); ha=axes; set(ha,'units','normalized'); set(ha,'position',[0.1 0.1 0.8 0.7]); if islb && size(data, 1) == numel(labels) hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha); else hs=scatter3(data(:,1),data(:,2),data(:,3),5,'parent',ha); end if size(data, 1) ~= numel(labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end set(hs,'UserData',data); % memorize data in userdata of plot % title as text contol: xc=0.5; yc=0.94; dx=0.8; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', name,... 'units','normalized',... 'fontunits','normalized',... 'HorizontalAlignment','center',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % dimensionality text xc=0.5; yc=0.9; dx=0.2; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', ['dimensionality=' num2str(length(data(1,:)))],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % edits: xc=0.5; yc=0.86; dy=0.04; dytx=0.03; x0=0.12; dxg=0.05; xt=x0; for cc=1:3 switch cc case 1 ls='X'; case 2 ls='Y'; case 3 ls='Z'; end dx1=0.07; uicontrol('Style', 'text',... 'parent',hf,... 'String', [ls ' ' 'data:'],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'edit',... 'parent',hf,... 'String', num2str(cc),... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xt=xt+dx1+0.005; dx1=0.065; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'column',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; xt=xt+dxg; end xlabel(ha,'X'); ylabel(ha,'Y'); zlabel(ha,'Z'); set(hf,'Toolbar','figure');
github
eulertech/DeepLearningCrudeOilForecast-master
no_history.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/no_history.m
7,508
utf_8
d5c85b897eeca97b3e37ea41551de2b1
function varargout = no_history(varargin) % NO_HISTORY M-file for no_history.fig % NO_HISTORY by itself, creates a new NO_HISTORY or raises the % existing singleton*. % % H = NO_HISTORY returns the handle to a new NO_HISTORY or the handle to % the existing singleton*. % % NO_HISTORY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NO_HISTORY.M with the given input arguments. % % NO_HISTORY('Property','Value',...) creates a new NO_HISTORY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before no_history_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to no_history_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help no_history % Last Modified by GUIDE v2.5 16-Sep-2008 15:57:20 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @no_history_OpeningFcn, ... 'gui_OutputFcn', @no_history_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before no_history is made visible. function no_history_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to no_history (see VARARGIN) % Choose default command line output for no_history handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes no_history wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = no_history_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
eulertech/DeepLearningCrudeOilForecast-master
load_data_vars.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/load_data_vars.m
7,943
utf_8
3e892de48b2b883da0e7121eb6b7cfbc
function varargout = load_data_vars(varargin) % LOAD_DATA_VARS M-file for load_data_vars.fig % LOAD_DATA_VARS, by itself, creates a new LOAD_DATA_VARS or raises the existing % singleton*. % % H = LOAD_DATA_VARS returns the handle to a new LOAD_DATA_VARS or the handle to % the existing singleton*. % % LOAD_DATA_VARS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA_VARS.M with the given input arguments. % % LOAD_DATA_VARS('Property','Value',...) creates a new LOAD_DATA_VARS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_vars_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_vars_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data_vars % Last Modified by GUIDE v2.5 23-Jul-2008 18:19:22 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_vars_OpeningFcn, ... 'gui_OutputFcn', @load_data_vars_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data_vars is made visible. function load_data_vars_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data_vars (see VARARGIN) % Choose default command line output for load_data_vars handles.output = hObject; % Update handles structure guidata(hObject, handles); vn=varargin{1}; % variable names str=''; for vnc=1:length(vn) str=[str vn{vnc}]; if vnc~=length(vn) str=[str ' ']; end end set(handles.lv,'string',str); set(handles.d,'string',vn{1}); set(handles.ivn,'string',vn{2}); % UIWAIT makes load_data_vars wait for user response (see UIRESUME) uiwait(handles.figure1); %uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_vars_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function lv_Callback(hObject, eventdata, handles) % hObject handle to lv (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of lv as text % str2double(get(hObject,'String')) returns contents of lv as a double % --- Executes during object creation, after setting all properties. function lv_CreateFcn(hObject, eventdata, handles) % hObject handle to lv (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function d_Callback(hObject, eventdata, handles) % hObject handle to d (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of d as text % str2double(get(hObject,'String')) returns contents of d as a double % --- Executes during object creation, after setting all properties. function d_CreateFcn(hObject, eventdata, handles) % hObject handle to d (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ivn_Callback(hObject, eventdata, handles) % hObject handle to ivn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ivn as text % str2double(get(hObject,'String')) returns contents of ivn as a double % --- Executes during object creation, after setting all properties. function ivn_CreateFcn(hObject, eventdata, handles) % hObject handle to ivn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function icn_Callback(hObject, eventdata, handles) % hObject handle to icn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of icn as text % str2double(get(hObject,'String')) returns contents of icn as a double % --- Executes during object creation, after setting all properties. function icn_CreateFcn(hObject, eventdata, handles) % hObject handle to icn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.iv,'value') set(handles.ivn,'Enable','on'); else set(handles.ivn,'Enable','off'); end if get(handles.ic,'value') set(handles.icn,'Enable','on'); else set(handles.icn,'Enable','off'); end
github
eulertech/DeepLearningCrudeOilForecast-master
mapping_parameters.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/mapping_parameters.m
24,066
utf_8
ddb259e8821b5440a07fc05910595864
function varargout = mapping_parameters(varargin) % MAPPING_PARAMETERS M-file for mapping_parameters.fig % MAPPING_PARAMETERS, by itself, creates a new MAPPING_PARAMETERS or raises the existing % singleton*. % % H = MAPPING_PARAMETERS returns the handle to a new MAPPING_PARAMETERS or the handle to % the existing singleton*. % % MAPPING_PARAMETERS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MAPPING_PARAMETERS.M with the given input arguments. % % MAPPING_PARAMETERS('Property','Value',...) creates a new MAPPING_PARAMETERS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before mapping_parameters_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to mapping_parameters_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Last Modified by GUIDE v2.5 28-Jul-2008 16:23:20 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @mapping_parameters_OpeningFcn, ... 'gui_OutputFcn', @mapping_parameters_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before mapping_parameters is made visible. function mapping_parameters_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to mapping_parameters (see VARARGIN) % Choose default command line output for mapping_parameters handles.output = hObject; no_dims=varargin{1}; handles.islb=varargin{2}; if length(no_dims)~=0 set(handles.nd,'string',num2str(round(no_dims))); else set(handles.nd,'string','2'); end case1; % case one is default for start % Update handles structure guidata(hObject, handles); % handles % UIWAIT makes mapping_parameters wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = mapping_parameters_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) % figure1: 218.0023 % sm: 240.0021 % na: 239.0021 % nat: 238.0021 % uipanel_tp: 235.0021 % prp: 234.0021 % prpt: 233.0021 % kpd: 232.0021 % kpdt: 231.0021 % kpR: 230.0021 % kpRt: 229.0021 % kgs: 228.0021 % kgst: 227.0021 % uipanel_k: 223.0022 % uipanel_ft: 220.0022 % sig: 53.0027 % sigt: 52.0027 % uipanel_ei: 49.0027 % prc: 48.0027 % prct: 47.0027 % k: 46.0028 % kt: 45.0028 % mi: 44.0028 % mit: 43.0029 % nd: 42.0029 % text3: 41.0034 % wl: 40.0029 % text1: 39.0033 % listbox1: 219.0023 % tl: 237.0021 % tg: 236.0021 % kp: 226.0022 % kg: 225.0022 % kl: 224.0022 % ftn: 222.0022 % fty: 221.0022 % eij: 51.0027 % eim: 50.0027 % output: 218.0023 % islb: % PCA % LDA % MDS % SimplePCA % ProbPCA % FactorAnalysis % Isomap % LandmarkIsomap % LLE % Laplacian % HessianLLE % LTSA % MVU % CCA % LandmarkMVU % FastMVU % DiffusionMaps % KernelPCA % GDA % SNE % SymSNE % t-SNE % LPP % NPE % LLTSA % SPE % Autoencoder % LLC % ManifoldChart % CFA % GPLVM switch get(hObject,'Value') case 1 % PCA % no parameters; case1; case 2 % LDA % no parameters; case1; if handles.islb set(handles.wl,'visible','off'); set(handles.sm,'Enable','on'); else set(handles.wl,'visible','on'); set(handles.sm,'Enable','off'); end case 3 % MDS % no parameters; case1; case 4 % SimplePCA % no parameters; case1; case 5 % ProbPCA case1; % hide all contols first set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); case 6 % FactorAnalysis % no parameters; case1; case 7 % Isomap case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; case 8 % LandmarkIsomap case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.prc,'Visible','on'); set(handles.prct,'Visible','on'); case 9 % LLE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 10 % Laplacian case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 11 % HessianLLE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 12 % LTSA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 13 % MVU case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 14 % CCA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 15 % LandmarkMVU case1; % hide all contols first set(handles.k,'Visible','on','string',5); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; case 16 % FastMVU case1; % hide all contols first set(handles.k,'Visible','on','string',5); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); set(handles.uipanel_ft,'Visible','on'); case 17 % DiffusionMaps case1; % hide all contols first set(handles.t,'Visible','on'); set(handles.tt,'Visible','on'); set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); case 18 % KernelPCA case1; % hide all contols first set(handles.uipanel_k,'Visible','on'); update_kernel_uipanel; case 19 % GDA case1; % hide all contols first if handles.islb set(handles.wl,'visible','off'); set(handles.sm,'Enable','on'); set(handles.uipanel_k,'Visible','on'); update_kernel_uipanel; else set(handles.wl,'visible','on'); set(handles.sm,'Enable','off'); end case 20 % SNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 21 % SymSNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 22 % t-SNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 23 % LPP case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 24 % NPE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 25 % LLTSA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 26 % SPE case1; % hide all contols first set(handles.uipanel_tp,'Visible','on'); update_type_uipanel; set(handles.k,'Enable','on'); adaptive_callback; case 27 % Autoencoder % no parameters; case1; case 28 % LLC case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 29 % ManifoldChart case1; % hide all contols first set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 30 % CFA case1; % hide all contols first set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); case 31 % GPLVM case1; % hide all contols first set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); case 32 % NCA case1; case 33 % MCML case1; end % --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nd_Callback(hObject, eventdata, handles) % hObject handle to nd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of nd as text % str2double(get(hObject,'String')) returns contents of nd as a double % --- Executes during object creation, after setting all properties. function nd_CreateFcn(hObject, eventdata, handles) % hObject handle to nd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function mi_Callback(hObject, eventdata, handles) % hObject handle to mi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mi as text % str2double(get(hObject,'String')) returns contents of mi as a double % --- Executes during object creation, after setting all properties. function mi_CreateFcn(hObject, eventdata, handles) % hObject handle to mi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function k_Callback(hObject, eventdata, handles) % hObject handle to k (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of k as text % str2double(get(hObject,'String')) returns contents of k as a double % --- Executes during object creation, after setting all properties. function k_CreateFcn(hObject, eventdata, handles) % hObject handle to k (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function prc_Callback(hObject, eventdata, handles) % hObject handle to prc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of prc as text % str2double(get(hObject,'String')) returns contents of prc as a double % --- Executes during object creation, after setting all properties. function prc_CreateFcn(hObject, eventdata, handles) % hObject handle to prc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sig_Callback(hObject, eventdata, handles) % hObject handle to sig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sig as text % str2double(get(hObject,'String')) returns contents of sig as a double % --- Executes during object creation, after setting all properties. function sig_CreateFcn(hObject, eventdata, handles) % hObject handle to sig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kgs_Callback(hObject, eventdata, handles) % hObject handle to kgs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kgs as text % str2double(get(hObject,'String')) returns contents of kgs as a double % --- Executes during object creation, after setting all properties. function kgs_CreateFcn(hObject, eventdata, handles) % hObject handle to kgs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kpR_Callback(hObject, eventdata, handles) % hObject handle to kpR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kpR as text % str2double(get(hObject,'String')) returns contents of kpR as a double % --- Executes during object creation, after setting all properties. function kpR_CreateFcn(hObject, eventdata, handles) % hObject handle to kpR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kpd_Callback(hObject, eventdata, handles) % hObject handle to kpd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kpd as text % str2double(get(hObject,'String')) returns contents of kpd as a double % --- Executes during object creation, after setting all properties. function kpd_CreateFcn(hObject, eventdata, handles) % hObject handle to kpd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function prp_Callback(hObject, eventdata, handles) % hObject handle to prp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of prp as text % str2double(get(hObject,'String')) returns contents of prp as a double % --- Executes during object creation, after setting all properties. function prp_CreateFcn(hObject, eventdata, handles) % hObject handle to prp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function na_Callback(hObject, eventdata, handles) % hObject handle to na (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of na as text % str2double(get(hObject,'String')) returns contents of na as a double % --- Executes during object creation, after setting all properties. function na_CreateFcn(hObject, eventdata, handles) % hObject handle to na (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in sm. function sm_Callback(hObject, eventdata, handles) set(handles.sm,'Enable','off'); drawnow; uiresume(handles.figure1); function t_Callback(hObject, eventdata, handles) % hObject handle to t (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of t as text % str2double(get(hObject,'String')) returns contents of t as a double % --- Executes during object creation, after setting all properties. function t_CreateFcn(hObject, eventdata, handles) % hObject handle to t (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % -------------------------------------------------------------------- function uipanel_k_SelectionChangeFcn(hObject, eventdata, handles) update_kernel_uipanel; % -------------------------------------------------------------------- function uipanel_tp_SelectionChangeFcn(hObject, eventdata, handles) update_type_uipanel; % --- Executes on button press in ka. function ka_Callback(hObject, eventdata, handles) adaptive_callback;
github
eulertech/DeepLearningCrudeOilForecast-master
load_xls.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/load_xls.m
4,845
utf_8
98f040ec0685b024ddf99d454fea770d
function varargout = load_xls(varargin) % LOAD_XLS M-file for load_xls.fig % LOAD_XLS, by itself, creates a new LOAD_XLS or raises the existing % singleton*. % % H = LOAD_XLS returns the handle to a new LOAD_XLS or the handle to % the existing singleton*. % % LOAD_XLS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_XLS.M with the given input arguments. % % LOAD_XLS('Property','Value',...) creates a new LOAD_XLS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_xls_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_xls_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_xls % Last Modified by GUIDE v2.5 11-Sep-2008 10:53:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_xls_OpeningFcn, ... 'gui_OutputFcn', @load_xls_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_xls is made visible. function load_xls_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_xls (see VARARGIN) % Choose default command line output for load_xls handles.output = hObject; nmc=varargin{1}; % number of columns % Update handles structure guidata(hObject, handles); set(handles.noc,'string',num2str(nmc)); set(handles.col,'string',num2str(nmc)); cl=[0.4 0.4 0.4]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','off'); % UIWAIT makes load_xls wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = load_xls_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function col_Callback(hObject, eventdata, handles) % hObject handle to col (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of col as text % str2double(get(hObject,'String')) returns contents of col as a double % --- Executes during object creation, after setting all properties. function col_CreateFcn(hObject, eventdata, handles) % hObject handle to col (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % --- Executes when selected object is changed in uipanel1. function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.uc,'value') cl=[0 0 0]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','on'); else cl=[0.4 0.4 0.4]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','off'); end
github
eulertech/DeepLearningCrudeOilForecast-master
drtool.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/drtool.m
53,877
utf_8
25abf1c6522b90b00b1c29d7d4f4c091
function varargout = drtool(varargin) % DRTOOL M-file for drtool.fig % DRTOOL, by itself, creates a new DRTOOL or raises the existing % singleton*. % % H = DRTOOL returns the handle to a new DRTOOL or the handle to % the existing singleton*. % % DRTOOL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DRTOOL.M with the given input arguments. % % DRTOOL('Property','Value',...) creates a new DRTOOL or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before drtool_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to drtool_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help drtool % Last Modified by GUIDE v2.5 16-Sep-2008 12:18:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @drtool_OpeningFcn, ... 'gui_OutputFcn', @drtool_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before drtool is made visible. function drtool_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to drtool (see VARARGIN) % Choose default command line output for drtool handles.output = hObject; set(handles.edr,'UserData',[]); % demention not estimated at begining % here data will be stored: handles.X=[]; handles.labels=[]; handles.islb=false; % if labels provided handles.isl=false; % if data loaded handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X handles.m1={}; % m-code from part1 handles.m2={}; % m-code from part2 handles.m21={}; % addition with no_dims handles.m3={}; % m-code from part3 handles.a2=false; % if code part with no_dims was writed handles.mstf={}; % save to file part handles.isxls=[]; % if data loaded as xls-file (will be used before save history) %handles.ndr=[]; % rounded number of dimention from intrinsic_dim, need for m-file % Update handles structure guidata(hObject, handles); % UIWAIT makes drtool wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = drtool_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in ld. function ld_Callback(hObject, eventdata, handles) handles.a2=false; set(handles.ld,'Enable','off'); drawnow; % load data lead to clear mapped data handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X set(handles.cd,'Visible','off'); try hs=load_data; catch set(handles.ld,'Enable','on'); return end hands_l_d=guidata(hs); if (~get(hands_l_d.file,'value'))&&(~get(hands_l_d.xls,'value')) %if not from file and not from xls-file handles.isxls=[]; set(hands_l_d.ok,'Enable','off'); drawnow; if get(hands_l_d.sw,'value') dataname='swiss'; end if get(hands_l_d.hl,'value') dataname='helix'; end if get(hands_l_d.tp,'value') dataname='twinpeaks'; end if get(hands_l_d.cl,'value') dataname='3d_clusters'; end if get(hands_l_d.is,'value') dataname='intersect'; end n=str2num(get(hands_l_d.ndp,'string')); noise=str2num(get(hands_l_d.nl,'string')); [X, labels] = generate_data(dataname, n,noise); handles.X=X; handles.labels=labels; handles.islb=true; handles.isl=true; set(handles.dld,'visible','on'); % m-file memorizing: % clear all previose history because new original dataset generated: handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; handles.m1={ '% generate data'; ['n = ' num2str(n) '; % number of datapoints' ]; ['noise = ' num2str(noise) '; % noise level' ]; ['[X, labels] = generate_data(''' dataname ''', n,noise); % generate ' dataname ' data']}; delete(hands_l_d.figure1); drawnow; else if get(hands_l_d.file,'value') % here if need to load data from file handles.isxls=false; delete(hands_l_d.figure1); drawnow; S = uiimport; if length(S)==0 handles.X=[]; handles.labels=[]; handles.islb=false; handles.isl=false; set(handles.dld,'visible','off'); handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; else vn=fieldnames(S); if length(vn)==1 X = getfield(S, vn{1}); hs1=load_data_1_var; hld1=guidata(hs1); if get(hld1.i,'value') cn=str2num(get(hld1.cn,'string')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; else % one variable without labels handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); handles.labels=[]; handles.islb=false; end delete(hld1.figure1); else hss=load_data_vars(vn); hlds=guidata(hss); Xn=get(hlds.d,'string'); X = getfield(S, Xn); if get(hlds.ni,'value') % not include handles.labels=[]; handles.islb=false; handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); end if get(hlds.iv,'value') % include from variable ivn=get(hlds.ivn,'String'); labels = getfield(S, ivn); handles.labels=labels; handles.islb=true; handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); end if get(hlds.ic,'value') % include from column cn=str2num(get(hlds.icn,'String')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; end delete(hlds.figure1); end % history: % clear: handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; if handles.islb handles.m1={'load(''X.mat''); % load data'; 'load(''labels.mat''); % load labels';}; else handles.m1={'load(''X.mat''); % load data'}; end end else % here if load from xls file handles.isxls=true; delete(hands_l_d.figure1); drawnow; [FileName,PathName] = uigetfile({'*.xls';'*.xlsx'},'Select the xls-file'); if (FileName==0) % do nothing if click cancel else X = xlsread([PathName FileName]); % load fom xls numbers only handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; hstmp=load_xls(length(X(1,:))); drawnow; hands_l_x=guidata(hstmp); if get(hands_l_x.wl,'value') % if not use labels handles.labels=[]; handles.islb=false; handles.X=X; handles.isl=true; % history: handles.m1={['PathName = ''' PathName '''; % path to xls-file']; ['FileName = ''' FileName '''; % file name of xls-file']; 'X = xlsread([PathName FileName]); % load xls file'}; set(handles.dld,'visible','on'); else % if use labels cn=str2num(get(hands_l_x.col,'String')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; % history: handles.m1={['PathName = ''' PathName '''; % path to xls-file']; ['FileName = ''' FileName '''; % file name of xls-file']; 'X = xlsread([PathName FileName]); % load xls file'; ['cn = ' num2str(cn) '; % column number where labels are placed']; 'lX=length(X(1,:)); % total number of column'; 'ncn1=1:lX;'; 'ncni=find(ncn1~=cn); % indexes of data columns'; 'ncn=ncn1(ncni); % data columns'; 'labels=X(:,cn); % get labels'; 'X=X(:,ncn); % get data'}; end delete(hands_l_x.figure1); drawnow; end end end set(handles.edr,'String',''); set(handles.cd,'visible','off'); handles.mcd=false; guidata(handles.figure1, handles); set(handles.ld,'Enable','on'); drawnow; % --- Executes on button press in sp. function sp_Callback(hObject, eventdata, handles) if handles.isl ld=length(handles.X(1,:)); if ld==2 hf=figure; set(hf,'name','Original dataset','NumberTitle','off'); if handles.islb scatter(handles.X(:,1),handles.X(:,2),5,handles.labels); else scatter(handles.X(:,1),handles.X(:,2),5); end title('Original dataset'); else if handles.islb scattern('Original dataset',handles.X,handles.labels); else scattern('Original dataset',handles.X); end end else % 'not loaded' not_loaded; end % --- Executes on button press in p. function p_Callback(hObject, eventdata, handles) if handles.isl ld=length(handles.X(1,:)); if ld==2 hf=figure; set(hf,'name','Original dataset','NumberTitle','off'); % if handles.islb % plot(handles.X(:,1),handles.X(:,2),5,handles.labels); % else plot(handles.X(:,1),handles.X(:,2),'.r'); % end title('Original dataset'); else % if handles.islb % scattern('Original dataset',handles.X,handles.labels); % else plotn('Original dataset',handles.X); % end end else % 'not loaded' not_loaded; end % --- Executes on button press in ed. function ed_Callback(hObject, eventdata, handles) handles.a2=false; if handles.isl try s=choose_method; catch return end hs1=guidata(s); set(hs1.ok,'Enable','off'); drawnow; method=get(hs1.str,'string'); no_dims = intrinsic_dim(handles.X, method); % estimate dimention lead to clear calculated data: handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X set(handles.cd,'Visible','off'); % history: handles.m2={}; handles.m3={}; handles.mstf={}; % get detailed method name from listbox: lstbs=get(hs1.listbox1,'string'); lstv=get(hs1.listbox1,'value'); mthds=lstbs{lstv}; handles.m2={['method_ed = ''' method '''; % (' mthds ') method of estimation of dimensionality']; ['no_dims = intrinsic_dim(X, method_ed); % estimate intrinsic dimensionality']}; delete(hs1.figure1); drawnow; set(handles.edr,'string',num2str(no_dims)); set(handles.edr,'UserData',no_dims); % memorize pricise value in userdata guidata(handles.figure1, handles); else % 'not loaded' not_loaded; end function edr_Callback(hObject, eventdata, handles) % hObject handle to edr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edr as text % str2double(get(hObject,'String')) returns contents of edr as a double % --- Executes during object creation, after setting all properties. function edr_CreateFcn(hObject, eventdata, handles) % hObject handle to edr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in cm. function cm_Callback(hObject, eventdata, handles) if handles.isl handles.m3={}; % eraise priviose history handles.mstf={}; no_dims=get(handles.edr,'UserData'); no_dims_old=no_dims; try s=mapping_parameters(no_dims,handles.islb); catch return end hs1=guidata(s); %mappedA = compute_mapping(A, type, no_dims, parameters, eig_impl) no_dims=str2num(get(hs1.nd,'string')); %if (~handles.a2)||(round(no_dims_old)~=no_dims) % if was not added or if changed handles.a2=true; if ~isempty(no_dims_old) if round(no_dims_old)~=no_dims % if demetion was changed handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; else handles.m21={' '; ['no_dims = round(no_dims); % round number of dimensions to have integer number']; ' '}; end else handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; end if isempty(handles.m2) handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; end %handles.m2=vertcat(handles.m2,m2t); %end mappedA=[]; try noparam=false; % if no parameters mthd=''; % method when no parameters switch get(hs1.listbox1,'Value') case 1 % PCA % no parameters; mappedA = compute_mapping(handles.X, 'PCA', no_dims); noparam=true; mthd='PCA'; case 2 % LDA % no parameters; % correct lables only to column-vector: lb=handles.labels; slb=size(lb); if min(slb)>1 warning('slb must be vector'); end if slb(1)<slb(2) lb=lb'; end if handles.islb mappedA = compute_mapping([lb handles.X], 'LDA', no_dims); % set labels through first column if slb(1)<slb(2) handles.m3={['labels=labels''; % labels must be a vector-column ']; ['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']}; else handles.m3={['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']}; end else % imposible because data without labels warning('it is imposible to be here'); end case 3 % MDS % no parameters; mappedA = compute_mapping(handles.X, 'MDS', no_dims); noparam=true; mthd='MDS'; case 4 % SimplePCA % no parameters; mappedA = compute_mapping(handles.X, 'SimplePCA', no_dims); noparam=true; mthd='SimplePCA'; case 5 % ProbPCA mi=str2num(get(hs1.mi,'string')); mappedA = compute_mapping(handles.X, 'ProbPCA', no_dims, mi); handles.m3={['mi = ' num2str(mi) '; % max iterations']; ['mappedX = compute_mapping(X, ''ProbPCA'', no_dims, mi);']}; case 6 % FactorAnalysis % no parameters; mappedA = compute_mapping(handles.X, 'FactorAnalysis', no_dims); noparam=true; mthd='FactorAnalysis'; case 7 % Isomap if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end mappedA = compute_mapping(handles.X, 'Isomap', no_dims, k); m3t={['mappedX = compute_mapping(X, ''Isomap'', no_dims, k);']}; handles.m3=vertcat(handles.m3,m3t); case 8 % LandmarkIsomap if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end prc=str2num(get(hs1.prc,'string')); m3t={['prc = ' num2str(prc) '; % percentage']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LandmarkIsomap', no_dims, k, prc); m3t={['mappedX = compute_mapping(X, ''LandmarkIsomap'', no_dims, k, prc);']}; handles.m3=vertcat(handles.m3,m3t); case 9 % LLE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); [mappedA, mapping] = compute_mapping(handles.X, 'LLE', no_dims, k, eim); m3t={['[mappedX, mapping] = compute_mapping(X, ''LLE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 10 % Laplacian if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'Laplacian', no_dims, k, sig, eim); m3t={['mappedX = compute_mapping(X, ''Laplacian'', no_dims, k, sig, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 11 % HessianLLE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'HessianLLE', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''HessianLLE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 12 % LTSA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LTSA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''LTSA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 13 % MVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'MVU', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''MVU'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 14 % CCA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'CCA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''CCA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 15 % LandmarkMVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end mappedA = compute_mapping(handles.X, 'LandmarkMVU', no_dims, k); m3t={['mappedX = compute_mapping(X, ''LandmarkMVU'', no_dims, k);']}; handles.m3=vertcat(handles.m3,m3t); case 16 % FastMVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end ft=get(hs1.fty,'value'); if ft m3t={['ft = true; % finetune']}; else m3t={['ft = false; % finetune']}; end handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'FastMVU', no_dims, k, ft, eim); m3t={['mappedX = compute_mapping(X, ''FastMVU'', no_dims, k, ft, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 17 % DiffusionMaps t=str2num(get(hs1.t,'string')); handles.m3={['t = ' num2str(t) ';']}; sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'DiffusionMaps', no_dims, t, sig); m3t={['mappedX = compute_mapping(X, ''DiffusionMaps'', no_dims, t, sig);']}; handles.m3=vertcat(handles.m3,m3t); case 18 % KernelPCA kernel='gauss'; if get(hs1.kl,'value') kernel='linear'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel); handles.m3={['kernel = ''linear'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']}; end if get(hs1.kg,'value') s=str2num(get(hs1.kgs,'string')); handles.m3={['s = ' num2str(s) '; % variance']}; kernel='gauss'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s); m3t={['kernel = ''gauss'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']}; handles.m3=vertcat(handles.m3,m3t); end if get(hs1.kp,'value') R=str2num(get(hs1.kpR,'string')); handles.m3={['R = ' num2str(R) '; % additional value']}; d=str2num(get(hs1.kpd,'string')); m3t={['d = ' num2str(d) '; % power number']}; handles.m3=vertcat(handles.m3,m3t); kernel='poly'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d); m3t={['kernel = ''poly'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']}; handles.m3=vertcat(handles.m3,m3t); end case 19 % GDA % correct lables only to column-vector: lb=handles.labels; slb=size(lb); if min(slb)>1 warning('slb must be vector'); end if slb(1)<slb(2) lb=lb'; end if slb(1)<slb(2) m3t={['labels=labels''; % labels must be a vector-column ']}; else m3t={}; end if handles.islb kernel='gauss'; if get(hs1.kl,'value') kernel='linear'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel); handles.m3={['kernel = ''linear'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']}; handles.m3=vertcat(m3t,handles.m3); end if get(hs1.kg,'value') s=str2num(get(hs1.kgs,'string')); handles.m3={['s = ' num2str(s) '; % variance']}; handles.m3=vertcat(m3t,handles.m3); kernel='gauss'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s); m3t={['kernel = ''gauss'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']}; handles.m3=vertcat(handles.m3,m3t); end if get(hs1.kp,'value') R=str2num(get(hs1.kpR,'string')); handles.m3={['R = ' num2str(R) '; % additional value']}; handles.m3=vertcat(m3t,handles.m3); d=str2num(get(hs1.kpd,'string')); m3t={['d = ' num2str(d) '; % power number']}; handles.m3=vertcat(handles.m3,m3t); kernel='poly'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d); m3t={['kernel = ''poly'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']}; handles.m3=vertcat(handles.m3,m3t); end else % imposible because data without labels warning('it is imposible to be here'); end case 20 % SNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 'SNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''SNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 21 % SymSNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 'SymSNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''SymSNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 22 % t-SNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 't-SNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''t-SNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 23 % LPP if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LPP', no_dims, k, sig, eim); m3t={['mappedX = compute_mapping(X, ''LPP'', no_dims, k, sig, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 24 % NPE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'NPE', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''NPE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 25 % LLTSA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LLTSA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''LLTSA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 26 % SPE tp='Global'; if get(hs1.tg,'value') tp='Global'; mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp); handles.m3={'tp = ''Global''; % type of stress function that minimized'; ['mappedX = compute_mapping(X, ''SPE'', no_dims, tp);']}; end if get(hs1.tl,'value') tp='Local'; k=str2num(get(hs1.k,'string')); mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp, k); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']; 'tp = ''Local''; % type of stress function that minimized'; ['mappedX = compute_mapping(X, ''SPE'', no_dims, tp, k);']}; end case 27 % AutoEncoder % no parameters; mappedA = compute_mapping(handles.X, 'Autoencoder', no_dims); noparam=true; mthd='Autoencoder'; case 28 % LLC % no parameters; mappedA = compute_mapping(handles.X, 'LLC', no_dims); noparam=true; mthd='LLC'; case 29 % LLC if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end na=str2num(get(hs1.na,'string')); m3t={['na = ' num2str(na) '; % number of factor analyzers']}; handles.m3=vertcat(handles.m3,m3t); mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end mappedA = compute_mapping(handles.X, 'LLC', no_dims, k, na, mi, eim); m3t={['mappedX = compute_mapping(X, ''LLC'', no_dims, k, na, mi, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 30 % ManifoldChart na=str2num(get(hs1.na,'string')); handles.m3={['na = ' num2str(na) '; % number of factor analyzers']}; mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end mappedA = compute_mapping(handles.X, 'ManifoldChart', no_dims, na, mi, eim); m3t={['mappedX = compute_mapping(X, ''ManifoldChart'', no_dims, na, mi, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 31 % CFA na=str2num(get(hs1.na,'string')); handles.m3={['na = ' num2str(na) '; % number of factor analyzers']}; mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'CFA', no_dims, na, mi); m3t={['mappedX = compute_mapping(X, ''CFA'', no_dims, na, mi);']}; handles.m3=vertcat(handles.m3,m3t); case 32 % GPLVM sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'GPLVM', no_dims, sig); m3t={['mappedX = compute_mapping(X, ''GPLVM'', no_dims, sig);']}; handles.m3=vertcat(handles.m3,m3t); case 33 % NCA mappedA = compute_mapping(handles.X, 'NCA', no_dims); m3t={'mappedX = compute_mapping(X, ''NCA'', no_dims);'}; handles.m3=vertcat(handles.m3,m3t); case 34 % MCML mappedA = compute_mapping(handles.X, 'MCML', no_dims); m3t={'mappedX = compute_mapping(X, ''MCML'', no_dims);'}; handles.m3=vertcat(handles.m3,m3t); end if noparam handles.m3={['mappedX = compute_mapping(X, ''' mthd ''', no_dims); % compute mapping using ' mthd ' method']}; end catch set(handles.cd,'visible','off'); handles.mcd=false; warning('mapping was not calculated'); handles.m3={}; handles.mstf={}; guidata(handles.figure1, handles); delete(hs1.figure1); drawnow; rethrow(lasterror); return end if length(mappedA)~=0 set(handles.cd,'visible','on'); handles.mX=mappedA; handles.mcd=true; else set(handles.cd,'visible','off'); handles.mcd=false; warning('mapping was not calculated'); handles.m3={}; handles.mstf={}; end guidata(handles.figure1, handles); delete(hs1.figure1); drawnow; else % 'not loaded' not_loaded; end % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) if handles.mcd ld=length(handles.mX(1,:)); if ld==2 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); if handles.islb && size(handles.mX, 1) == numel(handles.labels) scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels); else scatter(handles.mX(:,1),handles.mX(:,2),5); end title('Result of dimensionality reduction'); if size(handles.mX, 1) ~= numel(handles.labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end else if ld==1 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); if handles.islb && size(handles.mX, 1) == numel(handles.labels) scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels); else scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5); end title('Result of dimensionality reduction'); if size(handles.mX, 1) ~= numel(handles.labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end else if handles.islb scattern('Result of dimensionality reduction',handles.mX,handles.labels); else scattern('Result of dimensionality reduction',handles.mX); end end end else % 'not calulated' not_calculated; end % --- Executes on button press in pushbutton7. function pushbutton7_Callback(hObject, eventdata, handles) if handles.mcd ld=length(handles.mX(1,:)); if ld==2 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); % if handles.islb % scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels); % else plot(handles.mX(:,1),handles.mX(:,2),'.r'); % end title('Result of dimensionality reduction'); else if ld==1 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); %if handles.islb %scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels); %else plot(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),'.k'); %end title('Result of dimensionality reduction'); else %if handles.islb % scattern('Result of dimensionality reduction',handles.mX,handles.labels); %else plotn('Result of dimensionality reduction',handles.mX); %end end end else % 'not calulated' not_calculated; end % --- Executes on button press in stmf. function stmf_Callback(hObject, eventdata, handles) [file,path] = uiputfile('*.mat','Save Mapped Data As'); if length(file)==1 if file==0 return end end mX=handles.mX; save([path file], 'mX'); % --- Executes on button press in sttf. function sttf_Callback(hObject, eventdata, handles) [file,path] = uiputfile('*.txt','Save Mapped Data As'); if length(file)==1 if file==0 return end end mX=handles.mX; save([path file], 'mX','-ascii', '-tabs'); % --- Executes on button press in stf. function stf_Callback(hObject, eventdata, handles) set(handles.stf,'Enable','off'); drawnow; if handles.mcd if get(handles.stmfr,'value') [file,path] = uiputfile('*.mat','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; save([path file], 'mX'); handles.mstf={['save(''' path file ''', ''mappedX''); % save result to mat-file']}; end if get(handles.sttfr,'value') [file,path] = uiputfile('*.txt','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; save([path file], 'mX','-ascii', '-tabs'); handles.mstf={['save(''' path file ''', ''mappedX'',''-ascii'', ''-tabs''); % save result to txt-file']}; end if get(handles.stxfr,'value') [file,path] = uiputfile('*.xls','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; xlswrite([path file], mX); handles.mstf={['xlswrite(''' path file ''', mappedX); % save result to xls-file']}; end guidata(handles.figure1, handles); else % 'not calulated' not_calculated; end set(handles.stf,'Enable','on'); drawnow; % --- Executes when selected object is changed in uipanel1. function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) % hObject handle to the selected object in uipanel1 % eventdata structure with the following fields (see UIBUTTONGROUP) % EventName: string 'SelectionChanged' (read only) % OldValue: handle of the previously selected object or empty if none was selected % NewValue: handle of the currently selected object % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in sh. function sh_Callback(hObject, eventdata, handles) set(handles.sh,'enable','off'); drawnow; if (isempty(handles.m1))&&(isempty(handles.m2))&&(isempty(handles.m3)) no_history; else [file,path] = uiputfile('*.m','Save History As'); if length(file)==1 if file==0 set(handles.sh,'enable','on'); drawnow; return end end fid = fopen([path file],'w'); fprintf(fid,'%s\r\n',['% this file was generated by drtool at ' datestr(now)]); fprintf(fid,'%s\r\n',' '); % empty line - delimeter if ~isempty(handles.isxls) if ~handles.isxls % here if txt/mat file was loaded so it is need save data and labels X=handles.X; save([path 'X.mat'],'X'); if handles.islb % save labells if any labels=handles.labels; save([path 'labels.mat'],'labels'); fprintf(fid,'%s\r\n','% Note: data and labels were saved in X.mat and labels.mat together with this m-file in the same folder'); else fprintf(fid,'%s\r\n','% Note: data was saved in X.mat together with this m-file in the same folder'); end end end fprintf(fid,'%s\r\n',' '); fprintf(fid,'%s\r\n','% 1.'); fprintf(fid,'%s\r\n','% get data'); for mc=1:length(handles.m1) fprintf(fid,'%s\r\n',handles.m1{mc}); end % plot original data: mpod={'% plot original data:'}; ld=length(handles.X(1,:)); if ld==2 mpodt={'hf=figure;'; 'set(hf,''name'',''Original dataset'',''NumberTitle'',''off'');'}; mpod=vertcat(mpod,mpodt); if handles.islb mpodt={'scatter(X(:,1),X(:,2),5,labels);'}; else mpodt={'plot(X(:,1),X(:,2),''x-'');'}; end mpod=vertcat(mpod,mpodt); mpodt={'title(''Original dataset'');'}; mpod=vertcat(mpod,mpodt); else if handles.islb mpodt={'scattern(''Original dataset'',X,labels);'}; else mpodt={'plotn(''Original dataset'',X);'}; end mpod=vertcat(mpod,mpodt); end fprintf(fid,'%s\r\n',' '); for mc=1:length(mpod) fprintf(fid,'%s\r\n',mpod{mc}); end fprintf(fid,'%s\r\n',' '); if length(handles.m2)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter handles.m2=vertcat(handles.m2,handles.m21); fprintf(fid,'%s\r\n','% 2.'); fprintf(fid,'%s\r\n','% estimate intrinsic dimensionality'); for mc=1:length(handles.m2) fprintf(fid,'%s\r\n',handles.m2{mc}); end else if length(handles.m3)~=0 % if was not dimetion estimation thet it is need to set it for % part 3 for mc=1:length(handles.m21) fprintf(fid,'%s\r\n',handles.m21{mc}); end end end if length(handles.m3)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter fprintf(fid,'%s\r\n','% 3.'); fprintf(fid,'%s\r\n','% compute mapping'); for mc=1:length(handles.m3) fprintf(fid,'%s\r\n',handles.m3{mc}); end % plot result mpod={'% plot result of dimensionality reduction:'}; if handles.islb mpodt={'scatter12n(''Result of dimensionality reduction'',mappedX,labels);'}; else mpodt={'plot12n(''Result of dimensionality reduction'',mappedX);'}; end mpod=vertcat(mpod,mpodt); fprintf(fid,'%s\r\n',' '); for mc=1:length(mpod) fprintf(fid,'%s\r\n',mpod{mc}); end fprintf(fid,'%s\r\n',' '); end if length(handles.mstf)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter fprintf(fid,'%s\r\n',' '); % empty line - delimeter for mc=1:length(handles.mstf) fprintf(fid,'%s\r\n',handles.mstf{mc}); end end fclose(fid); end set(handles.sh,'enable','on'); drawnow;
github
eulertech/DeepLearningCrudeOilForecast-master
plot12n.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/plot12n.m
1,356
utf_8
8a16c46e9b838f4602a5af8fc8a857a8
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function plot12n(name,data) ld=length(data(1,:)); if ld==2 hf=figure; set(hf,'name',name,'NumberTitle','off'); % if handles.islb % scatter(data(:,1),data(:,2),5,handles.labels); % else plot(data(:,1),data(:,2),'.r'); % end title(name); else if ld==1 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb %scatter(data(:,1),zeros(length(data(:,1)),1),5,handles.labels); %else plot(data(:,1),zeros(length(data(:,1)),1),'.k'); %end title(name); else %if handles.islb % scattern('Result of dimensionality reduction',data,handles.labels); %else plotn(name,data); %end end end
github
eulertech/DeepLearningCrudeOilForecast-master
not_loaded.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/not_loaded.m
7,728
utf_8
a754380baacab27eac13658ea4cc21a3
function varargout = not_loaded(varargin) % NOT_LOADED M-file for not_loaded.fig % NOT_LOADED by itself, creates a new NOT_LOADED or raises the % existing singleton*. % % H = NOT_LOADED returns the handle to a new NOT_LOADED or the handle to % the existing singleton*. % % NOT_LOADED('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NOT_LOADED.M with the given input arguments. % % NOT_LOADED('Property','Value',...) creates a new NOT_LOADED or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before not_loaded_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to not_loaded_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help not_loaded % Last Modified by GUIDE v2.5 24-Jul-2008 18:38:56 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @not_loaded_OpeningFcn, ... 'gui_OutputFcn', @not_loaded_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before not_loaded is made visible. function not_loaded_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to not_loaded (see VARARGIN) % Choose default command line output for not_loaded handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes not_loaded wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = not_loaded_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
eulertech/DeepLearningCrudeOilForecast-master
load_data.m
.m
DeepLearningCrudeOilForecast-master/drtoolbox/gui/load_data.m
6,534
utf_8
ade0538cbeeb79ed3c72aea5743a2424
function varargout = load_data(varargin) % LOAD_DATA M-file for load_data.fig % LOAD_DATA, by itself, creates a new LOAD_DATA or raises the existing % singleton*. % % H = LOAD_DATA returns the handle to a new LOAD_DATA or the handle to % the existing singleton*. % % LOAD_DATA('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA.M with the given input arguments. % % LOAD_DATA('Property','Value',...) creates a new LOAD_DATA or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data % Last Modified by GUIDE v2.5 23-Jul-2008 16:01:33 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_OpeningFcn, ... 'gui_OutputFcn', @load_data_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data is made visible. function load_data_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data (see VARARGIN) % Choose default command line output for load_data handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes load_data wait for user response (see UIRESUME) uiwait(handles.figure1); % uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function ndp_Callback(hObject, eventdata, handles) % hObject handle to ndp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ndp as text % str2double(get(hObject,'String')) returns contents of ndp as a double % --- Executes during object creation, after setting all properties. function ndp_CreateFcn(hObject, eventdata, handles) % hObject handle to ndp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nl_Callback(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of nl as text % str2double(get(hObject,'String')) returns contents of nl as a double % --- Executes during object creation, after setting all properties. function nl_CreateFcn(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.file,'value') cl=[0.4 0.4 0.4]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','off'); set(handles.nl,'Enable','off'); set(handles.ok,'String','Start wizard'); else cl=[0 0 0]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','on'); set(handles.nl,'Enable','on'); set(handles.ok,'String','OK'); end if get(handles.xls,'value') cl=[0.4 0.4 0.4]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','off'); set(handles.nl,'Enable','off'); set(handles.ok,'String','Open XLS-file'); else if ~get(handles.file,'value') cl=[0 0 0]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','on'); set(handles.nl,'Enable','on'); set(handles.ok,'String','OK'); end end
github
thomasjlew/davis_tracker-master
knnsearch.m
.m
davis_tracker-master/src/knnsearch.m
4,157
utf_8
bf67a671cf817680b7a3f8a108d816e1
function [idx,D]=knnsearch(varargin) % TLEW Note 09/29/17: Code Taken from https://ch.mathworks.com/ % matlabcentral/fileexchange/19345-efficient-k-nearest-neighbor-search- % using-jit?focused=5151612&tab=function % KNNSEARCH Linear k-nearest neighbor (KNN) search % IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array % representing n points in a d-dimensional space) to find the k-nearest % neighbors of each query point represented by eahc row of Q (m x d array). % The results are stored in the (m x K) index array, IDX. % % IDX = knnsearch(Q,R) takes the default value K=1. % % IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q. % % Rationality % Linear KNN search is the simplest appraoch of KNN. The search is based on % calculation of all distances. Therefore, it is normally believed only % suitable for small data sets. However, other advanced approaches, such as % kd-tree and delaunary become inefficient when d is large comparing to the % number of data points. On the other hand, the linear search in MATLAB is % relatively insensitive to d due to the vectorization. In this code, the % efficiency of linear search is further improved by using the JIT % aceeleration of MATLAB. Numerical example shows that its performance is % comparable with kd-tree algorithm in mex. % % See also, kdtree, nnsearch, delaunary, dsearch % By Yi Cao at Cranfield University on 25 March 2008 % Example 1: small data sets %{ R=randn(100,2); Q=randn(3,2); idx=knnsearch(Q,R); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx'); %} % Example 2: ten nearest points to [0 0] %{ R=rand(100,2); Q=[0 0]; K=10; idx=knnsearch(Q,R,10); r=max(sqrt(sum(R(idx,:).^2,2))); theta=0:0.01:pi/2; x=r*cos(theta); y=r*sin(theta); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2); %} % Example 3: cputime comparion with delaunay+dsearch I, a few to look up %{ R=randn(10000,4); Q=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 4: cputime comparion with delaunay+dsearch II, lots to look up %{ Q=randn(10000,4); R=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 5: cputime comparion with kd-tree by Steven Michael (mex file) % <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=7030&objectType=file">kd-tree by Steven Michael</a> %{ Q=randn(10000,10); R=randn(500,10); t0=cputime; idx=knnsearch(Q,R); t1=cputime; tree=kdtree(R); idx1=kdtree_closestpoint(tree,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Check inputs [Q,R,K,fident] = parseinputs(varargin{:}); % Check outputs error(nargoutchk(0,2,nargout)); % C2 = sum(C.*C,2)'; [N,M] = size(Q); L=size(R,1); idx = zeros(N,K); D = idx; if K==1 % Loop for each query point for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [D(k),idx(k)]=min(d); end else for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [s,t]=sort(d); idx(k,:)=t(1:K); D(k,:)=s(1:K); end end if nargout>1 D=sqrt(D); end function [Q,R,K,fident] = parseinputs(varargin) % Check input and output error(nargchk(1,3,nargin)); Q=varargin{1}; if nargin<2 R=Q; fident = true; else fident = false; R=varargin{2}; end if isempty(R) fident = true; R=Q; end if ~fident fident = isequal(Q,R); end if nargin<3 K=1; else K=varargin{3}; end
github
thomasjlew/davis_tracker-master
is_in_patch.m
.m
davis_tracker-master/src/is_in_patch.m
1,506
utf_8
8c0cf739ecbaf71ac334f7dcf48440c8
% IS_IN_PATCH - Determines if a point is inside a patch % % Syntax: is_in_patch(event_x, event_y, patches(patch_id), PATCH_WIDTH) % % Inputs: % - pt_x: x position of the point % - pt_y: y position of the point % - patch: patch structure as defined in "features_main.m" % - PATCH_WIDTH: Width of the patch % % Outputs: % Boolean: true if the event is in the patch % % Example: % if is_in_patch(event_x, event_y, patches(patch_id), PATCH_WIDTH) % ... % % Author: Thomas Lew % email: [email protected] % Website: https://github.com/thomasjlew/ % September 2017; Last revision: 22-September-2017 %------------- BEGIN CODE -------------- function [ b_is_inside_patch ] = is_in_patch( pt_x, pt_y, patch, PATCH_WIDTH ) %IS_IN_PATCH - Returns true if the point is inside the patch % Inputs: % patch - structure containing all elements of a patch % patch.feat_pos - x&y coord of features point wrt. img % patch.model_pts - coord of model points wrt. image % pt_x & pt_y - point coordinates wrt. image if pt_x >= (patch.feat_pos(1) - PATCH_WIDTH/2) && ... pt_x <= (patch.feat_pos(1) + PATCH_WIDTH/2) && ... pt_y >= (patch.feat_pos(2) - PATCH_WIDTH/2) && ... pt_y <= (patch.feat_pos(2) + PATCH_WIDTH/2) b_is_inside_patch = true; return else b_is_inside_patch = false; return end end %------------- END OF CODE --------------
github
thomasjlew/davis_tracker-master
icp.m
.m
davis_tracker-master/src/icp.m
18,480
utf_8
fdad7e189d4f40abc7d4f4d67948f984
function [TR, TT, ER, t] = icp(q,p,varargin) % TLEW Note 09/29/17: Code Taken from https://ch.mathworks.com/ % matlabcentral/fileexchange/27804-iterative-closest-point % Perform the Iterative Closest Point algorithm on three dimensional point % clouds. % % [TR, TT] = icp(q,p) returns the rotation matrix TR and translation % vector TT that minimizes the distances from (TR * p + TT) to q. % p is a 3xm matrix and q is a 3xn matrix. % % [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations % exactly. The default is 10 iterations. % % [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k % iterations in a (k+1)x1 vector. ER(0) is the initial error. % % [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per % iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing. % % Additional settings may be provided in a parameter list: % % Boundary % {[]} | 1x? vector % If EdgeRejection is set, a vector can be provided that indexes into % q and specifies which points of q are on the boundary. % % EdgeRejection % {false} | true % If EdgeRejection is true, point matches to edge vertices of q are % ignored. Requires that boundary points of q are specified using % Boundary or that a triangulation matrix for q is provided. % % Extrapolation % {false} | true % If Extrapolation is true, the iteration direction will be evaluated % and extrapolated if possible using the method outlined by % Besl and McKay 1992. % % Matching % {bruteForce} | Delaunay | kDtree % Specifies how point matching should be done. % bruteForce is usually the slowest and kDtree is the fastest. % Note that the kDtree option is depends on the Statistics Toolbox % v. 7.3 or higher. % % Minimize % {point} | plane | lmaPoint % Defines whether point to point or point to plane minimization % should be performed. point is based on the SVD approach and is % usually the fastest. plane will often yield higher accuracy. It % uses linearized angles and requires surface normals for all points % in q. Calculation of surface normals requires substantial pre % proccessing. % The option lmaPoint does point to point minimization using the non % linear least squares Levenberg Marquardt algorithm. Results are % generally the same as in points, but computation time may differ. % % Normals % {[]} | n x 3 matrix % A matrix of normals for the n points in q might be provided. % Normals of q are used for point to plane minimization. % Else normals will be found through a PCA of the 4 nearest % neighbors. % % ReturnAll % {false} | true % Determines whether R and T should be returned for all iterations % or only for the last one. If this option is set to true, R will be % a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix. % % Triangulation % {[]} | ? x 3 matrix % A triangulation matrix for the points in q can be provided, % enabling EdgeRejection. The elements should index into q, defining % point triples that act together as triangles. % % Verbose % {false} | true % Enables extrapolation output in the Command Window. % % Weight % {@(match)ones(1,m)} | Function handle % For point or plane minimization, a function handle to a weighting % function can be provided. The weighting function will be called % with one argument, a 1xm vector that specifies point pairs by % indexing into q. The weighting function should return a 1xm vector % of weights for every point pair. % % WorstRejection % {0} | scalar in ]0; 1[ % Reject a given percentage of the worst point pairs, based on their % Euclidean distance. % % Martin Kjer and Jakob Wilm, Technical University of Denmark, 2012 % Use the inputParser class to validate input arguments. inp = inputParser; inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3); inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3); inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5); inp.addParamValue('Boundary', [], @(x)size(x,1) == 1); inp.addParamValue('EdgeRejection', false, @(x)islogical(x)); inp.addParamValue('Extrapolation', false, @(x)islogical(x)); validMatching = {'bruteForce','Delaunay','kDtree'}; inp.addParamValue('Matching', 'bruteForce', @(x)any(strcmpi(x,validMatching))); validMinimize = {'point','plane','lmapoint'}; inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize))); inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('ReturnAll', false, @(x)islogical(x)); inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3); inp.addParamValue('Verbose', false, @(x)islogical(x)); inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle')); inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1); inp.parse(q,p,varargin{:}); arg = inp.Results; clear('inp'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Actual implementation % Allocate vector for RMS of errors in every iteration. t = zeros(arg.iter+1,1); % Start timer tic; Np = size(p,2); % Transformed data point cloud pt = p; % Allocate vector for RMS of errors in every iteration. ER = zeros(arg.iter+1,1); % Initialize temporary transform vector and matrix. T = zeros(3,1); R = eye(3,3); % Initialize total transform vector(s) and rotation matric(es). TT = zeros(3,1, arg.iter+1); TR = repmat(eye(3,3), [1,1, arg.iter+1]); % If Minimize == 'plane', normals are needed if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals)) arg.Normals = lsqnormest(q,4); end % If Matching == 'Delaunay', a triangulation is needed if strcmp(arg.Matching, 'Delaunay') DT = DelaunayTri(transpose(q)); end % If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3) if strcmp(arg.Matching, 'kDtree') kdOBJ = KDTreeSearcher(transpose(q)); end % If edge vertices should be rejected, find edge vertices if arg.EdgeRejection if isempty(arg.Boundary) bdr = find_bound(q, arg.Triangulation); else bdr = arg.Boundary; end end if arg.Extrapolation % Initialize total transform vector (quaternion ; translation vec.) qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)]; % Allocate vector for direction change and change angle. dq = zeros(7,arg.iter+1); theta = zeros(1,arg.iter+1); end t(1) = toc; % Go into main iteration loop for k=1:arg.iter % Do matching switch arg.Matching case 'bruteForce' [match mindist] = match_bruteForce(q,pt); case 'Delaunay' [match mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [match mindist] = match_kDtree(q,pt,kdOBJ); end % If matches to edge vertices should be rejected if arg.EdgeRejection p_idx = not(ismember(match, bdr)); q_idx = match(p_idx); mindist = mindist(p_idx); else p_idx = true(1, Np); q_idx = match; end % If worst matches should be rejected if arg.WorstRejection edge = round((1-arg.WorstRejection)*sum(p_idx)); pairs = find(p_idx); [~, idx] = sort(mindist); p_idx(pairs(idx(edge:end))) = false; q_idx = match(p_idx); mindist = mindist(p_idx); end if k == 1 ER(k) = sqrt(sum(mindist.^2)/length(mindist)); end switch arg.Minimize case 'point' % Determine weight vector weights = arg.Weight(match); [R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx)); case 'plane' weights = arg.Weight(match); [R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx)); case 'lmaPoint' [R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx)); end % Add to the total transformation TR(:,:,k+1) = R*TR(:,:,k); TT(:,:,k+1) = R*TT(:,:,k)+T; % Apply last transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Root mean of objective function ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx)); % If Extrapolation, we might be able to move quicker if arg.Extrapolation qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)]; dq(:,k+1) = qq(:,k+1) - qq(:,k); theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1)))); if arg.Verbose disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]); end if k>2 && theta(k+1) < 10 && theta(k) < 10 d = [ER(k+1), ER(k), ER(k-1)]; v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))]; vmax = 25 * norm(dq(:,k+1)); dv = extrapolate(v,d,vmax); if dv ~= 0 q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1)); q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4)); qq(:,k+1) = q_mark; TR(:,:,k+1) = quat2rmat(qq(1:4,k+1)); TT(:,:,k+1) = qq(5:7,k+1); % Reapply total transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Recalculate root mean of objective function % Note this is costly and only for fun! switch arg.Matching case 'bruteForce' [~, mindist] = match_bruteForce(q,pt); case 'Delaunay' [~, mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [~, mindist] = match_kDtree(q,pt,kdOBJ); end ER(k+1) = sqrt(sum(mindist.^2)/length(mindist)); end end end t(k+1) = toc; end if not(arg.ReturnAll) TR = TR(:,:,end); TT = TT(:,:,end); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_bruteForce(q, p) m = size(p,2); n = size(q,2); match = zeros(1,m); mindist = zeros(1,m); for ki=1:m d=zeros(1,n); for ti=1:3 d=d+(q(ti,:)-p(ti,ki)).^2; end [mindist(ki),match(ki)]=min(d); end mindist = sqrt(mindist); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_Delaunay(q, p, DT) match = transpose(nearestNeighbor(DT, transpose(p))); mindist = sqrt(sum((p-q(:,match)).^2,1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_kDtree(~, p, kdOBJ) [match mindist] = knnsearch(kdOBJ,transpose(p)); match = transpose(match); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_point(q,p,weights) m = size(p,2); n = size(q,2); % normalize weights weights = weights ./ sum(weights); % find data centroid and deviations from centroid q_bar = q * transpose(weights); q_mark = q - repmat(q_bar, 1, n); % Apply weights q_mark = q_mark .* repmat(weights, 3, 1); % find data centroid and deviations from centroid p_bar = p * transpose(weights); p_mark = p - repmat(p_bar, 1, m); % Apply weights %p_mark = p_mark .* repmat(weights, 3, 1); N = p_mark*transpose(q_mark); % taking points of q in matched order [U,~,V] = svd(N); % singular value decomposition R = V*diag([1 1 det(U*V')])*transpose(U); T = q_bar - R*p_bar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_plane(q,p,n,weights) n = n .* repmat(weights,3,1); c = cross(p,n); cn = vertcat(c,n); C = cn*transpose(cn); b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n)); sum(sum((p-q).*repmat(cn(2,:),3,1).*n)); sum(sum((p-q).*repmat(cn(3,:),3,1).*n)); sum(sum((p-q).*repmat(cn(4,:),3,1).*n)); sum(sum((p-q).*repmat(cn(5,:),3,1).*n)); sum(sum((p-q).*repmat(cn(6,:),3,1).*n))]; X = C\b; cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3)); sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3)); R = [cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz; cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx; -sy cy*sx cx*cy]; T = X(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_lmaPoint(q,p) Rx = @(a)[1 0 0; 0 cos(a) -sin(a); 0 sin(a) cos(a)]; Ry = @(b)[cos(b) 0 sin(b); 0 1 0; -sin(b) 0 cos(b)]; Rz = @(g)[cos(g) -sin(g) 0; sin(g) cos(g) 0; 0 0 1]; Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3)); myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata)); options = optimset('Algorithm', 'levenberg-marquardt'); x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options); R = Rot(x(1:3)); T = x(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extrapolation in quaternion space. Details are found in: % % Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes. % IEEE Transactions on pattern analysis and machine intelligence, 239?256. function [dv] = extrapolate(v,d,vmax) p1 = polyfit(v,d,1); % linear fit p2 = polyfit(v,d,2); % parabolic fit v1 = -p1(2)/p1(1); % linear zero crossing v2 = -p2(2)/(2*p2(1)); % polynomial top point if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1]) disp('Parabolic update!'); dv = v2; elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])... || (v2 < 0 && issorted([0 v1 vmax])) disp('Line based update!'); dv = v1; elseif v1 > vmax && v2 > vmax disp('Maximum update!'); dv = vmax; else disp('No extrapolation!'); dv = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Determine the RMS error between two point equally sized point clouds with % point correspondance. % ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices. function ER = rms_error(p1,p2) dsq = sum(power(p1 - p2, 2),1); ER = sqrt(mean(dsq)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (orthogonal) rotation matrices R to (unit) quaternion % representations % % Input: A 3x3xn matrix of rotation matrices % Output: A 4xn matrix of n corresponding quaternions % % http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion function quaternion = rmat2quat(R) Qxx = R(1,1,:); Qxy = R(1,2,:); Qxz = R(1,3,:); Qyx = R(2,1,:); Qyy = R(2,2,:); Qyz = R(2,3,:); Qzx = R(3,1,:); Qzy = R(3,2,:); Qzz = R(3,3,:); w = 0.5 * sqrt(1+Qxx+Qyy+Qzz); x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz); y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz); z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz); quaternion = reshape([w;x;y;z],4,[]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (unit) quaternion representations to (orthogonal) rotation matrices R % % Input: A 4xn matrix of n quaternions % Output: A 3x3xn matrix of corresponding rotation matrices % % http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix function R = quat2rmat(quaternion) q0(1,1,:) = quaternion(1,:); qx(1,1,:) = quaternion(2,:); qy(1,1,:) = quaternion(3,:); qz(1,1,:) = quaternion(4,:); R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy; 2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx; 2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Least squares normal estimation from point clouds using PCA % % H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle. % Surface reconstruction from unorganized points. % In Proceedings of ACM Siggraph, pages 71:78, 1992. % % p should be a matrix containing the horizontally concatenated column % vectors with points. k is a scalar indicating how many neighbors the % normal estimation is based upon. % % Note that for large point sets, the function performs significantly % faster if Statistics Toolbox >= v. 7.3 is installed. % % Jakob Wilm 2010 function n = lsqnormest(p, k) m = size(p,2); n = zeros(3,m); v = ver('stats'); if str2double(v.Version) >= 7.5 neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1)); else neighbors = k_nearest_neighbors(p, p, k+1); end for i = 1:m x = p(:,neighbors(2:end, i)); p_bar = 1/k * sum(x,2); P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P %P = 2*cov(x); [V,D] = eig(P); [~, idx] = min(diag(D)); % choses the smallest eigenvalue n(:,i) = V(:,idx); % returns the corresponding eigenvector end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Program to find the k - nearest neighbors (kNN) within a set of points. % Distance metric used: Euclidean distance % % Note that this function makes repetitive use of min(), which seems to be % more efficient than sort() for k < 30. function [neighborIds neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k) numDataPoints = size(dataMatrix,2); numQueryPoints = size(queryMatrix,2); neighborIds = zeros(k,numQueryPoints); neighborDistances = zeros(k,numQueryPoints); D = size(dataMatrix, 1); %dimensionality of points for i=1:numQueryPoints d=zeros(1,numDataPoints); for t=1:D % this is to avoid slow repmat() d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2; end for j=1:k [s,t] = min(d); neighborIds(j,i)=t; neighborDistances(j,i)=sqrt(s); d(t) = NaN; % remove found number from d end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Boundary point determination. Given a set of 3D points and a % corresponding triangle representation, returns those point indices that % define the border/edge of the surface. function bound = find_bound(pts, poly) %Correcting polygon indices and converting datatype poly = double(poly); pts = double(pts); %Calculating freeboundary points: TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)'); FF = freeBoundary(TR); %Output bound = FF(:,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
thomasjlew/davis_tracker-master
show_frames.m
.m
davis_tracker-master/src/show_frames.m
2,916
utf_8
8747c8f29ebef9ce6102ca26116d4ad0
% SHOW_FRAMES - Show all frames quickly from "The Event-Camera Dataset" [1] % Syntax: show_frames % % Inputs: % Frames from "The Event-Camera Dataset" [2] % % Outputs: % Images shown sequentially from the set [2] % % Example: % show_frames % % Other m-files required: none % Subfunctions: none % MAT-files required: none % Dataset required: Any set from "The Event-Camera Dataset" [1] % References: % [1] E. Mueggler, H. Rebecq, G. Gallego, T. Delbruck, D. Scaramuzza % The Event-Camera Dataset and Simulator: Event-based Data for Pose % Estimation, Visual Odometry, and SLAM, International Journal of % Robotics Research, Vol. 36, Issue 2, pages 142-149, Feb. 2017. % Author: Thomas Lew % email: [email protected] % Website: https://github.com/thomasjlew/ % September 2017; Last revision: 26-September-2017 %------------- BEGIN CODE -------------- clc; close all; clear all; DATASET_PATH = './shapes_6dof/'; % DATASET_PATH = './poster_6dof/'; B_EXTRACT_FRAMES_ONLY_ONCE = true; NB_MAX_FRAMES = inf; SIZE_FRAME_IMG = 0; % Initialized in the code % NB_STRONGEST_FEAT = 30; NB_STRONGEST_FEAT = 4; PATCH_WIDTH = 24; % We use square patches of width 25 (around middle pixel) NB_MAX_EVENTS_PER_FRAME = 10000; % put 100 is max I think B_PLOT_EVENTS = false; B_PLOT_SUBPLOT3 = true; PATCH_PLOT_ID = 3; global sb2_fh; global sb3_fh; % necessary to erase it within a function global sb3_axis; % From paper: In practice, % it is more efficient to compute the registration transformation % every M events, e.g., of half the size of the model point set. NEW_EVENTS_TO_REGISTR_FACTOR = 2; % Open .txt files frames_fileID = fopen(strcat(DATASET_PATH,'images.txt'),'r'); events_fileID = fopen(strcat(DATASET_PATH,'events.txt'),'r'); for frame_nb = 1:NB_MAX_FRAMES fprintf('---------------\n'); fprintf(strcat('New frame nb: ',int2str(frame_nb),'\n')); fprintf('---------------\n'); % -------------------------------------- % Find, Read and Display the frame image % -------------------------------------- % Find image from header tmp_frame_header=textscan(frames_fileID,'%f %s',1,'Delimiter','\n'); % OPTIMIZATION: REPLACE WITH GETL & SSCANF frame_cur_t = tmp_frame_header{1,1}; frame_cur_img_file = strcat(DATASET_PATH,cell2mat(tmp_frame_header{1,2})); % Read & display image frame_cur_img = imread(frame_cur_img_file); SIZE_FRAME_IMG = size(frame_cur_img); % hFig = figure(1); % set(hFig, 'Position', [100 1000 1000 1000]) imshow(frame_cur_img); % subplot1_setup(strcat('Raw Image n°', int2str(frame_nb),' with features'), ... % frame_cur_img); end %% Plotting function function subplot1_setup(my_title, image) hFig = figure(1); set(hFig, 'Position', [100 0 1000 1000]) subplot(2,2,1); imshow(image); title(my_title); hold on; end
github
yilei0620/RGBD-Slam-Semantic-Seg-DeepLab-master
classification_demo.m
.m
RGBD-Slam-Semantic-Seg-DeepLab-master/deeplab/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
yilei0620/RGBD-Slam-Semantic-Seg-DeepLab-master
MyVOCevalseg.m
.m
RGBD-Slam-Semantic-Seg-DeepLab-master/deeplab/matlab/my_script/MyVOCevalseg.m
4,625
utf_8
128c24319d520c2576168d1cf17e068f
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
yilei0620/RGBD-Slam-Semantic-Seg-DeepLab-master
MyVOCevalsegBoundary.m
.m
RGBD-Slam-Semantic-Seg-DeepLab-master/deeplab/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
yhyoscar/sklearn-study-master
karmarkar.m
.m
sklearn-study-master/20180407_LinearProgramming/karmarkar.m
474
utf_8
508c1aae69a7d8a67e07d0308acb3575
%% karmarkar's algorithm function x = karmarkar(A,b,c,x) N = size(c,1); x0 = x; y0 = ones(N,1); epi = 1e-3; alpha = 0.8; x_c = 2*ones(N,1); x_n = x0; r = zeros(N,1); Dx = diag(x_c); flag = 0; i = 1; while flag == 0 x_c = x_n; Dx = diag(x_c); r = c - A'*inv((A*Dx*Dx*A'))*A*Dx*Dx*c; p = -Dx*Dx*r; x_n = x_c + alpha*p/norm(Dx*r) ; if (r > 0)&(ones(1,N)*Dx*r <epi) flag =1; end i = i+1; x(:,i) = x_n; end end
github
alex-parisi/Phased-Vocoder-master
changePitchLength.m
.m
Phased-Vocoder-master/changePitchLength.m
2,028
utf_8
69a7ffac541318a8da2dca0c8b1e2031
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%% INPUT: %%%% %%%% sig - audioread(filename) %%%% %%%% Fs - Sample rate %%%% %%%% file - operations file %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%% OUTPUT: %%%% %%%% sig - new audio signal %%%% %%%% that has been %%%% %%%% stretched and shifted %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sig,fs] = changePitchLength(sig_file, op_file) [sig,fs]=audioread(sig_file); % Read operations file % blocks = xlsread(op_file); numBlocks = size(blocks, 1); % Sort in descending order by StartTime % sortedBlocks = sortrows(blocks, -1); % Process each block % for (i = 1:numBlocks) % Split signal % startN = ceil(sortedBlocks(i, 1) * fs); endN = floor(sortedBlocks(i, 2) * fs); bef = []; aft = []; if (startN > 1) bef = sig(1:startN - 1); end if (endN < length(sig)) aft = sig((endN - 1):end); end dur = sortedBlocks(i, 3); pitch = sortedBlocks(i, 4); segment = sig(startN:endN); % Process this block % segment = PhaseVocoder(segment, fs, dur, pitch); segment = audioread('finaloutput.wav'); % Reassemble signal % sig = [bef ; segment ; aft]; end % Clean up % delete 'output.wav' 'temp.wav' 'finaloutput.wav' end
github
alex-parisi/Phased-Vocoder-master
PhaseVocoder.m
.m
Phased-Vocoder-master/PhaseVocoder.m
7,160
utf_8
f0d64ec15bf41366a1148c2b9934ee37
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%% INPUT: %%%% %%%% origSpeech - audioread(filename) %%%% %%%% Fs - Sample rate %%%% %%%% newDuration - new length of %%%% %%%% speech %%%% %%%% newPitch - new pitch of speech %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% %%%% OUTPUT: %%%% %%%% procSpeech - new audio signal %%%% %%%% that has been %%%% %%%% stretched and shifted %%%% %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function procSpeech = PhaseVocoder(origSpeechSig, Fs, newDuration, newPitch) % Initialize % WindowLen = 256; % First process for pitch-shifting % % Determine original pitch % [maxValue, indexMax] = max(10 * log10(pwelch(origSpeechSig))); origFreq = indexMax * Fs / length(origSpeechSig); origPitch = 3233 * log10(1 + origFreq / 1000) % Determine pitch-shifting ratio % pitchRatio = newPitch / origPitch; % Set analysis and synthesis hop size SynthesisLen = 50; AnalysisLen = ceil(SynthesisLen / pitchRatio); Hopratio = pitchRatio; % Write temporary .wav file % audiowrite('temp.wav', origSpeechSig, Fs); % Create system objects used in processing % reader = dsp.AudioFileReader('temp.wav', 'SamplesPerFrame', AnalysisLen, 'OutputDataType', 'double'); buff = dsp.Buffer(WindowLen, WindowLen - AnalysisLen); %Buffer win = dsp.Window('Hanning', 'Sampling', 'Periodic'); %Window dft = dsp.FFT; %FFT idft = dsp.IFFT('ConjugateSymmetricInput', true, 'Normalize', false); %IDFT player = audioDeviceWriter('SampleRate', Fs, 'SupportVariableSizeInput', true, 'BufferSize', 512); %Player logger = dsp.SignalSink; %Logger % Initialize Processing % yprevwin = zeros(WindowLen - SynthesisLen, 1); gain = 1 / (WindowLen * sum(hanning(WindowLen, 'periodic') .^ 2) / SynthesisLen); unwrapdata = 2 * pi * AnalysisLen * (0:WindowLen - 1)' / WindowLen; yangle = zeros(WindowLen, 1); firsttime = true; % Begin processing for pitch-shifting % while ~isDone(reader) y = reader(); % Take windowed, buffered FFT of signal % yfft = dft(win(buff(y))); % Convert FFT data to magnitude and phase % ymag = abs(yfft); yprevangle = yangle; yangle = angle(yfft); % Synthesis-Phase Calculation % yunwrap = (yangle - yprevangle) - unwrapdata; yunwrap = yunwrap - round(yunwrap / (2 * pi)) * 2 * pi; yunwrap = (yunwrap + unwrapdata) * Hopratio; if (firsttime) ysangle = yangle; firsttime = false; else ysangle = ysangle + yunwrap; end % Convert magnitude and phase to complex numbers % ys = ymag .* complex(cos(ysangle), sin(ysangle)); % Windowed IFFT % ywin = win(idft(ys)); % Overlap-add operation % olapadd = [ywin(1:end-SynthesisLen,:) + yprevwin ; ywin(end-SynthesisLen+1:end,:)]; yistfft = olapadd(1:SynthesisLen, :); yprevwin = olapadd(SynthesisLen + 1:end, :); % Normalize % yistfft = yistfft * gain; % Log signal % logger(yistfft); end % Define pitch-shifted speech % pitchShiftedSpeech = logger.Buffer(200:end)'; Fs = round(Fs * Hopratio); audiowrite('output.wav', pitchShiftedSpeech.', Fs); release(reader); % Second process for time-scaling % % Determine original duration % origDuration = length(pitchShiftedSpeech) / Fs; % Determine time-scaling ratio % timeRatio = newDuration / origDuration; % Set analysis and synthesis hop size SynthesisLen = 50; AnalysisLen = ceil(SynthesisLen / timeRatio); Hopratio = timeRatio; % Create system objects used in processing % reader = dsp.AudioFileReader('output.wav', 'SamplesPerFrame', AnalysisLen, 'OutputDataType', 'double'); buff = dsp.Buffer(WindowLen, WindowLen - AnalysisLen); %Buffer win = dsp.Window('Hanning', 'Sampling', 'Periodic'); %Window dft = dsp.FFT; %FFT idft = dsp.IFFT('ConjugateSymmetricInput', true, 'Normalize', false); %IDFT player = audioDeviceWriter('SampleRate', Fs, 'SupportVariableSizeInput', true, 'BufferSize', 512); %Player logger = dsp.SignalSink; %Logger % Initialize Processing % yprevwin = zeros(WindowLen - SynthesisLen, 1); gain = 1 / (WindowLen * sum(hanning(WindowLen, 'periodic') .^ 2) / SynthesisLen); unwrapdata = 2 * pi * AnalysisLen * (0:WindowLen - 1)' / WindowLen; yangle = zeros(WindowLen, 1); firsttime = true; % Begin processing for time-scaling % while ~isDone(reader) y = reader(); % Take windowed, buffered FFT of signal % yfft = dft(win(buff(y))); % Convert FFT data to magnitude and phase % ymag = abs(yfft); yprevangle = yangle; yangle = angle(yfft); % Synthesis-Phase Calculation % yunwrap = (yangle - yprevangle) - unwrapdata; yunwrap = yunwrap - round(yunwrap / (2 * pi)) * 2 * pi; yunwrap = (yunwrap + unwrapdata) * Hopratio; if (firsttime) ysangle = yangle; firsttime = false; else ysangle = ysangle + yunwrap; end % Convert magnitude and phase to complex numbers % ys = ymag .* complex(cos(ysangle), sin(ysangle)); % Windowed IFFT % ywin = win(idft(ys)); % Overlap-add operation % olapadd = [ywin(1:end-SynthesisLen,:) + yprevwin ; ywin(end-SynthesisLen+1:end,:)]; yistfft = olapadd(1:SynthesisLen, :); yprevwin = olapadd(SynthesisLen + 1:end, :); % Normalize % yistfft = yistfft * gain; % Log signal % logger(yistfft); end % Define final processed signal % release(reader); procSpeech = logger.Buffer(200:end)'; procSpeech = resample(procSpeech, 8000, Fs); audiowrite('finaloutput.wav', procSpeech, 8000); end
github
brightnesss/RGB-D-Tracking-master
run_tracker.m
.m
RGB-D-Tracking-master/run_tracker.m
9,067
utf_8
ccd2b4a290e4a753d839215267a71a06
% % High-Speed Tracking with Kernelized Correlation Filters % % Joao F. Henriques, 2014 % http://www.isr.uc.pt/~henriques/ % % Main interface for Kernelized/Dual Correlation Filters (KCF/DCF). % This function takes care of setting up parameters, loading video % information and computing precisions. For the actual tracking code, % check out the TRACKER function. % % RUN_TRACKER % Without any parameters, will ask you to choose a video, track using % the Gaussian KCF on HOG, and show the results in an interactive % figure. Press 'Esc' to stop the tracker early. You can navigate the % video using the scrollbar at the bottom. % % RUN_TRACKER VIDEO % Allows you to select a VIDEO by its name. 'all' will run all videos % and show average statistics. 'choose' will select one interactively. % % RUN_TRACKER VIDEO KERNEL % Choose a KERNEL. 'gaussian'/'polynomial' to run KCF, 'linear' for DCF. % % RUN_TRACKER VIDEO KERNEL FEATURE % Choose a FEATURE type, either 'hog' or 'gray' (raw pixels). % % RUN_TRACKER(VIDEO, KERNEL, FEATURE, SHOW_VISUALIZATION, SHOW_PLOTS) % Decide whether to show the scrollable figure, and the precision plot. % % Useful combinations: % >> run_tracker choose gaussian hog %Kernelized Correlation Filter (KCF) % >> run_tracker choose linear hog %Dual Correlation Filter (DCF) % >> run_tracker choose gaussian gray %Single-channel KCF (ECCV'12 paper) % >> run_tracker choose linear gray %MOSSE filter (single channel) % % % revised by: Yang Li, August, 2014 % http://ihpdep.github.io function [precision, track_result ,fps, successes, success_auc] = run_tracker(video, kernel_type, feature_type, show_visualization, show_plots) %path to the videos (you'll be able to choose one with the GUI). base_path ='.\data\'; %default settings if nargin < 1, video = 'choose'; end if nargin < 2, kernel_type = 'gaussian'; end if nargin < 3, feature_type = 'hogcolor'; end if nargin < 4, show_visualization = ~strcmp(video, 'all'); end if nargin < 5, show_plots = ~strcmp(video, 'all'); end %parameters according to the paper. at this point we can override %parameters based on the chosen kernel or feature type kernel.type = kernel_type; features.gray = false; features.hog = false; features.hogcolor = false; padding = 1.5; %extra area surrounding the target lambda = 1e-4; %regularization output_sigma_factor = 0.1; %spatial bandwidth (proportional to target) switch feature_type case 'gray' interp_factor = 0.075; %linear interpolation factor for adaptation kernel.sigma = 0.2; %gaussian kernel bandwidth kernel.poly_a = 1; %polynomial kernel additive term kernel.poly_b = 7; %polynomial kernel exponent features.gray = true; cell_size = 1; case 'hog' interp_factor = 0.02; kernel.sigma = 0.5; kernel.poly_a = 1; kernel.poly_b = 9; features.hog = true; features.hog_orientations = 9; cell_size = 4; case 'hogcolor' interp_factor = 0.01; kernel.sigma = 0.5; kernel.poly_a = 1; kernel.poly_b = 9; features.hogcolor = true; features.hog_orientations = 9; cell_size = 4; otherwise error('Unknown feature.') end assert(any(strcmp(kernel_type, {'linear', 'polynomial', 'gaussian'})), 'Unknown kernel.') switch video case 'choose' %ask the user for the video, then call self with that video name. validation_set = [base_path,'ValidationSet']; video = choose_video(validation_set); if ~isempty(video) [precision, track_result, fps, successes, success_auc ] = run_tracker(video, kernel_type, ... feature_type, show_visualization, show_plots); if nargout == 0 %don't output precision as an argument clear precision end end case 'all' %all videos, call self with each video name. %only keep valid directory names % validation_set = [base_path, 'ValidationSet']; evaluation_set = [base_path, 'EvaluationSet']; % dirs = dir(validation_set); % validation_videos = {dirs.name}; % validation_videos(strcmp('.', validation_videos) | strcmp('..', validation_videos) | ... % strcmp('anno', validation_videos) | ~[dirs.isdir]) = []; % validation_videos = strcat('ValidationSet\',validation_videos); dirs = dir(evaluation_set); evaluation_videos = {dirs.name}; evaluation_videos(strcmp('.', evaluation_videos) | strcmp('..', evaluation_videos) | ... strcmp('anno', evaluation_videos) | ~[dirs.isdir]) = []; evaluation_videos = strcat('EvaluationSet\', evaluation_videos); % videos = [validation_videos,evaluation_videos]; videos = evaluation_videos; % all_precisions = zeros(numel(videos),1); %to compute averages all_fps = zeros(numel(videos),1); for k = 1:numel(videos) fprintf(['video %d: ', videos{k}, ' is going to run\n'], k); [~, ~, all_fps(k)] = run_tracker(videos{k}, ... kernel_type, feature_type, false, false); end % if ~exist('parpool', 'file') % %no parallel toolbox, use a simple 'for' to iterate % for k = 1:numel(videos) % fprintf(['video %d: ', videos{k}, ' is going to run\n'], k); % [all_precisions(k), all_fps(k)] = run_tracker(videos{k}, ... % kernel_type, feature_type, show_visualization, show_plots); % end % else % %evaluate trackers for all videos in parallel % % p = gcp('nocreate'); % if isempty(p) % parpool('local'); % end % % parfor k = 1:numel(videos) % fprintf(['video %d: ', videos{k}, ' is going to run\n'], k); % [all_precisions(k), all_fps(k)] = run_tracker(videos{k}, ... % kernel_type, feature_type, show_visualization, show_plots); % end % end %compute average precision at 20px, and FPS % mean_precision = mean(all_precisions); fps = mean(all_fps); precision = []; track_result = []; % fprintf('\nAverage precision (20px):% 1.3f, Average FPS:% 4.2f\n\n', mean_precision, fps) % if nargout > 0 % precision = mean_precision; % end case 'benchmark' %running in benchmark mode - this is meant to interface easily %with the benchmark's code. %get information (image file names, initial position, etc) from %the benchmark's workspace variables seq = evalin('base', 'subS'); target_sz = seq.init_rect(1,[4,3]); pos = seq.init_rect(1,[2,1]) + floor(target_sz/2); img_files = seq.s_frames; video_path = []; %call tracker function with all the relevant parameters [positions,rect_results,t]= tracker(video_path, img_files, pos, target_sz, ... padding, kernel, lambda, output_sigma_factor, interp_factor, ... cell_size, features, 0); %return results to benchmark, in a workspace variable rects =rect_results; % [positions(:,2) - target_sz(2)/2, positions(:,1) - target_sz(1)/2]; % rects(:,3) = target_sz(2); % rects(:,4) = target_sz(1); res.type = 'rect'; res.res = rects; assignin('base', 'res', res); otherwise %we were given the name of a single video to process. %get image file names, initial state, and ground truth for evaluation [rgbdimgs, pos, target_sz, ground_truth_position, ground_truth, video_path] = load_video_info(base_path, video); % %call tracker function with all the relevant parameters [positions,track_result, time, occ_results] = tracker(video_path, rgbdimgs, pos, target_sz, ... padding, kernel, lambda, output_sigma_factor, interp_factor, ... cell_size, features, show_visualization); %call tracker function with all the relevant parameters % [positions,track_result, time, occ_results] = rgbtracker(video_path, rgbdimgs, pos, target_sz, ... % padding, kernel, lambda, output_sigma_factor, interp_factor, ... % cell_size, features, show_visualization); % [positions,track_result, time] = samf_tracker(video_path, rgbdimgs, pos, target_sz, ... % padding, kernel, lambda, output_sigma_factor, interp_factor, ... % cell_size, features, show_visualization); %calculate and show precision plot, as well as frames-per-second fps = numel(rgbdimgs.rgb) / time; if show_plots precisions = precision_plot(positions, ground_truth_position, video, 0); % fprintf('%12s - Precision (20px):% 1.3f, FPS:% 4.2f\n', video, precisions(20), fps) [success,auc] = success_plot(track_result, ground_truth, video, 0); if nargout > 0 %return precisions at a 20 pixels threshold precision = precisions; successes = success; success_auc = auc; end else precision = []; successes = []; success_auc = []; end % result_path = [base_path, 'Result\', video, '.txt']; % % write_result(result_path, track_result, occ_results); end end
github
HEVC-Projects/CPH-master
extractCUDepthGrndTruthCPHInter.m
.m
CPH-master/extractCUDepthGrndTruthCPHInter.m
13,369
utf_8
d84d00f57e79881007284e2b04fa0d55
function extractCUDepthGrndTruthCPHInter % This program transfers raw video and label files to samples for % training, validation and test, establishing a large-scale database % for CU partition of inter-mode HEVC (CPH-Inter). % The database contains 111 videos in total. % For each video, there are 9 corresponding input files: % 1 YUV file and 8 DAT files. % The YUV file (in 420 format) stores original pixel-wise information of the video. % The DAT files store labels and other necessary information, arranged by QPs (22, 27, 32 and 37). % The files ending with "_CUDepth.dat" are binary data representing CU depth, % and the files ending with "" are text messages listing out the % information of all frames in the YUV file. % Each line in "_Index.dat" file indicates % some basic information of each frame, including POC, frame width, % frame height and QP for the current frame. In the 1st frame (POC 0), YUV file name are % also included. Corresponding to each line in "_Index.dat", are a % certain number of bytes organized in the file "_CUDepth.dat". Considering % that in HEVC frames, the CU depth (0, 1, 2 or 3) in a 16*16 unit is % the same, so for a W*H frame, there are floor(H/16) rows and % floor(W/16) columns, and the number of bytes needed is % floor(W/16)*floor(H/16). % Note that all bytes for a frame are stored in row-major order. % Below is an example of "_CUDepth.dat" and "_Index.dat". % In "Info_20170424_033631_LDP_BasketballDrive_1920x1080_50_qp32_nf500_Index.dat", % the 1st line is: % 0 1920 1080 32 BasketballDrive_1920x1080_50.yuv. % It is the 1st frame (POC=0) in "IBasketballDrive_1920x1080_50.yuv", and QP = 32. % There are 67 rows and 120 columns, corresponding to 67*120 = 8040 bytes % in "Info_20170424_033631_LDP_BasketballDrive_1920x1080_50_qp32_nf500_CUDepth.dat", % organized as follows. % [CU depth in Row 1 Column 1] % [CU depth in Row 1 Column 2] % . % . % . % [CU depth in Row 1 Column 120] % [CU depth in Row 2 Column 1] % [CU depth in Row 2 Column 2] % . % . % . % [CU depth in Row 2 Column 120] % . % . % . % . % . % . % [CU depth in Row 67 Column 1] % [CU depth in Row 67 Column 2] % . % . % . % [CU depth in Row 67 Column 120] % After executing this program, for each video at each QP, 3 sample files ended with "_CUXXSamples.dat" % will be generated, arranged by CU size and QP. In each % file, all samples are continuously stored. Each sample takes up % (1 + CUWidth * CUWidth) bytes, where the initial byte is the label % representing whether the CU is split and the rest CUWidth * CUWidth % bytes are the luminance information of the CU in row-major order. All % the labels and luminance data are 8-bit unsigned type. % Below is an example of "_CUXXSamples.dat". % There are totally 240,000 samples for 64*64 CUs in the video "BasketballDrive_1920x1080_50.yuv". % So the file "BasketballDrive_1920x1080_50_qp32_CU64Samples.dat" % is orgarized as follows. % [label of the 1st CU (1 byte)] % [luminance infomation of the lst CU (64*64 bytes)] % [label of the 2nd CU (1 byte)] % [luminance infomation of the 2nd CU (64*64 bytes)] % . % . % . % [label of the 240,000-th CU (1 byte)] % [luminance infomation of the 240,000-th CU (64*64 bytes)] % Therefore, the file size is (1+64*64)*240,000 = 983,280,000 bytes. filePathInput='G:\YUV_All\'; % where all input YUV files and DAT files exist filePathExtract='F:\YUV_All_Extract\'; % where to store the extracted samples % Uncomment some video name(s) in the variable "yuvNameList". yuvNameList={... 'BasketballPass_416x240_50' 'BlowingBubbles_416x240_50' 'BQSquare_416x240_60' 'RaceHorses_416x240_30' 'BasketballDrill_832x480_50' 'BQMall_832x480_60' 'PartyScene_832x480_50' 'RaceHorses_832x480_30' 'FourPeople_1280x720_60' 'Johnny_1280x720_60' 'KristenAndSara_1280x720_60' 'BasketballDrive_1920x1080_50' 'BQTerrace_1920x1080_60' 'Cactus_1920x1080_50' 'Kimono_1920x1080_24' 'ParkScene_1920x1080_24' 'PeopleOnStreet_2560x1600_30_crop' 'Traffic_2560x1600_30_crop' % 'garden_sif' % 'stefan_sif' % 'tennis_sif' % 'tt_sif' % 'akiyo_cif' % 'bowing_cif' % 'bridge_close_cif' % 'bridge_far_cif' % 'bus_cif' % 'coastguard_cif' % 'container_cif' % 'deadline_cif' % 'flower_cif' % 'football_cif' % 'foreman_cif' % 'hall_monitor_cif' % 'highway_cif' % 'husky_cif' % 'mad900_cif' % 'mobile_cif' % 'mother_daughter_cif' % 'news_cif' % 'pamphlet_cif' % 'paris_cif' % 'sign_irene_cif' % 'silent_cif' % 'students_cif' % 'tempete_cif' % 'waterfall_cif' % 'flower_garden_720x480' % 'football_720x480' % 'galleon_720x480' % 'intros_720x480' % 'mobile_calendar_720x480' % 'vtc1nw_720x480' % 'washdc_720x480' % 'city_4cif' % 'crew_4cif' % 'harbour_4cif' % 'ice_4cif' % 'soccer_4cif' % 'mobcal_ter_720p50' % 'parkrun_ter_720p50' % 'shields_ter_720p50' % 'stockholm_ter_720p5994' % 'aspen_1080p' % 'blue_sky_1080p25' % 'controlled_burn_1080p' % 'crowd_run_1080p50' % 'dinner_1080p30' % 'ducks_take_off_1080p50' % 'factory_1080p30' % 'in_to_tree_1080p50' % 'life_1080p30' % 'old_town_cross_1080p50' % 'park_joy_1080p50' % 'pedestrian_area_1080p25' % 'red_kayak_1080p' % 'riverbed_1080p25' % 'rush_field_cuts_1080p' % 'rush_hour_1080p25' % 'sintel_trailer_2k_1080p24' % 'snow_mnt_1080p' % 'speed_bag_1080p' % 'station2_1080p25' % 'sunflower_1080p25' % 'touchdown_pass_1080p' % 'tractor_1080p25' % 'west_wind_easy_1080p' % 'Netflix_Aerial_2048x1080_60fps_420' % 'Netflix_BarScene_2048x1080_60fps_420' % 'Netflix_Boat_2048x1080_60fps_420' % 'Netflix_BoxingPractice_2048x1080_60fps_420' % 'Netflix_Crosswalk_2048x1080_60fps_420' % 'Netflix_Dancers_2048x1080_60fps_420' % 'Netflix_DinnerScene_2048x1080_60fps_420' % 'Netflix_DrivingPOV_2048x1080_60fps_420' % 'Netflix_FoodMarket_2048x1080_60fps_420' % 'Netflix_Narrator_2048x1080_60fps_420' % 'Netflix_PierSeaside_2048x1080_60fps_420' % 'Netflix_RitualDance_2048x1080_60fps_420' % 'Netflix_RollerCoaster_2048x1080_60fps_420' % 'Netflix_SquareAndTimelapse_2048x1080_60fps_420' % 'Netflix_Tango_2048x1080_60fps_420' % 'Netflix_ToddlerFountain_2048x1080_60fps_420' % 'Netflix_TunnelFlag_2048x1080_60fps_420' % 'Netflix_WindAndNature_2048x1080_60fps_420' % 'female150' % 'male150' % 'onedarkfinal' % 'simo' % 'training' % 'x2' }; QPList=[22 27 32 37]; for iSeq=1:length(yuvNameList) for iQP=1:length(QPList) extractCUDepthGrndTruth(iSeq,yuvNameList{iSeq},QPList(iQP),filePathInput,filePathExtract); end end end function filePathAndName=getFilePathAndName(filePath,keyWords1,keyWords2) dirOutput=dir([filePath '*' keyWords1 '*' keyWords2 '*']); [filePath '*' keyWords1 '*' keyWords2 '*'] fileNameList={dirOutput.name}'; assert(length(fileNameList)==1); filePathAndName=[filePath fileNameList{1}]; end function nSamplesMatrix=extractCUDepthGrndTruth(... iSeq,yuvName,QP,... filePathInput,... filePathExtract... ) fileNameCUDepthIndex=getFilePathAndName(filePathInput,['_' yuvName '_qp' num2str(QP)],'_Index.dat'); fileNameCUDepth=getFilePathAndName(filePathInput,['_' yuvName '_qp' num2str(QP)],'_CUDepth.dat'); fileNameExtract64=[filePathExtract yuvName '_qp' num2str(QP) '_CU64Samples.dat']; fileNameExtract32=[filePathExtract yuvName '_qp' num2str(QP) '_CU32Samples.dat']; fileNameExtract16=[filePathExtract yuvName '_qp' num2str(QP) '_CU16Samples.dat']; fidCUDepthIndex=fopen(fileNameCUDepthIndex); fidCUDepth=fopen(fileNameCUDepth); fidExtract64=fopen(fileNameExtract64,'w+'); fidExtract32=fopen(fileNameExtract32,'w+'); fidExtract16=fopen(fileNameExtract16,'w+'); nSamplesMatrix=zeros(3,2); %[[n64split n64nonsplit] % [n32split n32nonsplit] % [n16split n16nonsplit]] while ~feof(fidCUDepthIndex) tline=fgetl(fidCUDepthIndex); nList=sscanf(tline,'%d %d %d'); nFrame=nList(1); if nFrame==0 nListTemp=sscanf(tline,'%d %d %d %d %s'); end width=nList(2); height=nList(3); widthIn16=fix(width/16); heightIn16=fix(height/16); infoTemp=fread(fidCUDepth,widthIn16*heightIn16,'uint8'); infoTemp=reshape(infoTemp,widthIn16,heightIn16)'; info(:,:,nFrame+1)=infoTemp; end infoYInCTU=zeros(64,64); nTotal=0; fileNameYUV=[filePathInput yuvName '.yuv'] fidYUV=fopen(fileNameYUV); for iFrame=0:size(info,3)-1 disp(['Sequence ' num2str(iSeq) ', QP ' num2str(QP) ' : Frame ' num2str(iFrame+1) ' / ' num2str(size(info,3))]); Y=fread(fidYUV,width*height,'uint8'); UV=fread(fidYUV,width*height/2,'uint8'); matrixY=reshape(Y,width,height)'; widthInCTU=floor(size(info,2)/4); heightInCTU=floor(size(info,1)/4); for y=1:heightInCTU for x=1:widthInCTU nTotal=nTotal+1; infoYInCTU(:,:)=matrixY((y-1)*64+1:y*64,(x-1)*64+1:x*64); infoCUDepthInCTU=info((y-1)*4+1:y*4,(x-1)*4+1:x*4,iFrame+1); if mean(mean(infoCUDepthInCTU))>0 label64=1; nSamplesMatrix(1,1)=nSamplesMatrix(1,1)+1; else label64=0; nSamplesMatrix(1,2)=nSamplesMatrix(1,2)+1; end fwrite(fidExtract64,label64,'uint8'); fwrite(fidExtract64,reshape(infoYInCTU(:,:)',1,64*64),'uint8'); end end widthIn32=widthInCTU*2; heightIn32=heightInCTU*2; for y=1:heightIn32 for x=1:widthIn32 isValid32=0; infoYIn32x32(:,:)=matrixY((y-1)*32+1:y*32,(x-1)*32+1:x*32); infoCUDepthIn32x32=info((y-1)*2+1:y*2,(x-1)*2+1:x*2,iFrame+1); if infoCUDepthIn32x32(1,1)>=2 isValid32=1; label32=1; nSamplesMatrix(2,1)=nSamplesMatrix(2,1)+1; elseif infoCUDepthIn32x32(1,1)==1 isValid32=1; label32=0; nSamplesMatrix(2,2)=nSamplesMatrix(2,2)+1; end if isValid32>0 fwrite(fidExtract32,label32,'uint8'); fwrite(fidExtract32,reshape(infoYIn32x32(:,:)',1,32*32),'uint8'); end end end widthIn16=widthInCTU*4; heightIn16=heightInCTU*4; for y=1:heightIn16 for x=1:widthIn16 isValid16=0; infoYIn16x16(:,:)=matrixY((y-1)*16+1:y*16,(x-1)*16+1:x*16); infoCUDepthIn16x16=info(y,x,iFrame+1); if infoCUDepthIn16x16(1,1)==3 isValid16=1; label16=1; nSamplesMatrix(3,1)=nSamplesMatrix(3,1)+1; elseif infoCUDepthIn16x16(1,1)==2 isValid16=1; label16=0; nSamplesMatrix(3,2)=nSamplesMatrix(3,2)+1; end if isValid16>0 fwrite(fidExtract16,label16,'uint8'); fwrite(fidExtract16,reshape(infoYIn16x16(:,:)',1,16*16),'uint8'); end end end % Uncomment these lines to show CU depth matrix (optional). % infoShown=imresize(info(:,:,iFrame+1),5,'nearest'); % imshow(infoShown,[0 3]); % title(['POC ' num2str(iFrame)]); % pause; end fclose(fidYUV); if iSeq==1 fidLogStat=fopen('LogStat.txt','w+'); else fidLogStat=fopen('LogStat.txt','a+'); end fprintf(fidLogStat,'Sequence %d, QP %d:\r\n',iSeq,QP); fprintf(fidLogStat,'%10d%10d\r\n%10d%10d\r\n%10d%10d\r\n\r\n',... nSamplesMatrix(1,1),nSamplesMatrix(1,2),... nSamplesMatrix(2,1),nSamplesMatrix(2,2),... nSamplesMatrix(3,1),nSamplesMatrix(3,2)); fclose('all'); end
github
HEVC-Projects/CPH-master
extractCUDepthGrndTruthCPHIntra.m
.m
CPH-master/extractCUDepthGrndTruthCPHIntra.m
10,768
utf_8
1dad2cb9720a3eb99ec39590d41811b7
function extractCUDepthGrndTruthCPHIntra % This program transfers raw image and label files to samples that are directly available for deep CNNs, % in order to establish a large-scale database for CU partition of % intra-mode HEVC (CPH-Intra). % All images are stored in 12 YUV files, arranged by resolutions and % usages (training, validation and test). % All labels and other necessary information are stored in 8 DAT files, % arranged by QPs (22, 27, 32 and 37). The files begining with % "CUDepth_" are binary data representing CU depth, and the ones % begining with "CUDepthIndex_" are text messages listing out the % information of all frames in YUV files. % Each line in "CUDepthIndex_" file indicates % some basic information of each frame, including POC, frame width and % frame height, and in the 1st frame (POC 0), QP and YUV file name are % also included. Corresponding to each line in "CUDepthIndex_", are a % certain number of bytes organized in the file "CUDepth_". Considering % that in HEVC frames, the CU depth (0, 1, 2 or 3) in a 16*16 unit is % the same, so for a W*H frame, there are floor(H/16) rows and % floor(W/16) columns, and the number of bytes needed is % floor(W/16)*floor(H/16). % Note that all bytes for a frame are stored in row-major order. % Below is an example of "CUDepth_" and "CUDepthIndex_". % In "CUDepthIndex_AI_CPIH_768_1536_2880_4928_qp32_nf425_25_50.dat", % the 1st line is: % 0 768 512 32 IntraTrain_768x512.yuv. % It is the 1st frame (POC=0) in "IntraTrain_768x512.yuv", and QP = 32. % There are 32 rows and 48 columns, corresponding to 32*48 = 1536 bytes % in "CUDepth_AI_CPIH_768_1536_2880_4928_qp32_nf425_25_50.dat", % organized as follows. % [CU depth in Row 1 Column 1] % [CU depth in Row 1 Column 2] % . % . % . % [CU depth in Row 1 Column 48] % [CU depth in Row 2 Column 1] % [CU depth in Row 2 Column 2] % . % . % . % [CU depth in Row 2 Column 48] % . % . % . % . % . % . % [CU depth in Row 32 Column 1] % [CU depth in Row 32 Column 2] % . % . % . % [CU depth in Row 32 Column 48] % After executing this program, 36 sample files named "CUXXSamples_" % will be generated, arranged by CU sizes, QPs and usages. In each % file, all samples are continuously stored. Each sample takes up % (1 + CUWidth * CUWidth) bytes, where the initial byte is the label % representing whether the CU is split and the rest CUWidth * CUWidth % bytes are the luminance information of the CU in row-major order. All % the labels and luminance data are 8-bit unsigned type. % Below is an example of "CUXXSamples_". % There are totally 2446725 samples for 64*64 CUs in the training set. % So the file "CU64Samples_AI_CPIH_768_1536_2880_4928_qp22_Train.dat" % is orgarized as follows. % [label of the 1st CU (1 byte)] % [luminance infomation of the lst CU (64*64 bytes)] % [label of the 2nd CU (1 byte)] % [luminance infomation of the 2nd CU (64*64 bytes)] % . % . % . % [label of the 2446725th CU (1 byte)] % [luminance infomation of the 2446725th CU (64*64 bytes)] % Therefore, the file size is (1+64*64)*2446725 = 10024232325 bytes. filePathInput=''; filePathExtract=''; QPList=[22 27 32 37]; for i=1:length(QPList) extractCUDepthGrndTruth(... filePathInput,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_nf425_25_50'],... filePathExtract,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_Train'],... [1 4 7 10]); extractCUDepthGrndTruth(... filePathInput,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_nf425_25_50'],... filePathExtract,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_Valid'],... [2 5 8 11]); extractCUDepthGrndTruth(... filePathInput,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_nf425_25_50'],... filePathExtract,['_AI_CPIH_768_1536_2880_4928_qp' num2str(QPList(i)) '_Test'],... [3 6 9 12]); end end function nSamplesMatrix=extractCUDepthGrndTruth(... filePathInput,fileSuffixInput,... filePathExtract,fileSuffixExtract,... seqValidIndex) fileNameCUDepthIndex=[filePathInput 'CUDepthIndex' fileSuffixInput '.dat']; fileNameCUDepth=[filePathInput 'CUDepth' fileSuffixInput '.dat']; fileNameExtract64=[filePathExtract 'CU64Samples' fileSuffixExtract '.dat']; fileNameExtract32=[filePathExtract 'CU32Samples' fileSuffixExtract '.dat']; fileNameExtract16=[filePathExtract 'CU16Samples' fileSuffixExtract '.dat']; fidCUDepthIndex=fopen(fileNameCUDepthIndex); fidCUDepth=fopen(fileNameCUDepth); fidExtract64=fopen(fileNameExtract64,'w+'); fidExtract32=fopen(fileNameExtract32,'w+'); fidExtract16=fopen(fileNameExtract16,'w+'); nSamplesMatrix=zeros(3,2); %[[n64split n64nonsplit] % [n32split n32nonsplit] % [n16split n16nonsplit]] nSeq=0; nSeqTemp=0; info=[]; widthIn16=[]; heightIn16=[]; width=[]; qp=[]; isValidSeq=0; while ~feof(fidCUDepthIndex) tline=fgetl(fidCUDepthIndex); nList=sscanf(tline,'%d %d %d'); nFrame=nList(1); if nFrame==0 nSeq=nSeq+1; info{nSeq}=[]; nListTemp=sscanf(tline,'%d %d %d %d %s'); qp(nSeq)=nListTemp(4); yuvNameList{nSeq}=nListTemp(5:end)'; end width(nSeq)=nList(2); height(nSeq)=nList(3); widthIn16(nSeq)=fix(width(nSeq)/16); heightIn16(nSeq)=fix(height(nSeq)/16); infoTemp=fread(fidCUDepth,widthIn16(nSeq)*heightIn16(nSeq),'uint8'); infoTemp=reshape(infoTemp,widthIn16(nSeq),heightIn16(nSeq))'; info{nSeq}(:,:,nFrame+1)=infoTemp; end infoYInCTU=zeros(64,64); nTotal=0; for k=1:nSeq if ismember(k,seqValidIndex) fileNameYUV=[filePathInput yuvNameList{k}] fidYUV=fopen(fileNameYUV); for iFrame=0:size(info{k},3)-1 disp(['Sequence ' num2str(k) ' : Frame ' num2str(iFrame+1) ' / ' num2str(size(info{k},3))]); Y=fread(fidYUV,width(k)*height(k),'uint8'); UV=fread(fidYUV,width(k)*height(k)/2,'uint8'); matrixY=reshape(Y,width(k),height(k))'; widthInCTU=floor(size(info{k},2)/4); heightInCTU=floor(size(info{k},1)/4); for y=1:heightInCTU for x=1:widthInCTU nTotal=nTotal+1; infoYInCTU(:,:)=matrixY((y-1)*64+1:y*64,(x-1)*64+1:x*64); infoCUDepthInCTU=info{k}((y-1)*4+1:y*4,(x-1)*4+1:x*4,iFrame+1); if mean(mean(infoCUDepthInCTU))>0 label64=1; nSamplesMatrix(1,1)=nSamplesMatrix(1,1)+1; else label64=0; nSamplesMatrix(1,2)=nSamplesMatrix(1,2)+1; end fwrite(fidExtract64,label64,'uint8'); fwrite(fidExtract64,reshape(infoYInCTU(:,:)',1,64*64),'uint8'); end end widthIn32=floor(size(info{k},2)/2); heightIn32=floor(size(info{k},1)/2); for y=1:heightIn32 for x=1:widthIn32 isValid32=0; infoYIn32x32(:,:)=matrixY((y-1)*32+1:y*32,(x-1)*32+1:x*32); infoCUDepthIn32x32=info{k}((y-1)*2+1:y*2,(x-1)*2+1:x*2,iFrame+1); if infoCUDepthIn32x32(1,1)>=2 isValid32=1; label32=1; nSamplesMatrix(2,1)=nSamplesMatrix(2,1)+1; elseif infoCUDepthIn32x32(1,1)==1 isValid32=1; label32=0; nSamplesMatrix(2,2)=nSamplesMatrix(2,2)+1; end if isValid32>0 fwrite(fidExtract32,label32,'uint8'); fwrite(fidExtract32,reshape(infoYIn32x32(:,:)',1,32*32),'uint8'); end end end widthIn16=size(info{k},2); heightIn16=size(info{k},1); for y=1:heightIn16 for x=1:widthIn16 isValid16=0; infoYIn16x16(:,:)=matrixY((y-1)*16+1:y*16,(x-1)*16+1:x*16); infoCUDepthIn16x16=info{k}(y,x,iFrame+1); if infoCUDepthIn16x16(1,1)==3 isValid16=1; label16=1; nSamplesMatrix(3,1)=nSamplesMatrix(3,1)+1; elseif infoCUDepthIn16x16(1,1)==2 isValid16=1; label16=0; nSamplesMatrix(3,2)=nSamplesMatrix(3,2)+1; end if isValid16>0 fwrite(fidExtract16,label16,'uint8'); fwrite(fidExtract16,reshape(infoYIn16x16(:,:)',1,16*16),'uint8'); end end end % Uncomment these lines to show CU depth matrix (optional) . % infoShown=imresize(info{k}(:,:,iFrame+1),5,'nearest'); % imshow(infoShown,[0 3]); % title(['POC ' num2str(iFrame)]); % pause; end fclose(fidYUV); disp(['Sequence ' num2str(k) ' Completed.']); end end disp([num2str(nTotal) ' CTUs Completed.']); nSamplesMatrix fidLogStat=fopen('LogStat.txt','a+'); fprintf(fidLogStat,'%10d%10d\r\n%10d%10d\r\n%10d%10d\r\n\r\n',... nSamplesMatrix(1,1),nSamplesMatrix(1,2),... nSamplesMatrix(2,1),nSamplesMatrix(2,2),... nSamplesMatrix(3,1),nSamplesMatrix(3,2)); fclose('all'); end
github
fangcaoxin/Myproject-master
generate_2d_points.m
.m
Myproject-master/SfM/generate_2d_points.m
1,495
utf_8
fcb889bbb13927636e96ccae3687121c
% drawmultiview(); function generate2D() %drawmultiview(); generate_2DPoints(); end function generate_2DPoints() addpath('cylindrical') load teapotMatrix1008.mat imagePointMatrix = zeros(size(teapotMatrix,1), 2, 10); for i = 1:10 imagePointMatrix(:,:,i) = point3d_t_2d(teapotMatrix(:,:,i)); % plot(imagePointMatrix(:,1,i), imagePointMatrix(:,2,i),'r.'); end save imagePointMatrix1008.mat imagePointMatrix load('teapot.mat'); teapot1 = teapot(1:10:end,:) + [0 0 600]; % Z>600 basePoint = point3d_t_2d(double(teapot1)); save basePoint1008.mat basePoint end function drawmultiview() load rotateMatrix1008.mat load TransMatrix.mat load('teapot.mat'); teapot1 = teapot(1:10:end,:) + [0 0 600]; % Z>600 teapotMatrix = zeros(size(teapot1, 1), 3, 10); for i = 1:10 loc = TransMatrix(i,:); ori = rotateMatrix(:,:,i)'; teapotMatrix(:,:,i) = (teapot1- loc)*ori'; color = i/10*[1 0 0]; plotCamera('Location',loc, 'Orientation', ori,'Size', 20,... 'label', int2str(i), 'color', color, 'AxesVisible', false); hold on end save teapotMatrix1008.mat teapotMatrix scatter3(teapot1(:,1), teapot1(:,2), teapot1(:,3), 5, 'MarkerFaceColor',[0 0 1],... 'MarkerEdgeColor',[0.3,0.5,0.9]); grid on axis equal xlabel('X[mm]'); ylabel('Y[mm]'); zlabel('Z[mm]'); end function generateR() addpath('helpers'); rotateMatrix = zeros(3,3,10); for i = 1: 10 rotateMatrix(:,:,i) = generateBoundedR(pi/180*10); end save ratateMatrix1008.mat rotateMatrix end
github
fangcaoxin/Myproject-master
refractivetriangulateMultiview.m
.m
Myproject-master/SfM/refractivetriangulateMultiview.m
1,296
utf_8
70d34e64fe663cdb4debd9dbfb94d25d
function [points3d, errors] = refractivetriangulateMultiview(bearingVec, ... camPoses, cameraParams) %outputType = validateInputs(pointTracks, camPoses, cameraParams); numTracks = numel(bearingVec); points3d = zeros(numTracks, 3); numCameras = size(camPoses, 1); cameraMatrices = containers.Map('KeyType', 'uint32', 'ValueType', 'any'); for i = 1:numCameras id = camPoses{i, 'ViewId'}; R = camPoses{i, 'Orientation'}{1}; t = camPoses{i, 'Location'}{1}; cameraMatrices(id) = cameraMatrix(cameraParams, R', -t*R'); end for i = 1:numTracks track = bearingVec(i); points3d(i, :) = triangulateOnePoint(track, cameraMatrices); end %points3d = cast(points3d, outputType); end function point3d = triangulateOnePoint(track, cameraMatrices) viewIds = track.ViewIds; %points = track.Points'; points = track.BearingVector(:,1:3)'; numViews = numel(viewIds); A = zeros(numViews * 2, 4); for i = 1:numViews % Check if the viewId exists if ~isKey(cameraMatrices, viewIds(i)) error(message('vision:absolutePoses:missingViewId', viewIds(i))); end P = cameraMatrices(viewIds(i))'; idx = 2 * i; A(idx-1:idx,:) = points(1:2, i) * P(3,:) -points(3,i)* P(1:2,:); end [~,~,V] = svd(A); X = V(:, end); X = X/X(end); point3d = X(1:3)'; end
github
fangcaoxin/Myproject-master
refractiveBA.m
.m
Myproject-master/SfM/refractiveBA.m
2,834
utf_8
b8ab627f87b89be67cecc5ca7615fedf
function [xyzPoints, camPoses] = refractiveBA(p, bearingVec, camPoses) % p is point 1xN , Rt estimated rotation and translation mat4x3xM % v calucated bearing vector p_one_row = reshape(p, 1, []); R_one_row = reshape(cell2mat(camPoses.Orientation), 1, []); t_one_row = reshape(cell2mat(camPoses.Location), 1, []); x0 = [p_one_row R_one_row t_one_row]; numPoints = numel(v); numViews = size(camPoses,1); % opts = optimset('Display', 'off'); opts = optimoptions(@lsqnonlin,'Algorithm','levenberg-marquardt','MaxFunEvals',3e4,'TolFun',1e-3); out = lsqnonlin(@(x)fun(x,bearingVec,numPoints, numViews), x0, [],[], opts); xyzPoints = reshape(out(1:3*numPoints),[numPoints, 3]); R_opm = reshape(out(3*numPoints+1:3*numPoints + 9*(numViews-1)),[3,3, numViews]); t_opm = reshape(out(3*numPoints + 9*(numViews-1)+1:end), [1 3 numViews]); for k = 1: numViews camPoses.Orientation(k) = R_opm(:,:,k); camPoses.Location(k)= t_opm(:,:,k); end function fval = fun(x, v, numPoints, numViews) points = reshape(x(1:3*numPoints), [],3); Rot = reshape(x(3*numPoints+1:3*numPoints+9*(numViews-1)), 3,3,[]); trans = reshape(x(3*numPoints+1+9*(numViews-1):end),1,3,[]); fval = 0; count = 1; for i = 1: numPoints for j = 1: size(v(i).ViewIds,2) view = v(i).ViewIds(j); xc = (points(i,:) -trans(:,:,view))*Rot(:,:,view); xs = v(i).BearingVector(j,1:3); ro = v(i).BearingVector(j,4:6); tmp = [0 1 1]; N1 = xs.* tmp; % normal between glass and water N1_norm = N1/norm(N1); ro_est = xc - xs; xw_normal = cross(ro, N1_norm, 2); fval(count) = dot(ro_est, xw_normal, 2); count = count + 1; end end % t = (ro(:,3).*xc(:,3) + ro(:,2).*xc(:,2) + sqrt((ro(:,3).*xc(:,3) + ro(:,2).*xc(:,2)).^2 -(ro(:,2).*ro(:,2)+ro(:,3).*... % ro(:,3)).*(xc(:,2).*xc(:,2)+ xc(:,3).*xc(:,3)-50*50)))./(ro(:,2).*ro(:,2)+ro(:,3).*ro(:,3)); % xs_est = xc - t.*ro; % ro_est = xc - xs; % %ro_proj = ro(:,1:2)./ro(:,3); % %ro_est_proj = ro_est(:, 1:2)./ro_est(:,3); % %fval(end+1: end+pointsNumOfEachView(i)) = ro_proj(:,1)- ro_est_proj(:,1); % %fval(end+1: end + pointsNumOfEachView(i))= ro_proj(:,2)- ro_est_proj(:,2); % % fval(end+1: end + pointsNumOfEachView(i))= xs_est(:,1)-xs(:,1); % % fval(end+1: end + pointsNumOfEachView(i))= xs_est(:,2)-xs(:,2); % % fval(end+1: end + pointsNumOfEachView(i))= xs_est(:,3)-xs(:,3); % xw_normal = cross(ro, N1_norm, 2); % fval(end+1: end+ pointsNumOfEachView(i)) = dot(ro_est, xw_normal, 2); % fval(end+1)= norm(Rot(1,:,i-1)) -1; % fval(end+1) = norm(Rot(2,:,i-1)) - 1; % fval(end+1) = dot(Rot(1,:,i-1),Rot(2,:,i-1)); % r3 = cross(Rot(1,:,i-1), Rot(2,:,i-1)); % fval(end+1) = r3(1) - Rot(3,1,i-1); % fval(end+1) = r3(2) - Rot(3,2,i-1); % fval(end+1) = r3(3) - Rot(3,3,i-1); end end
github
fangcaoxin/Myproject-master
sfm_one_view.m
.m
Myproject-master/SfM/cube_near_1010/sfm_one_view.m
1,615
utf_8
e462e05e331c3e3369e012cc60d56f65
function [x_s, r_out_norm, r_in] = sfm_one_view(gg, x, K, c, w) d_flat = gg(1); Rc = angle2Rot(gg(2), gg(3), gg(4)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = d_flat./r_in(:,3); p1 = r_in.* t_0; % point at glass and air tmp = [0 0 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm, 2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 = w./r_glass_norm(:,3); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 0 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm, 2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; end function rotate = angle2Rot(alpha, beta, gamma) rotate = zeros(3,3); r1 = [cosd(gamma) sind(gamma) 0; -sind(gamma) cosd(gamma) 0; 0 0 1 ]; r2 = [cosd(beta) 0 -sind(beta); 0 1 0; sind(beta) 0 cosd(beta)]; r3 = [1 0 0; 0 cosd(alpha) sind(alpha); 0 -sind(alpha) cosd(alpha)]; rotate = r1*r2*r3; end
github
fangcaoxin/Myproject-master
refractive_sfm.m
.m
Myproject-master/SfM/cube_near_1010/refractive_sfm.m
4,255
utf_8
9af689c433c22f9cac2b88c5d3b07040
% Use |imageDatastore| to get a list of all image file names in a % directory. clear;clc; addpath('../common'); load corres.mat IntrinsicMatrix = [2881.84239103060,0,0;0,2890.20944782907,0;2073.63152572517,1398.01946105023,1]; radialDistortion = [0.0424498292149281,-0.0489981810340664]; %cameraParams = cameraParameters('IntrinsicMatrix',IntrinsicMatrix, 'RadialDistortion',radialDistortion); bearingVec = struct('ViewIds',{},'BearingVector',{}); order = [9 8 7 6 5]; % fileID_corres = fopen('res.txt', 'r'); % formatSpec = '%f %f'; % sizeA = [2 Inf]; % corresMat = fscanf(fileID_corres, formatSpec,sizeA); % fclose(fileID_corres); % corres = reshape(corresMat,2,60,9); % save corres.mat corres % Estimate the camera pose %gg = [89.28,-2.18342172302219,2.76380543162081,-1.05]; gg = [89.28, 0, 0, 0]; c = [1.0 1.49 1.333]; w = 5.11; K = IntrinsicMatrix; order = [9 8 7 6 5]; order1 = [ 1 4 6 8]; %K = cameraParams.IntrinsicMatrix; view = struct('points',{}, 'label',{},'rot',{},'trans',{}, 'bearing_vector',{}); tracks = struct ('points',{}, 'views', {}, 'pointcloud',{}); basePoints = corres(:,:,order(1))'; [xs_t1, ro_t1, ri_t1] = sfm_one_view(gg, basePoints, K, c,w); prevBearing = [ro_t1 xs_t1 ri_t1]; [temp1,temp] = find(basePoints(:,1)>0); prevlabel = temp1; view = addview(view, basePoints,prevlabel, eye(3), zeros(1,3),prevBearing, 1 ); for i = 2:size(order,2) currPoints = corres(:,:,order(i))'; [currlabel,temp] = find(currPoints(:,1)>0); matchedPairs = intersect(prevlabel, currlabel); [xs_t2, ro_t2, ri_t2] = sfm_one_view(gg, currPoints, K, c, w); currBearing = [ro_t2 xs_t2 ri_t2]; matchVector1 = prevBearing(matchedPairs, 1:6); matchVector2 = currBearing(matchedPairs, 1:6); testVector1 = matchVector1(1:2,1:6); testVector2 = matchVector2(1:2,1:6); U=umatrix_generator_general(matchVector1, matchVector2); [relativeOrient,relativeLoc]=R_t_estimator_pixel(U, 1, 1); relativeOrient relativeLoc % triangulation prevRot = view(i-1).rot; prevTrans = view(i-1).trans; rot = relativeOrient* prevRot trans = prevTrans + relativeLoc*prevRot xw_test = triangulateR(testVector1, testVector2, prevRot, prevTrans, rot, trans); if(xw_test(:,3) < 0) [relativeOrient,relativeLoc]=R_t_estimator_pixel(U, 0, 1); end rot = relativeOrient* prevRot trans = prevTrans + relativeLoc*prevRot % if(i >= 3) % tracks_cell = struct2cell(tracks); % xyzPoints = reshape(cell2mat(tracks_cell(3,:,:)), 3, []); % label = reshape(cell2mat(tracks_cell(1,:,:)), 1, []); % [exist_label, ia, ib] = intersect(label, currlabel); % d3_points = xyzPoints'; % [rot, trans] = R_t_estimator_3d(currBearing(exist_label, :), d3_points(ia, :), 0); % rot % trans % end points3D = triangulateR(matchVector1, matchVector2, prevRot,prevTrans, rot, trans); % in C1 scatter3(points3D(:,1), points3D(:,2), points3D(:,3), 10, 'MarkerFaceColor',[1 0 0],... 'MarkerEdgeColor',[0.9,0.5,0.3]); view = addview(view, currPoints, currlabel, rot, ... trans, currBearing, i); basePoints = currPoints; prevlabel = currlabel; prevBearing = currBearing; tracks = update_tracks(tracks, matchedPairs, i, points3D); tracks_cell = struct2cell(tracks); nxyzPoints = reshape(cell2mat(tracks_cell(3,:,:)), 3, []); nxyzPoints = nxyzPoints'; % get pointcloud [xw_est, view] = optim_point(view, tracks, 1, 1, numel(tracks)); scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3)); % Get the color of each reconstructed point axis equal %ptCloud = pointCloud(xw_est); %ax= pcshow(ptCloud, 'MarkerSize', 50); %axis(ax, 'equal'); % axis([-1 -0.5 2.02 2.06 41.6 42]); % pcwrite(ptCloud, 'structure_out', 'PLYFormat', 'binary'); % Rotate and zoom the plot % camorbit(0, -30); % camzoom(1.5); % Label the axes xlabel('x-axis'); ylabel('y-axis'); zlabel('z-axis') end [xw_est, view] = optim_point(view, tracks, K, 1, 1, numel(tracks)); scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3)); function vector_no_scale = vectorNoScale(x) hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); r_in = u_v./[fx fy 1]; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize x_s = zeros(size(x, 1),3); vector_no_scale = [r_in, x_s]; end
github
fangcaoxin/Myproject-master
lagrange.m
.m
Myproject-master/SfM/common/lagrange.m
2,287
utf_8
a7d43423e24d7835dab7f4f602d61800
function g=lagrange(U,g0) l = zeros(6,1); %l = [0.5;0.5;0.5;0.5;0.5;0.5]; gg0=[g0;l];%init f=@(gg)Ug(gg,U);% % [gg,fval,info]=fsolve(f,gg0,optimset("TolFun",3e-16,"TolX",3e-16,"MaxIter",1e20)); options=optimoptions('fsolve','Algorithm', 'levenberg-marquardt',... 'Display','iter',... 'FunctionTolerance',1e-6,'MaxFunctionEvaluations', 1e6, ... 'StepTolerance', 1e-6,'MaxIterations',3000); [gg,fval,info]=fsolve(f,gg0,options); g=gg; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; end function Ug_val=Ug(gg,U) g=gg; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; g(19,:)=[]; UU=U'*U; Ug_val(1)= UU(1,:)*g; %+ gg(25)*(gg(5)*gg(9)- gg(6)*gg(8)); Ug_val(2)= UU(2,:)*g; % + gg(25)*(gg(6)*gg(7)-gg(4)*gg(9)); Ug_val(3)= UU(3,:)*g; % + gg(25)*(gg(4)*gg(8)-gg(5)*gg(7)); Ug_val(4)= UU(4,:)*g; % + gg(25)*(gg(3)*gg(8)-gg(2)*gg(9)); Ug_val(5)= UU(5,:)*g; % + gg(25)*(gg(1)*gg(9)-gg(3)*gg(7)); Ug_val(6)= UU(6,:)*g; % + gg(25)*(gg(2)*gg(7)-gg(1)*gg(8)); Ug_val(7)= UU(7,:)*g; % + gg(25)*(gg(2)*gg(6)-gg(3)*gg(5)); Ug_val(8)= UU(8,:)*g; % + gg(25)*(gg(3)*gg(4)-gg(1)*gg(6)); Ug_val(9)= UU(9,:)*g; % + gg(25)*(gg(1)*gg(5)-gg(2)*gg(4)); Ug_val(10)= UU(10,:)*g+gg(19)*gg(10)-gg(15)*gg(23)+gg(14)*gg(24)+gg(13)*gg(21); Ug_val(11)= UU(11,:)*g+gg(19)*gg(11)-gg(13)*gg(24)+gg(15)*gg(22)+gg(14)*gg(21); Ug_val(12)= UU(12,:)*g+gg(19)*gg(12)-gg(14)*gg(22)+gg(13)*gg(23)+gg(15)*gg(21); Ug_val(13)= UU(13,:)*g+gg(20)*gg(13)-gg(11)*gg(24)+gg(12)*gg(23)+gg(10)*gg(21); Ug_val(14)= UU(14,:)*g+gg(20)*gg(14)-gg(12)*gg(22)+gg(10)*gg(24)+gg(11)*gg(21); Ug_val(15)= UU(15,:)*g+gg(20)*gg(15)-gg(10)*gg(23)+gg(11)*gg(22)+gg(12)*gg(21); Ug_val(16)= UU(16,:)*g-gg(22); Ug_val(17)= UU(17,:)*g-gg(23); Ug_val(18)= UU(18,:)*g-gg(24); Ug_val(19)= (gg(10)^2+gg(11)^2+gg(12)^2-1)/2; Ug_val(20)= (gg(13)^2+gg(14)^2+gg(15)^2-1)/2; Ug_val(21)= gg(10)*gg(13)+gg(11)*gg(14)+gg(12)*gg(15); Ug_val(22)= gg(11)*gg(15)-gg(12)*gg(14)-gg(16); Ug_val(23)= gg(12)*gg(13)-gg(10)*gg(15)-gg(17); Ug_val(24)= gg(10)*gg(14)-gg(11)*gg(13)-gg(18); % Ug_val(25) = gg(1)*gg(5)*gg(9)+gg(2)*gg(6)*gg(7) + gg(3)*gg(4)*gg(8)... % -gg(3)*gg(5)*gg(7) - gg(1)*gg(6)*gg(8) - gg(2)*gg(4)*gg(9); end
github
fangcaoxin/Myproject-master
R_t_estimator_pixel.m
.m
Myproject-master/SfM/common/R_t_estimator_pixel.m
1,308
utf_8
c9c659d08f91fe8ed85c063aff0f6492
function [R_est,t_est]=R_t_estimator_pixel(U, mark, vertical) %load parameter.mat addpath('common'); [R_est, t_est] = Rt_estimate(U, mark, vertical); end function [R_est, t_est] = Rt_estimate(U, mark, vertical) U = cast(U, 'double'); [v,lambda]=eig(U'*U); if (vertical) g=v(:,2); else g =v(:,1); end k=sqrt(g(10)^2+g(11)^2+g(12)^2); g0 = g/k; if mark == 1 g0 = -g/k; end g = lagrange(U,g0); % g = g0; g(10)^2+g(11)^2+g(12)^2 g(13)^2+g(14)^2+g(15)^2 g(16)^2+g(17)^2+g(18)^2 R1=[g(10) g(11) g(12)]; R2=[g(13) g(14) g(15)]; R3=[g(16) g(17) g(18)]; R_est=[R1;R2;R3]; E=[g(1) g(2) g(3); g(4) g(5) g(6); g(7) g(8) g(9)]; [U1, S1, V1] = svd(E); W = [ 0 -1 0; 1 0 0; 0 0 1]; R_est_1(:,:,1) = U1*W*V1'; R_est_1(:,:,2) = U1*W*V1'; R_est_1(:,:,3) = U1*W'*V1'; R_est_1(:,:,4) = U1*W'*V1'; t_est_1(:,:,1) = U1(:,3); t_est_1(:,:,2) = -U1(:,3); t_est_1(:,:,3) = U1(:,3); t_est_1(:,:,4) = -U1(:,3); %U1 %S1 %V1 T = E*R_est'; t_err= 0.5*[T(3,2)-T(2,3); T(1,3)-T(3,1);T(2,1)-T(1,2)]; sign_t_err = sign(t_err); scale = (S1(1,1) + S1(2,2))/2; t_est = scale * U1(:,3); sign_t_est = sign(t_est); if(sign_t_err ~= sign_t_est) t_est = -t_est; end t_est = t_err'; end
github
fangcaoxin/Myproject-master
R_t_estimator_3d.m
.m
Myproject-master/SfM/common/R_t_estimator_3d.m
1,290
utf_8
630b96fd1b87d070ac970be92c30d654
function [R_est, t_est] = R_t_estimator_3d(bearing_vector, d3_points, vertical) ro = bearing_vector(:, 1:3); xs = bearing_vector(:, 4:6); X = d3_points; U = [ro(:, 3).*X(:,1)-ro(:, 2).*X(:,1) ... ro(:, 3).*X(:,2)-ro(:, 2).*X(:,2) ... ro(:, 3).*X(:,3)-ro(:, 2).*X(:,3) ... ro(:, 1).*X(:,1)-ro(:, 3).*X(:,1) ... ro(:, 1).*X(:,2)-ro(:, 3).*X(:,2) ... ro(:, 1).*X(:,3)-ro(:, 3).*X(:,3) ... ro(:, 2).*X(:,1)-ro(:, 1).*X(:,1) ... ro(:, 2).*X(:,2)-ro(:, 1).*X(:,2) ... ro(:, 2).*X(:,3)-ro(:, 1).*X(:,3) ... ro(:, 3)-ro(:, 2) ... ro(:, 1)-ro(:, 3) ... ro(:, 2)-ro(:, 1)]; [R_est, t_est] = Rt_estimate(U, 0, vertical); end function [R_est, t_est] = Rt_estimate(U, mark, vertical) U = cast(U, 'double'); [v,lambda]=eig(U'*U); if (vertical) g=v(:,2); else g =v(:,1); end k=sqrt(g(1)^2+g(2)^2+g(3)^2); g0 = g/k; if mark == 1 g0 = -g/k; end g = lagrange_pnp(U,g0); % g = g0; g(1)^2+g(2)^2+g(3)^2 g(4)^2+g(5)^2+g(6)^2 g(7)^2+g(8)^2+g(9)^2 R1=[g(1) g(2) g(3)]; R2=[g(4) g(5) g(6)]; R3=[g(7) g(8) g(9)]; R_p=[R1;R2;R3]; t_p = [g(10); g(11); g(12)]; R_est = R_p'; t_est = -R_p'*t_p; t_est = t_est'; % t_est = t_err; end
github
fangcaoxin/Myproject-master
optim_point.m
.m
Myproject-master/SfM/common/optim_point.m
4,569
utf_8
cc7cc33ee2be85704f02fcdcd9c8ee1b
function [xyzPoints, view] = optim_point(view, tracks, K, step, startNum, endNum) % p is point 1xN , Rt estimated rotation and translation mat4x3xM % v calucated bearing vector tracks_cell = struct2cell(tracks); nxyzPoints = reshape(cell2mat(tracks_cell(3,:,:)), 3, []); % get pointcloud p = nxyzPoints'; % all points now p_select = p(startNum:step: endNum, :); tracks_select = tracks(1, startNum:step: endNum); numViews = numel(view); numPoints = size(p_select,1); p_one_row = reshape(p_select, 1, []); R_one_row = reshape([view.rot], 1, []); t_one_row = reshape([view.trans], 1, []); <<<<<<< HEAD v = reshape([view.bearing_vector], [], 6, numViews); points_2d = reshape([view.points], [], 2, numViews); x0 = [p_one_row R_one_row(10:end) t_one_row(4:end)]; ======= v = reshape([view.bearing_vector], [], 9, numViews); x0 = [p_one_row R_one_row t_one_row]; >>>>>>> 77e8b05ee755f8118a972afe53521fb931f38ddf p_lb = -Inf(1, size(p_one_row,2)); p_ub = Inf(1, size(p_one_row,2)); R_lb = -ones(1, size(R_one_row(10:end),2)); R_ub = ones(1, size(R_one_row(10:end),2)); t_lb = -Inf(1, size(t_one_row(4:end),2)); t_ub = Inf(1, size(t_one_row(4:end),2)); lb = [p_lb R_lb t_lb]; ub = [p_ub R_ub t_ub]; %opts = optimset('Display', 'iter'); %opts = optimoptions(@lsqnonlin,'Algorithm','levenberg-marquardt','MaxFunEvals',3e4,'TolFun',1e-3); <<<<<<< HEAD %opts = optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt','MaxFunEvals',3e10,'TolFun',1e-10); out = lsqnonlin(@(x)fun(x,v,points_2d,K, numViews,numPoints,tracks_select), x0, [],[], opts); ======= opts = optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt','MaxFunEvals',3e10,'TolFun',1e-5); out = lsqnonlin(@(x)fun(x,v,numViews,numPoints,tracks_select), x0, [],[], opts); >>>>>>> 77e8b05ee755f8118a972afe53521fb931f38ddf xyzPoints = reshape(out(1:3*numPoints),[numPoints, 3]); R_opm = reshape(out(3*numPoints+1:3*numPoints + 9*(numViews)),[3,3, numViews]); t_opm = reshape(out(3*numPoints + 9*(numViews)+1:end), [3 1 numViews]); for k = 1: numViews view(k).rot = R_opm(:,:,k); view(k).trans = t_opm(:,:,k)'; end end % startNum the starting num of 3D points for optim % endNum the ending num of 3D points for optim % the step for 3D points for optim function fval = fun(x, v, points_2d,K, numViews,numPoints, tracks) m = numViews; % how many views n = numPoints; % how many points points = reshape(x(1:3*n), [],3); Rot = reshape(x(3*n+1:3*n+9*(m)), [3 3 m] ); trans = reshape(x(3*n+9*(m)+1:end),[1 3 m]); fval = zeros(1, n+6*(m)); for i = 1:n e_total = 0; for j = 1 : size(tracks(i).views, 2) view = tracks(i).views(j); rotate = Rot(:,:,view); translation = trans(:,:,view); xc = rotate'*(points(i,:) - translation)'; xc = xc'; ro = v(tracks(i).points, 1:3, view); xs = v(tracks(i).points, 4:6, view); ro_est = xc - xs; ro_est = ro_est/norm(ro_est); e1 =norm(cross(ro, ro_est)); <<<<<<< HEAD ======= ri = v(tracks(i).points, 7:9, view); >>>>>>> 77e8b05ee755f8118a972afe53521fb931f38ddf tmp = [0 0 1]; N1 = xs.*tmp; N1_norm = N1/norm(N1); xw_normal = cross(ro, N1_norm); e2 = dot(ro_est, xw_normal); xc_2d = K'*xc'; xc_2d_norm = [xc_2d(1,1) xc_2d(2,1)]./xc_2d(3,1); e3 = norm(xc_2d_norm - points_2d(tracks(i).points, :, view)); e_total = e_total + e1 + e2; end fval(i) = e_total/size(tracks(i).views, 2); end for j = 1:numViews rotate = Rot(:,:,j); fval(n + 6*(j-1)+1) = norm(rotate(1,:))-1; fval(n + 6*(j-1)+2) = norm(rotate(2,:))-1; fval(n + 6*(j-1)+3) = dot(rotate(1,:), rotate(2,:)); r3 = cross(rotate(1,:), rotate(2,:)); fval(n + 6*(j-1)+4) = r3(1)- rotate(3,1); fval(n + 6*(j-1)+5) = r3(2)- rotate(3,2); fval(n + 6*(j-1)+6) = r3(3)- rotate(3,3); end % (reshape(x(3*n+9*view -17:3*n+9*view-8),[3 3])'*... % (x(3*i-2:3*i)'-x(3*n+9*(m-1)+3*view-5:3*n+9*(m-1)+3*view-3)'))'-xs %fval(end+1: end + n)= xs_est(:,1)-xs(:,1); % fval(end+1: end + n)= xs_est(:,2)-xs(:,2); %fval(end+1: end + n)= xs_est(:,3)-xs(:,3); %xw_normal = cross(ro, N1_norm, 2); %fval(end+1: end+ n) = dot(ro_est, xw_normal, 2); % fval(end+1)= norm(Rot(1,:,i-1)) -1; % fval(end+1) = norm(Rot(2,:,i-1)) - 1; % fval(end+1) = dot(Rot(1,:,i-1),Rot(2,:,i-1)); % r3 = cross(Rot(1,:,i-1), Rot(2,:,i-1)); % fval(end+1) = r3(1) - Rot(3,1,i-1); % fval(end+1) = r3(2) - Rot(3,2,i-1); % fval(end+1) = r3(3) - Rot(3,3,i-1); end
github
fangcaoxin/Myproject-master
triangulateOptim.m
.m
Myproject-master/SfM/common/triangulateOptim.m
700
utf_8
42b18bf7d5fa641327bc7366f0de17b5
function xw = triangulateOptim(vec1, vec2, R_2, t_2) % R_2, t_2 the camera pose relative world coordinate system r_out_w1 = vec1(:, 1:3); xs_w1 = vec1(:, 4:6); ro2 = vec2(:, 1:3); xs2 = vec2(:, 4:6); r_out_w2 = ro2*R_2'; xs_w2 = xs2*R_2'+t_2'; num = size(r_out_w1, 1); k0 =50* ones(num, 2); opts = optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt','MaxFunEvals',3e10,'TolFun',1e-10); out = lsqnonlin(@(k)fun(k,r_out_w1, xs_w1, r_out_w2, xs_w2),k0, [],[], opts); xw = xs_w1 + out(:,1).*r_out_w1; end function fval = fun(k, r_out_w1, xs_w1, r_out_w2, xs_w2) num = size(r_out_w1, 1); fval = xs_w1 + k(:,1).*r_out_w1 - xs_w2 - k(:, 2).*r_out_w2; end
github
fangcaoxin/Myproject-master
lagrange_pnp.m
.m
Myproject-master/SfM/common/lagrange_pnp.m
1,610
utf_8
de38f7fca54749f8ca6f4197c58beb2c
function g=lagrange_pnp(U,g0) l = zeros(6,1); %l = [0.5;0.5;0.5;0.5;0.5;0.5]; gg0=[g0;l];%init f=@(gg)Ug(gg,U);% [gg,fval,info]=fsolve(f,gg0,optimset("TolFun",3e-16,"TolX",3e-16,"MaxIter",1e20)); %options=optimoptions('fsolve','Algorithm', 'levenberg-marquardt',... %'Display','iter',... % 'FunctionTolerance',1e-6,'MaxFunctionEvaluations', 1e6, ... % 'StepTolerance', 1e-6,'MaxIterations',3000); %[gg,fval,info]=fsolve(f,gg0,options); g=gg; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; end function Ug_val=Ug(gg,U) g=gg; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; g(13,:)=[]; UU=U'*U; Ug_val(1)= UU(1,:)*g+gg(13)*gg(1)-gg(17)*gg(6)+gg(15)*gg(4)+ gg(18)*gg(5); Ug_val(2)= UU(2,:)*g+gg(13)*gg(2)-gg(18)*gg(4)+gg(15)*gg(5)+gg(16)*gg(6); Ug_val(3)= UU(3,:)*g+gg(13)*gg(3)-gg(16)*gg(5)+gg(15)*gg(6)+gg(17)*gg(4); Ug_val(4)= UU(4,:)*g+gg(14)*gg(4)-gg(18)*gg(2)+gg(15)*gg(1)+gg(17)*gg(3); Ug_val(5)= UU(5,:)*g+gg(14)*gg(5)-gg(16)*gg(3)+gg(15)*gg(2)+gg(18)*gg(1); Ug_val(6)= UU(6,:)*g+gg(14)*gg(6)-gg(17)*gg(1)+gg(15)*gg(3)+gg(16)*gg(2); Ug_val(7)= UU(7,:)*g-gg(16); Ug_val(8)= UU(8,:)*g-gg(17); Ug_val(9)= UU(9,:)*g-gg(18); Ug_val(10) = UU(10, :)*g; Ug_val(11) = UU(11, :)*g; Ug_val(12) = UU(12, :)*g; Ug_val(13)= (gg(1)^2+gg(2)^2+gg(3)^2-1)/2; Ug_val(14)= (gg(4)^2+gg(5)^2+gg(6)^2-1)/2; Ug_val(15)= gg(1)*gg(4)+gg(2)*gg(5)+gg(3)*gg(6); Ug_val(16)= gg(2)*gg(6)-gg(3)*gg(5)-gg(7); Ug_val(17)= gg(3)*gg(4)-gg(1)*gg(6)-gg(8); Ug_val(18)= gg(1)*gg(5)-gg(2)*gg(4)-gg(9); end
github
fangcaoxin/Myproject-master
sfm_two_view.m
.m
Myproject-master/SfM/calibration/sfm_two_view.m
1,860
utf_8
9de142007a0437d9b75262532066c2c3
function xw_est = sfm_two_view() load imagePoints.mat load worldPoints.mat load historyn5.mat in = [1 2 3 5 9]; view = [3 4]; % good result x_best = historyn5.x(end,:); gg1 = [x_best(view(1)*9-8:view(1)*9) x_best(end-5:end) ]; gg2 = [x_best(view(2)*9-8:view(2)*9) x_best(end-5:end) ]; x1 = imagePoints(:,:,in(view(1))); x2 = imagePoints(:,:,in(view(2))); K =[590.2313 0 0; 0 559.4365 0; 369.2098 272.4348 1]; c = [1 1.49 1]; Ra = 50; ra = 46; [xs_w1, r_out_w1] = sfm_one_view(gg1, x1, K, c, Ra, ra); [xs_w2, r_out_w2] = sfm_one_view(gg2, x2, K, c, Ra, ra); v1 = sum(r_out_w1.*r_out_w1,2); v2 = sum(r_out_w2.*r_out_w2,2); v3 = sum(r_out_w1.*r_out_w2,2); w1 = sum((xs_w2-xs_w1).*r_out_w1,2) w2 = sum((xs_w2-xs_w1).*r_out_w2,2); s1 = (w1.*v2 - w2.*v3)./(v1.*v2-v3.*v3); s2 = (s1.*v3 -w2)./v2; xw_est = (xs_w1 + s1.*r_out_w1 + xs_w2 + s2.*r_out_w2)/2; error_x = xw_est(:,1)- worldPoints(:,1); error_y = xw_est(:,2)- worldPoints(:,2); error_z = xw_est(:,3); error = error_x.*error_x + error_y.*error_y + error_z.*error_z; error_sum = sqrt(sum(error, 1))/70; % save xw_est.mat xw_est %% draw Z = zeros(70,1); [loc1, ori1] = camera_pose(gg1) [loc2, ori2] = camera_pose(gg2); cam1 = plotCamera('Location',loc1, 'Orientation', ori1,'Size', 15); hold on cam2 = plotCamera('Location',loc2, 'Orientation', ori2,'Size', 15, 'color', [0 0 1]); hold on scatter3(worldPoints(:,1), worldPoints(:,2), Z, 15,'MarkerFaceColor',[0 0 1]); hold on scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3), 15, 'MarkerFaceColor',[1 0 0]); grid on xlabel('X(mm)'); ylabel('Y(mm)'); zlabel('Z(mm)'); legend('groud truth', 'constructed points', 'Location', 'northeast'); axis([-150 380 0 380 -600 20]); end function [loc, ori] = camera_pose(gg) r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; ori = Rot'; loc = -Rot'*ts; end
github
fangcaoxin/Myproject-master
backProjectionError.m
.m
Myproject-master/SfM/calibration/backProjectionError.m
2,918
utf_8
0d40c57c1eea57e083e2e9c610eea17b
function val = backProjectionError(x, x_w) load res.mat K =[590.2313 0 0; 0 559.4365 0; 369.2098 272.4348 1]; c = [1 1.49 1]; Ra = 50; ra = 46; r1 = [res(1) res(2) res(3)]; r2 = [res(4) res(5) res(6)]; r1 = r1/norm(r1); r2 = r2/norm(r2); r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [res(7); res(8);res(9)]; tc = [res(10); res(11); res(12)]; ac = [res(13); res(14); res(15)]; %rotate x, y, z Rc = angle2Rot(res(13), res(14), res(15)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-(r_in(:,3)*tc(3) + r_in(:,2)*tc(2)) + sqrt((r_in(:,3).*tc(3) + r_in(:,2).*tc(2)).^2 -(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(tc(2)*tc(2)+ tc(3)*tc(3)-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + tc'; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm, 2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm,2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; xs_w =(x_s - ts')*Rot; r_out_w = r_out_norm * Rot; lamda = -xs_w(:,3)./r_out_w(:,3); x_chess(:,1) = xs_w(:,1) + lamda.*r_out_w(:,1); x_chess(:,2) = xs_w(:,2) + lamda.*r_out_w(:,2); error = x_chess - x_w; x_chess val = norm(error, 'fro'); end function rotate = angle2Rot(alpha, beta, gamma) rotate = zeros(3,3); r1 = [cosd(gamma) sind(gamma) 0; -sind(gamma) cosd(gamma) 0; 0 0 1 ]; r2 = [cosd(beta) 0 -sind(beta); 0 1 0; sind(beta) 0 cosd(beta)]; r3 = [1 0 0; 0 cosd(alpha) sind(alpha); 0 -sind(alpha) cosd(alpha)]; rotate = r1*r2*r3; end
github
fangcaoxin/Myproject-master
fermat_flat.m
.m
Myproject-master/SfM/flat/fermat_flat.m
699
utf_8
3ce8b3c716837ff8e8cae3c065d94440
% use fermat to determine the intersect point at glass function [c]=fermat_flat(point,n1,n2,n3,w,d,cali) if(cali > 0) n3 = n1; end v = [-point(1), -point(2), -point(3)]; v = v/norm(v); t = (d+w-point(3))/v(3); t1 = (d-point(3))/v(3); x0 = point(1) + v(1)*t ; % outer y0 = point(2) + v(2)*t; x1 = point(1) + v(1)*t1; %inner y1 = point(2) + v(2)*t1; c0 = [x0;y0;x1;y1]; x = point(1); y = point(2); z = point(3); f=@(c)L_flat(c,x,y,z,n1,n2,n3,w,d); options=optimoptions('fmincon','Display','off'); %only matlab % [c,fval,info]=fsolve(f,c0,options); c = fmincon(f, c0,[],[],[],[],[-25 -25 -25 -23], [25 25 25 23],[], options); %fval %info end
github
fangcaoxin/Myproject-master
simulation_flat.m
.m
Myproject-master/SfM/flat/simulation_flat.m
3,359
utf_8
7e70c44b36a0cc4084871bcaabf1724c
%%simulate SfM %% load 3D points addpath('../common'); load('teapot.mat'); teapot1 = teapot(1:10:end,:) + [0 0 600]; % Z>600 %% transform 3D points to another view(R,t) external matrix load camera_motion.mat load parameter.mat teapot2 = (teapot1-trans')*rotate; teapot1 = cast(teapot1,'double'); teapot2 = cast(teapot2,'double'); %% intrinsic matrix K = [fx 0 640; 0 fy 480; 0 0 1]; %% no refraction, directly projection teapot_c1 = teapot1*K'; teapot_c2 = teapot2*K'; teapot_c1_norm = teapot_c1(:,1:2)./teapot_c1(:,3); teapot_c2_norm = teapot_c2(:,1:2)./teapot_c2(:,3); % plot(teapot_c2_norm(:,1), teapot_c2_norm(:,2),'r.'); % axis([0 1280 0 960]); % hold on %% considering refraction 3d->2d % image_points_1 = point3dt2d_flat(teapot1); % image_points_2 = point3dt2d_flat(teapot2); % plot(image_points_2(:,1), image_points_2(:,2), '.'); % save image_points_1.mat image_points_1 % save image_points_2.mat image_points_2 %% considering refraction 2d->3d load image_points_1.mat load image_points_2.mat [r_out_norm1, x_s1] = ray_out_flat(image_points_1,d_flat, w, 0); [r_out_norm2, x_s2] = ray_out_flat(image_points_2,d_flat, w, 0); %% estimate R and t matchedVector1 = [r_out_norm1 x_s1]; matchedVector2 = [r_out_norm2 x_s2]; testVector(:,:,1) = matchedVector1(1:2,:); testVector(:,:,2) = matchedVector2(1:2,:); U=umatrix_generator_general(matchedVector1, matchedVector2); %[Rp_est, tp_est] = R_t_estimator_pespective(matchedVector1,matchedVector2); [R_est,t_est]=R_t_estimator_pixel(U, testVector); rotate R_est trans t_est %% reconstruction xw = triangulateR(matchedVector1, matchedVector2, R_est, t_est); error = norm(xw-teapot1)/size(xw, 1); vec1_no_scale = vectorNoScale(image_points_1); vec2_no_scale = vectorNoScale(image_points_2); %[Rp_est, tp_est] = R_t_estimator_pespective(matchedVector1,matchedVector2); %xw_no_scale = triangulate(vec1_no_scale, vec2_no_scale, Rp_est, tp_est); %% draw color1 = [1 0 0]; draw(R_est, t_est, rotate, trans, xw, color1); hold on scatter3(teapot1(:,1), teapot1(:,2), teapot1(:,3), 5, 'MarkerFaceColor',[0 0 1], 'MarkerEdgeColor', [0 0 0.5]); axis equal % hold on % draw(Rotate, t_no_scale, 50*xw_no_scale, [0 1 0]); legend('Reconstructed by RSfM','Ground truth'); function draw(R_est, t_est, rotate, trans, xw_est, color) loc1 = [0;0;0]; loc2 = t_est; ori1 = [1 0 0; 0 1 0; 0 0 1]; ori2 = R_est; cam1 = plotCamera('Location',loc1, 'Orientation', ori1,'Size', 20,... 'label', '1', 'AxesVisible', false); hold on cam2 = plotCamera('Location',loc2, 'Orientation', ori2,'Size', 20,... 'Color',[0 0 1], 'label', 'Estimated 2', 'AxesVisible', false); hold on cam4 = plotCamera('Location',trans, 'Orientation', rotate,'Size', 20,... 'Color',[0 1 0], 'label', 'Ground truth 2', 'AxesVisible', false); % hold on % scatter3(worldPoints(:,1), worldPoints(:,2), Z,'MarkerFaceColor',[0 0 1]); % hold on scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3), 5, 'MarkerFaceColor',color, 'MarkerEdgeColor', 0.5*color); grid on xlabel('X[mm]'); ylabel('Y[mm]'); zlabel('Z[mm]'); %legend('Reconstructed by RSfM', 'Ground truth', 'Reconstructed by PSfM (50x)'); end function vector_no_scale = vectorNoScale(x) load parameter.mat u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize x_s = zeros(size(x, 1),3); vector_no_scale = [r_in, x_s]; end
github
fangcaoxin/Myproject-master
error_min.m
.m
Myproject-master/SfM/cylindrical/error_min.m
2,822
utf_8
0fa3d4b232c0453c67f09777904807d4
function res = error_min(init, x,x_w, K, c, Ra, ra) fun = @(gg)fun1(gg, x, K, c, Ra, ra) - x_w; lb = [-1 -1 -1 -1 -1 -1 -500 -500 0 0]; ub = [1 1 1 1 1 1 500 500 800 45]; %options=optimoptions('lsqnonlin', 'Display','iter','FunctionTolerance',1e-10); opts = optimset("MaxIter", 1e5, "Display", "on"); res = lsqnonlin(fun, init,lb, ub, opts); %problem = createOptimProblem('lsqnonlin','x0',init,'objective',fun,... % 'lb',lb,'ub',ub); %ms = MultiStart; %[xx,f] = run(ms, problem, 30); %f %res = xx; fun end function val = fun1(gg, x, K, c, Ra, ra) r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r1 = r1/norm(r1); r2 = r2/norm(r2); r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; d = gg(10); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u = x(1) - hcx; % coord on image sensor v = x(2) - hcy; r_in=[u, v*fx/fy, fx]; % ray in air r_in = r_in/norm(r_in); % normalize t_0 = (-r_in(3)*d + sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*... r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); if(d+r_in(3)*t_0 < 0) t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); end p1 = [r_in(1)*t_0 r_in(2)*t_0 r_in(3)*t_0+d]; % point at glass and air N = [0 p1(2) p1(3)]; % normal between air and glass N_norm = N/norm(N); s1 = norm(cross(r_in, N_norm)); % sin(theta_1) c1 =norm( r_in.*N_norm); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1/n2-sqrt(1- n1*n1/(n2*n2)*s1*s1))*N_norm; r_glass_norm = r_glass/norm(r_glass); t_1 =( -(p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3)) + sqrt((p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3))*(p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3))... -(r_glass_norm(2)*r_glass_norm(2)+r_glass_norm(3)*r_glass_norm(3))*(p1(2)*p1(2) + p1(3)*p1(3)-R*R)))/(r_glass_norm(2)*r_glass_norm(2)+r_glass_norm(3)*r_glass_norm(3)); if(p1(3)+ t_1*r_glass_norm(3)<0) t_1 =( -(p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3)) - sqrt((p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3))*(p1(2)*r_glass_norm(2) +p1(3)*r_glass_norm(3))... -(r_glass_norm(2)*r_glass_norm(2)+r_glass_norm(3)*r_glass_norm(3))*(p1(2)*p1(2) + p1(3)*p1(3)-R*R)))/(r_glass_norm(2)*r_glass_norm(2)+r_glass_norm(3)*r_glass_norm(3)); end p2 = [p1(1)+t_1*r_glass_norm(1) p1(2)+t_1*r_glass_norm(2) p1(3)+t_1*r_glass_norm(3)]; % point at glass and water N1 = [0 p2(2) p2(3)]; % normal between glass and water N1_norm = N1/norm(N1); s2 = norm(cross(r_glass_norm,N1_norm)); c2 = norm(r_glass_norm.*N1_norm); r_out = n2/n3*r_glass_norm - (n2/n3*c2-sqrt(1- n2*n2/(n3*n3)*s2*s2))*N1_norm; r_out = r_out/norm(r_out); x_s = p2; xs_w = Rot'*(x_s' - ts); r_out_w = Rot'*r_out'; lamda = -xs_w(3)/r_out_w(3); val(1) = xs_w(1) + lamda*r_out_w(1); val(2) = xs_w(2) + lamda*r_out_w(2); end
github
fangcaoxin/Myproject-master
sfm_multi_view_Rt.m
.m
Myproject-master/SfM/cylindrical/sfm_multi_view_Rt.m
3,436
utf_8
0dd3f7953db9347d06b7a6a5beb704a7
function [xw_est, R_opm, t_opm] = sfm_multi_view_Rt(imagePoints, views) % calibration result gg = [ -0.72005 2.06590 42.66089 -0.28110 -1.39643 -1.96133 ]; K =[590.2313 0 0; 0 559.4365 0; 369.2098 272.4348 1]; c = [1 1.49 1]; Ra = 50; ra = 46; n = size(imagePoints, 1); m = size(views, 2); % the number of view Rt = zeros(4,3,m); % xw_average = zeros(n, 3); xw = zeros(n, 3, m); v = zeros(n, 6, m); base_view = views(1); prevPoints = imagePoints(:,:, base_view); prevLabels = set_label(prevPoints); [xs, ro] = sfm_one_view_Rt(gg, prevPoints, K, c, Ra, ra); Rt(:,:,1) = [1 0 0; 0 1 0; 0 0 1; 0 0 0]; prevBearing = [ro xs]; view = struct('points',{}, 'label',{},'rot',{},'trans',{}, 'bearing_vector',{}); view = addview(view, prevPoints, prevLabels, eye(3), zeros(1,3), prevBearing,1); matchedPairs= zeros(n,m); xw_total = zeros(n, 3); for i = 2:m currPoints = imagePoints(:,:, views(i)); currLabels = set_label(currPoints); [xs1, ro1] = sfm_one_view_Rt(gg, currPoints, K, c, Ra, ra); currBearing = [ro1 xs1]; [matchedVector1, matchedVector2, indexPairs] = matchVectors... (prevBearing,currBearing,prevLabels,currLabels); U=umatrix_generator_general(matchedVector1, matchedVector2); [R_est,t_est]=R_t_estimator_pixel(U); prevRot = view(i-1).rot; prevTrans = view(i-1).trans; rot = R_est* prevRot; trans = prevTrans + t_est'*prevRot; view = addview(view, currPoints, currLabels, rot, trans, currBearing,i); %Out = opengv('seventeenpt',[1:1:size(bearing_vec_select, 1)],bearing_vec1_select', bearing_vec_select'); %R_est = Out(:,1:3); %t_est = Out(:,4); matchedPairs(:,1) = matchedPairs(:,1) + indexPairs; matchedPairs(:,i) = indexPairs; points_num = sum(matchedPairs(:,1)>0); xw = zeros(n, 3); for j = 2:i xyzPoints = triangulate(view(j-1).bearing_vector, view(j).bearing_vector,... view(j-1).rot, view(j-1).trans, view(j).rot, view(j).trans, matchedPairs, j); [rows cols] = find(matchedPairs(:,j) > 0); xw(rows,:) = xyzPoints; xw_total = xw_total + xw; %scatter3(xyzPoints(:,1), xyzPoints(:,2), xyzPoints(:,3)); end xw_average = sum(xw_total, 3)./matchedPairs(:,1); %scatter3(xw_average(:,1), xw_average(:,2), xw_average(:,3)); out = optim_point(xw_average, view, i, n, matchedPairs); xw_est = reshape(out(1:3*points_num),[points_num, 3]); scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3)); R_opm = reshape(out(3*points_num+1:3*points_num + 9*(i-1)),[3,3, i-1]); t_opm = reshape(out(3*points_num + 9*(i-1)+1:end), [1 3 i-1]); view = updateView(view, R_opm, t_opm, i); prevBearing = currBearing; prevLabels = currLabels; end end function xw = triangulate(vec1Full, vec2Full, R1_est, t1_est, R2_est, t2_est, matchedPairs, k) [rows cols] = find(matchedPairs(:,k) > 0); vec1 = vec1Full(rows,:); vec2 = vec2Full(rows,:); r_out_w1 = vec1(:, 1:3)*R1_est'; xs_w1 = vec1(:, 4:6)*R1_est' + t1_est; ro2 = vec2(:, 1:3); xs2 = vec2(:, 4:6); r_out_w2 = ro2*R2_est'; xs_w2 = xs2*R2_est'; xs_w2 = xs_w2 + t2_est; v1 = sum(r_out_w1.*r_out_w1,2); v2 = sum(r_out_w2.*r_out_w2,2); v3 = sum(r_out_w1.*r_out_w2,2); w1 = sum((xs_w2-xs_w1).*r_out_w1,2); w2 = sum((xs_w2-xs_w1).*r_out_w2,2); s1 = (w1.*v2 - w2.*v3)./(v1.*v2-v3.*v3); s2 = (s1.*v3 -w2)./v2; xw = (xs_w1 + s1.*r_out_w1 + xs_w2 + s2.*r_out_w2)/2; end
github
fangcaoxin/Myproject-master
sfm_one_view.m
.m
Myproject-master/SfM/cylindrical/sfm_one_view.m
2,595
utf_8
9e4269061aa317e78af57939bcbf78e7
function [xs_w, r_out_w] = sfm_one_view(gg, x, K, c, Ra, ra) r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; tc = [gg(10); gg(11); gg(12)]; ac = [gg(13); gg(14); gg(15)]; %rotate x, y, z Rc = angle2Rot(gg(13), gg(14), gg(15)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-(r_in(:,3)*tc(3) + r_in(:,2)*tc(2)) + sqrt((r_in(:,3).*tc(3) + r_in(:,2).*tc(2)).^2 -(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(tc(2)*tc(2)+ tc(3)*tc(3)-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + tc'; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm, 2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm, 2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; xs_w =(x_s - ts')*Rot; r_out_w = r_out_norm * Rot; end function rotate = angle2Rot(alpha, beta, gamma) rotate = zeros(3,3); r1 = [cosd(gamma) sind(gamma) 0; -sind(gamma) cosd(gamma) 0; 0 0 1 ]; r2 = [cosd(beta) 0 -sind(beta); 0 1 0; sind(beta) 0 cosd(beta)]; r3 = [1 0 0; 0 cosd(alpha) sind(alpha); 0 -sind(alpha) cosd(alpha)]; rotate = r1*r2*r3; end
github
fangcaoxin/Myproject-master
sfm_one_view_Rt.m
.m
Myproject-master/SfM/cylindrical/sfm_one_view_Rt.m
2,431
utf_8
b9bd89530f1ecbac0e443f30f0d64b79
function [xs, ro] = sfm_one_view_Rt(gg, x, K, c, Ra, ra) tc = [gg(1); gg(2); gg(3)]; ac = [gg(4); gg(5); gg(6)]; %rotate x, y, z Rc = angle2Rot(gg(4), gg(5), gg(6)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-(r_in(:,3)*tc(3) + r_in(:,2)*tc(2)) + sqrt((r_in(:,3).*tc(3) + r_in(:,2).*tc(2)).^2 -(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(tc(2)*tc(2)+ tc(3)*tc(3)-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + tc'; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm, 2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm, 2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); xs = p2; ro = r_out_norm; end function rotate = angle2Rot(alpha, beta, gamma) rotate = zeros(3,3); r1 = [cosd(gamma) sind(gamma) 0; -sind(gamma) cosd(gamma) 0; 0 0 1 ]; r2 = [cosd(beta) 0 -sind(beta); 0 1 0; sind(beta) 0 cosd(beta)]; r3 = [1 0 0; 0 cosd(alpha) sind(alpha); 0 -sind(alpha) cosd(alpha)]; rotate = r1*r2*r3; end
github
fangcaoxin/Myproject-master
fermat.m
.m
Myproject-master/SfM/cylindrical/fermat.m
1,650
utf_8
da4bc1faf6de6486ebefb87c32310e6c
% use fermat to determine the intersect point at glass function [c]=fermat(point,n1,n2,n3,R,r,d, cali) load parameter.mat if(cali > 0) n3 = n1; end % point = double(point); v = [point(1), point(2), point(3)-d]; % v =[0 point(2)-camera_center(2) point(3)-camera_center(3)]; v = v/norm(v); t =( -(point(2)*v(2) +point(3)*v(3)) + sqrt((point(2)*v(2) +point(3)*v(3))*(point(2)*v(2) +point(3)*v(3))... -(v(2)*v(2)+v(3)*v(3))*(point(2)*point(2) + point(3)*point(3)-R*R)))/(v(2)*v(2)+v(3)*v(3)); t1 = ( -(point(2)*v(2) +point(3)*v(3)) + sqrt((point(2)*v(2) +point(3)*v(3))*(point(2)*v(2) +point(3)*v(3))... -(v(2)*v(2)+v(3)*v(3))*(point(2)*point(2) + point(3)*point(3)-r*r)))/(v(2)*v(2)+v(3)*v(3)); z0 = point(3) + v(3)*t; z1 = point(3) + v(3)*t1; if(z0 < 0) t =( -(point(2)*v(2) +point(3)*v(3)) - sqrt((point(2)*v(2) +point(3)*v(3))*(point(2)*v(2) +point(3)*v(3))-(v(2)*v(2)+v(3)*v(3))*(point(2)*point(2) + point(3)*point(3)-R*R)))/(v(2)*v(2)+v(3)*v(3)); end if(z1 < 0) t1 =( -(point(2)*v(2) +point(3)*v(3)) - sqrt((point(2)*v(2) +point(3)*v(3))*(point(2)*v(2) +point(3)*v(3))-(v(2)*v(2)+v(3)*v(3))*(point(2)*point(2) + point(3)*point(3)-r*r)))/(v(2)*v(2)+v(3)*v(3)); end x0 = point(1) + v(1)*t ; y0 = point(2) + v(2)*t; x1 = point(1) + v(1)*t1; y1 = point(2) + v(2)*t1; c0 = [x0;y0;x1;y1]; x = point(1); y = point(2); z = point(3); f=@(c)L(c,x,y,z,n1,n2,n3,R,r,d); options=optimoptions('fmincon','Display','off'); %only matlab % [c,fval,info]=fsolve(f,c0,options); c = fmincon(f, c0,[],[],[],[],[-25 -25 -25 -23], [25 25 25 23],[], options); %fval %info end
github
fangcaoxin/Myproject-master
error_min_2.m
.m
Myproject-master/SfM/cylindrical/error_min_2.m
8,253
utf_8
e95c3c41468a15ed9c19dbe38c683124
function res = error_min_2(init, x,x_w, K, c, Ra, ra,lb,ub, N) historyn5.x = []; historyn5.fval = []; fun = @(ga)fun_total(ga, x, x_w, K, c, Ra, ra, N); % options=optimoptions(@fmincon, 'Display','iter', 'Algorithm','sqp',... % 'MaxIterations',3000, 'MaxFunctionEvaluations', 1e4, 'ConstraintTolerance', 1e-1); options=optimoptions(@fmincon, 'OutputFcn', @outfun,'Display','iter', 'Algorithm','sqp',... 'MaxIterations',3000, 'MaxFunctionEvaluations', 1e4, 'ConstraintTolerance', 1e-1); % opts = optimset("MaxIter", 1e5, "Display", "on"); % nonlcon1 = @(gg)cameraRot1(gg); nonlcon1 = @(ga)cameraRot_total(ga, x, x_w, K , c, Ra, ra, N); A = []; b = []; Aeq = []; beq = []; res = fmincon(fun, init, A, b, Aeq, beq, lb, ub, nonlcon1,options); % problem =createOptimProblem('fmincon', 'objective', fun,'x0', init, 'lb', lb, 'ub', ub, 'nonlcon', nonlcon1,'options',options); % gs = GlobalSearch; % [res, val]= run(gs, problem); %[gg, val] = sqp(init, fun, nonlcon1, [], lb, ub); % [res, val, info, iter, nf, lambda] = sqp(init, fun, nonlcon1, [], lb, ub); res % val function[c, ceq] = cameraRot1(gg) c =[]; ceq(1,1) = gg(1)^2 + gg(2)^2 + gg(3)^2 -1; ceq(2,1) = gg(4)^2 + gg(5)^2 + gg(6)^2 -1; ceq(3,1) = gg(1)*gg(4) + gg(2)*gg(5) + gg(3)*gg(6); end function [c1, ceq] = cameraRot_total(ga, uv, x_w, K , c, Ra, ra, N) ceq = zeros(15*N+3,1); for i = 1:N gg = [ga(9*i-8:9*i) ga(9*N+1: end)]; [c1, ceq(15*i-14:15*i,1)] = cameraRot(gg, uv(:,:,i), x_w, K , c, Ra, ra); end end function[c1, ceq] = cameraRot(gg, uv, x_w, K , c, Ra, ra) c1=[]; % ceq = zeros(3+size(uv,1),1); ceq(1,1) = gg(1)^2 + gg(2)^2 + gg(3)^2 -1; ceq(2,1) = gg(4)^2 + gg(5)^2 + gg(6)^2 -1; ceq(3,1) = gg(1)*gg(4) + gg(2)*gg(5) + gg(3)*gg(6); r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; tc = [gg(10); gg(11); gg(12)]; ac = [gg(13); gg(14); gg(15)]; %rotate x, y, z Rc = angle2Rot(gg(13), gg(14), gg(15)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = uv - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-(r_in(:,3)*tc(3) + r_in(:,2)*tc(2)) + sqrt((r_in(:,3).*tc(3) + r_in(:,2).*tc(2)).^2 -(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(tc(2)*tc(2)+ tc(3)*tc(3)-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); p1 = r_in.* t_0 + tc'; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm,2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm,2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; x_w(:, 3) = 0; x_wc = x_w * Rot' + ts'; x_out = x_wc - x_s; x_out_norm = x_out./sqrt(sum(x_out.*x_out, 2)); angle = cross(x_out_norm, r_out_norm); angle_norm = sqrt(sum(angle.*angle, 2)); ceq(4: 6,1) = angle_norm(1:3); ceq(7: 9,1) = angle_norm(24:26); ceq(10: 12,1) = angle_norm(50:52); ceq(13: 15,1) = angle_norm(68:70); end function val_total = fun_total(ga, x, x_w, K, c, Ra, ra, N) gg = [ga(1:9) ga(9*N+1:end)]; val_total = fun1(gg, x(:,:,1), x_w, K, c, Ra, ra); for i = 2:N gg = [ga(i*9-8:i*9) ga(9*N+1:end)]; val_total= val_total + fun1(gg, x(:,:,i), x_w, K, c, Ra, ra); end end function val = fun1(gg, x, x_w, K, c, Ra, ra) r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r1 = r1/norm(r1); r2 = r2/norm(r2); r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; tc = [gg(10); gg(11); gg(12)]; ac = [gg(13); gg(14); gg(15)]; %rotate x, y, z Rc = angle2Rot(gg(13), gg(14), gg(15)); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in*Rc'; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-(r_in(:,3)*tc(3) + r_in(:,2)*tc(2)) + sqrt((r_in(:,3).*tc(3) + r_in(:,2).*tc(2)).^2 -(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(tc(2)*tc(2)+ tc(3)*tc(3)-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + tc'; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm, 2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm, 2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; xs_w =(x_s - ts')*Rot; r_out_w = r_out_norm * Rot; lamda = -xs_w(:,3)./r_out_w(:,3); x_chess(:,1) = xs_w(:,1) + lamda.*r_out_w(:,1); x_chess(:,2) = xs_w(:,2) + lamda.*r_out_w(:,2); error = x_chess - x_w; val = error.*error; val = sum(val, 2); val = sum(val, 1); % val = norm(error, 'fro'); end function rotate = angle2Rot(alpha, beta, gamma) rotate = zeros(3,3); r1 = [cosd(gamma) sind(gamma) 0; -sind(gamma) cosd(gamma) 0; 0 0 1 ]; r2 = [cosd(beta) 0 -sind(beta); 0 1 0; sind(beta) 0 cosd(beta)]; r3 = [1 0 0; 0 cosd(alpha) sind(alpha); 0 -sind(alpha) cosd(alpha)]; rotate = r1*r2*r3; end function stop = outfun(x,optimValues,state) stop = false; switch state case 'init' hold on case 'iter' % Concatenate current point and objective function % value with history. x must be a row vector. historyn5.fval = [historyn5.fval; optimValues.fval]; historyn5.x = [historyn5.x; x]; % plot(ga(48),optimValues.fval, 'o'); % optimValues.fval % Concatenate current search direction with % searchdir. % searchdir = [searchdir;... % optimValues.searchdirection']; % plot(x(1),x(2),'o'); % Label points with iteration number and add title. % Add .15 to x(1) to separate label from plotted 'o' % text(x(1)+.15,x(2),... % num2str(optimValues.iteration)); % title('Sequence of Points Computed by fmincon'); case 'done' save historyn5.mat historyn5; hold off otherwise end end end
github
fangcaoxin/Myproject-master
error_min_1.m
.m
Myproject-master/SfM/cylindrical/error_min_1.m
5,901
utf_8
4542da36101a814cb88048da1e5029ab
function res = error_min_1(init, x,x_w, K, c, Ra, ra) fun = @(gg)fun1(gg, x, x_w, K, c, Ra, ra); lb = [-1 -1 -1 -1 -1 -1 -500 -500 0 0]; ub = [1 1 1 1 1 1 500 500 800 43]; options=optimoptions(@fmincon, 'Display','iter', 'Algorithm','sqp',... 'MaxIterations',3000, 'MaxFunctionEvaluations', 1e5,'ConstraintTolerance', 1e-3); % opts = optimset("MaxIter", 1e5, "Display", "on"); % nonlcon1 = @(gg)cameraRot1(gg); nonlcon1 = @(gg)cameraRot(gg, x, x_w, K , c, Ra, ra); A = []; b = []; Aeq = []; beq = []; res = fmincon(fun, init, A, b, Aeq, beq, lb, ub, nonlcon1,options); % problem =createOptimProblem('fmincon', 'objective', fun,'x0', init, 'lb', lb, 'ub', ub, 'nonlcon', nonlcon1,'options',options); % gs = GlobalSearch; % [res, val]= run(gs, problem); res end function [c,ceq] = cameraRot1(gg) c = []; ceq(1,1) = gg(1)^2 + gg(2)^2 + gg(3)^2 -1; ceq(2,1) = gg(4)^2 + gg(5)^2 + gg(6)^2 -1; ceq(3,1) = gg(1)*gg(4) + gg(2)*gg(5) + gg(3)*gg(6); end function [c1, ceq] = cameraRot(gg, uv, x_w, K , c, Ra, ra) c1 =[]; ceq = zeros(3+size(uv,1),1); ceq(1,1) = gg(1)^2 + gg(2)^2 + gg(3)^2 -1; ceq(2,1) = gg(4)^2 + gg(5)^2 + gg(6)^2 -1; ceq(3,1) = gg(1)*gg(4) + gg(2)*gg(5) + gg(3)*gg(6); r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; d = gg(10); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = uv - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; %u = uv(:,1) - hcx; % coord on image sensor %v = uv(:,2) - hcy; %r_in=[u, v*fx/fy, fx]; % ray in air r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-r_in(:,3)*d + sqrt(r_in(:,3).*r_in(:,3)*d*d-(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(d*d-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + [0 0 d]; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm,2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm,2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; x_w(:, 3) = 0; x_wc = x_w * Rot' + ts'; x_out = x_wc - x_s; x_out_norm = x_out./sqrt(sum(x_out.*x_out, 2)); angle = cross(x_out_norm, r_out_norm); angle_norm = sqrt(sum(angle.*angle, 2)); ceq(4,1) = angle_norm(1); ceq(5,1) = angle_norm(25); ceq(6,1) = angle_norm(50); ceq(7,1) = angle_norm(60); %ceq(8: 9,1) = angle_norm(50:51); % ceq(10,1) = angle_norm(70); end function val = fun1(gg, x, x_w, K, c, Ra, ra) r1 = [gg(1) gg(2) gg(3)]; r2 = [gg(4) gg(5) gg(6)]; r1 = r1/norm(r1); r2 = r2/norm(r2); r3 = cross(r1,r2); Rot = [r1;r2;r3]; ts = [gg(7); gg(8);gg(9)]; d = gg(10); hcx = K(3,1); hcy = K(3,2); fx = K(1,1); fy = K(2,2); n1 = c(1); n2 = c(2); n3 = c(3); R = Ra; r = ra; u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize t_0 = (-r_in(:,3)*d + sqrt(r_in(:,3).*r_in(:,3)*d*d-(r_in(:,2).*r_in(:,2)+r_in(:,3).*... r_in(:,3))*(d*d-r*r)))./(r_in(:,2).*r_in(:,2)+r_in(:,3).*r_in(:,3)); %if(d+r_in(3)*t_0 < 0) % t_0 = (-r_in(3)*d - sqrt(r_in(3)*r_in(3)*d*d-(r_in(2)*r_in(2)+r_in(3)*r_in(3))*(d*d-r*r)))/(r_in(2)*r_in(2)+r_in(3)*r_in(3)); %end p1 = r_in.* t_0 + [0 0 d]; % point at glass and air tmp = [0 1 1]; coeff = repmat(tmp, size(p1,1), 1); N = p1.* coeff; % normal between air and glass N_norm = N./sqrt(sum(N.*N, 2)); s1 = cross(r_in, N_norm,2); % sin(theta_1) s1_norm = sqrt(sum(s1.*s1,2)); c1_norm = dot(r_in, N_norm,2); % cos(theta_1) r_glass = n1*r_in/n2 - (n1*c1_norm./n2-sqrt(1- n1*n1/(n2*n2)*s1_norm.*s1_norm)).*N_norm; r_glass_norm = r_glass./sqrt(sum(r_glass.*r_glass, 2)); t_1 =( -(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)) + sqrt((p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3)).*(p1(:,2).*r_glass_norm(:,2) +p1(:,3).*r_glass_norm(:,3))... -(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)).*(p1(:,2).*p1(:,2) + p1(:,3).*p1(:,3)-R*R)))./(r_glass_norm(:,2).*r_glass_norm(:,2)+r_glass_norm(:,3).*r_glass_norm(:,3)); p2 = p1 + t_1.*r_glass_norm; % point at glass and water tmp = [0 1 1]; coeff = repmat(tmp, size(p2,1), 1); N1 = p2.* coeff; % normal between glass and water N1_norm = N1./sqrt(sum(N1.*N1,2)); s2 = cross(r_glass_norm,N1_norm,2); s2_norm = sqrt(sum(s2.*s2, 2)); c2_norm = dot(r_glass_norm, N1_norm, 2); r_out = n2/n3*r_glass_norm - (n2/n3*c2_norm - sqrt(1- n2*n2/(n3*n3)*s2_norm.*s2_norm)).*N1_norm; r_out_norm = r_out./sqrt(sum(r_out.*r_out, 2)); x_s = p2; xs_w =(x_s - ts')*Rot; r_out_w = r_out_norm * Rot; lamda = -xs_w(:,3)./r_out_w(:,3); x_chess(:,1) = xs_w(:,1) + lamda.*r_out_w(:,1); x_chess(:,2) = xs_w(:,2) + lamda.*r_out_w(:,2); error = x_chess - x_w; val = norm(error, 'fro'); end
github
fangcaoxin/Myproject-master
simulate_sfm.m
.m
Myproject-master/SfM/cylindrical/simulate_sfm.m
3,750
utf_8
2675724566b0af6a7d0daac5c67cfdef
%%simulate SfM %% load 3D points addpath('common') load('teapot.mat'); teapot1 = teapot(1:10:end,:) + [0 0 600]; % Z>600 %% transform 3D points to another view(R,t) external matrix load camera_motion.mat load parameter.mat teapot2 = (teapot1-translation')*Rotate; % transform teapot 1 to Camera 2 system according R and t teapot1 = cast(teapot1,'double'); teapot2 = cast(teapot2,'double'); %% intrinsic matrix K = [fx 0 640; 0 fy 480; 0 0 1]; %% no refraction, directly projection teapot_c1 = teapot1*K'; teapot_c2 = teapot2*K'; teapot_c1_norm = teapot_c1(:,1:2)./teapot_c1(:,3); teapot_c2_norm = teapot_c2(:,1:2)./teapot_c2(:,3); % plot(teapot_c2_norm(:,1), teapot_c2_norm(:,2),'r.'); % axis([0 1280 0 960]); % hold on %% considering refraction 3d->2d % image_points_1 = point3d_t_2d(teapot1); % image_points_2 = point3d_t_2d(teapot2); % plot(image_points_2(:,1), image_points_2(:,2), '.'); % save image_points_1.mat image_points_1 % save image_points_2.mat image_points_2 %% considering refraction 2d->3d load image_points_1.mat load image_points_2.mat [r_out_norm1, x_s1] = ray_in_out_pixel(image_points_1,d, 0); [r_out_norm2, x_s2] = ray_in_out_pixel(image_points_2,d, 0); %% estimate R and t matchedVector1 = [r_out_norm1 x_s1]; matchedVector2 = [r_out_norm2 x_s2]; testVector(:,:,1) = matchedVector1(1:2,:); testVector(:,:,2) = matchedVector2(1:2,:); U=umatrix_generator_general(matchedVector1, matchedVector2); [R_est,t_est]=R_t_estimator_pixel(U, testVector); Rotate R_est translation t_est %% reconstruction xw = triangulateR(matchedVector1, matchedVector2, R_est, t_est); t_no_scale = translation/norm(translation); vec1_no_scale = vectorNoScale(image_points_1); vec2_no_scale = vectorNoScale(image_points_2); [R_p, t_p] = R_t_estimator_pespective(vec1_no_scale, vec2_no_scale); R_p t_p xw_no_scale = triangulateR(vec1_no_scale, vec2_no_scale, R_p, t_p); %% draw color1 = [0 1 0]; % draw(R_est, t_est, Rotate, translation, xw, color1); % hold on scatter3(teapot1(:,1), teapot1(:,2), teapot1(:,3), 5, 'MarkerFaceColor',[0 0 1], 'MarkerEdgeColor', [0 0 0.5]); hold on draw(Rotate, t_no_scale,Rotate, translation, 50*xw_no_scale, [0 1 0]); axis equal function draw(R_est, t_est, Rotate, translation, xw_est, color) loc1 = [0;0;0]; loc2 = t_est; ori1 = [1 0 0; 0 1 0; 0 0 1]; ori2 = R_est; % cam1 = plotCamera('Location',loc1, 'Orientation', ori1,'Size', 20,... % 'label', '1', 'AxesVisible', false); % hold on % cam2 = plotCamera('Location',loc2, 'Orientation', ori2,'Size', 20,... % 'Color',[0 0 1], 'label', 'Estimated 2', 'AxesVisible', false); % hold on % cam4 = plotCamera('Location',translation, 'Orientation', Rotate,'Size', 20,... % 'Color',[0 1 0], 'label', 'Ground truth 2', 'AxesVisible', false); % hold on % scatter3(worldPoints(:,1), worldPoints(:,2), Z,'MarkerFaceColor',[0 0 1]); hold on scatter3(xw_est(:,1), xw_est(:,2), xw_est(:,3), 5, 'MarkerFaceColor',color, 'MarkerEdgeColor', 0.5*color); grid on xlabel('X[mm]'); ylabel('Y[mm]'); zlabel('Z[mm]'); %legend('Reconstructed by RSfM', 'Ground truth', 'Reconstructed by PSfM (50x)'); legend('Ground truth','Reconstructed by PSfM (50x)'); % axis_x_min = min([xw_est(:,1); t_est(1,1)]); % axis_x_max = max([xw_est(:,1); t_est(1,1)]); % axis_y_min = min([xw_est(:,2); t_est(2,1)]); % axis_y_max = max([xw_est(:,2); t_est(2,1)]); % axis_z_min = min([xw_est(:,3); t_est(3,1)]); % axis_z_max = max([xw_est(:,3); t_est(3,1)]); % axis([axis_x_min axis_x_max axis_y_min axis_y_max axis_z_min axis_z_max]); end function vector_no_scale = vectorNoScale(x) load parameter.mat u_v = x - [hcx hcy]; u_v(:,3) = 1; r_in = u_v./[fx fy 1]; r_in = r_in./sqrt(sum(r_in.*r_in,2)); % normalize x_s = zeros(size(x, 1),3); vector_no_scale = [r_in, x_s]; end
github
ctjacobs/plane-poiseuille-flow-master
poiseuille.m
.m
plane-poiseuille-flow-master/poiseuille.m
3,160
utf_8
46fbab88c09a6344eb5ecf19205462e9
% Solves the equation d2u/dy2 = -G/mu to simulate plane Poiseuille flow. % This considers the fluid between two parallel plates located at y = 0 and % y = Ly, with both plates stationary and a constant pressure % gradient G = -dp/dx applied in the streamwise direction. The dynamic viscosity of % the fluid is denoted by mu. % % Note that the time-dependent PDE du/dt = d2u/dy2 + G/mu is actually solved % here, where nu is the kinematic viscosity of the fluid. It is the final % steady-state solution which satisfies d2u/dy2 = -G/mu. % % Copyright (C) 2017 Christian Thomas Jacobs function u = poiseuille(Ly, Ny, T, dt, G, mu) % Grid spacing in the y direction. dy = Ly/(Ny-1); % Number of timesteps. Nt = ceil(T/dt); % The stored solution from the previous timestep. % Initially this is a zero velocity field. u_old = zeros(Ny, 1); % Timestepping loop. % This uses the Forward Euler timestepping scheme. for n = 1:Nt % Compute solution at timestep n. u = solve(u_old, dy, dt, G, mu) % Save the solution for use in the next timestep. u_old = u; end % Compute the exact solution. u_exact = exact(Ly, Ny, G, mu); % Determine maximum error (in the Euclidean norm) of the numerical % solution. error = sum(abs(u-u_exact).^2)^0.5; fprintf('The error in the Euclidean norm is %.5f\n', error); % Plot the numerical and exact solutions. figure(1) plot(linspace(0, Ly, Ny), u) legend('Numerical') xlabel('y') ylabel('u(y)') % Plot the error. figure(2) plot(linspace(0, Ly, Ny), abs(u-u_exact)) legend('Error') xlabel('y') ylabel('|u(y) - u_{exact}(y)|') end function u = solve(u_old, dy, dt, G, mu) % Step forward one timestep by solving the discretised system of % equations. % Setup solution vector. Ny = size(u_old, 1); u = zeros(Ny, 1); % Thomas algorithm for the solution of the tri-diagonal matrix system. c1 = -dt/(2*dy^2); c2 = 1 + dt/(dy^2); a = zeros(Ny-1, 1); b = zeros(Ny, 1); r = zeros(Ny, 1); % Forward sweep. Note that indices 1 and Ny are not considered here, since % u(1) and u(Ny) are known from the boundary conditions. r(2) = dt*G/mu + (-c2+2)*u_old(2) - c1*u_old(3); % Apply Dirichlet condition u(1) = 0. a(2) = c1/c2; b(2) = r(2)/c2; for j = 3:Ny-2 r(j) = dt*G/mu + (-c2+2)*u_old(j) - c1*u_old(j+1) - c1*u_old(j-1); a(j) = c1/(c2-c1*a(j-1)); b(j) = (r(j) - c1*b(j-1))/(c2 - c1*a(j-1)); end r(Ny-1) = dt*G/mu + (-c2+2)*u_old(Ny-1) - c1*u_old(Ny-2); % Apply Dirichlet condition u(Ny) = 0. b(Ny-1) = (r(Ny-1) - c1*b(Ny-2))/(c2 - c1*a(Ny-2)); % Back substitution. u(Ny-1) = b(Ny-1); for j = Ny-2:-1:2 u(j) = b(j) - a(j)*u(j+1); end % Enforce boundary conditions. u(1) = 0; u(Ny) = 0; end function u = exact(Ly, Ny, G, mu) % Exact solution given by u(y) = (G/(2*mu))*y*(Ly-y). u = zeros(Ny, 1); for j = 1:Ny y = (j-1)*(Ly/(Ny-1)); u(j) = (G/(2*mu))*y*(Ly-y); end end
github
vkosuri/CourseraMachineLearning-master
submit.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/submit.m
1,438
utf_8
665ea5906aad3ccfd94e33a40c58e2ce
function submit() addpath('./lib'); conf.assignmentSlug = 'k-means-clustering-and-pca'; conf.itemName = 'K-Means Clustering and PCA'; conf.partArrays = { ... { ... '1', ... { 'findClosestCentroids.m' }, ... 'Find Closest Centroids (k-Means)', ... }, ... { ... '2', ... { 'computeCentroids.m' }, ... 'Compute Centroid Means (k-Means)', ... }, ... { ... '3', ... { 'pca.m' }, ... 'PCA', ... }, ... { ... '4', ... { 'projectData.m' }, ... 'Project Data (PCA)', ... }, ... { ... '5', ... { 'recoverData.m' }, ... 'Recover Data (PCA)', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(sin(1:165), 15, 11); Z = reshape(cos(1:121), 11, 11); C = Z(1:5, :); idx = (1 + mod(1:15, 3))'; if partId == '1' idx = findClosestCentroids(X, C); out = sprintf('%0.5f ', idx(:)); elseif partId == '2' centroids = computeCentroids(X, idx, 3); out = sprintf('%0.5f ', centroids(:)); elseif partId == '3' [U, S] = pca(X); out = sprintf('%0.5f ', abs([U(:); S(:)])); elseif partId == '4' X_proj = projectData(X, Z, 5); out = sprintf('%0.5f ', X_proj(:)); elseif partId == '5' X_rec = recoverData(X(:,1:5), Z, 5); out = sprintf('%0.5f ', X_rec(:)); end end
github
vkosuri/CourseraMachineLearning-master
submitWithConfiguration.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
vkosuri/CourseraMachineLearning-master
savejson.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
vkosuri/CourseraMachineLearning-master
loadjson.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
vkosuri/CourseraMachineLearning-master
loadubjson.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
vkosuri/CourseraMachineLearning-master
saveubjson.m
.m
CourseraMachineLearning-master/home/week-8/exercises/machine-learning-ex7/ex7/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
vkosuri/CourseraMachineLearning-master
submit.m
.m
CourseraMachineLearning-master/home/week-9/exercises/machine-learning-ex8/ex8/submit.m
2,135
utf_8
eebb8c0a1db5a4df20b4c858603efad6
function submit() addpath('./lib'); conf.assignmentSlug = 'anomaly-detection-and-recommender-systems'; conf.itemName = 'Anomaly Detection and Recommender Systems'; conf.partArrays = { ... { ... '1', ... { 'estimateGaussian.m' }, ... 'Estimate Gaussian Parameters', ... }, ... { ... '2', ... { 'selectThreshold.m' }, ... 'Select Threshold', ... }, ... { ... '3', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Cost', ... }, ... { ... '4', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Gradient', ... }, ... { ... '5', ... { 'cofiCostFunc.m' }, ... 'Regularized Cost', ... }, ... { ... '6', ... { 'cofiCostFunc.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases n_u = 3; n_m = 4; n = 5; X = reshape(sin(1:n_m*n), n_m, n); Theta = reshape(cos(1:n_u*n), n_u, n); Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u); R = Y > 0.5; pval = [abs(Y(:)) ; 0.001; 1]; Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed yval = [R(:) ; 1; 0]; params = [X(:); Theta(:)]; if partId == '1' [mu sigma2] = estimateGaussian(X); out = sprintf('%0.5f ', [mu(:); sigma2(:)]); elseif partId == '2' [bestEpsilon bestF1] = selectThreshold(yval, pval); out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]); elseif partId == '3' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', J(:)); elseif partId == '4' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', grad(:)); elseif partId == '5' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', J(:)); elseif partId == '6' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', grad(:)); end end
github
vkosuri/CourseraMachineLearning-master
submitWithConfiguration.m
.m
CourseraMachineLearning-master/home/week-9/exercises/machine-learning-ex8/ex8/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end