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
timy/texmacs-master
isplot.m
.m
texmacs-master/plugins/octave/octave/tm/isplot.m
694
utf_8
dde47566d9f45b2ac9d689317b65f2a6
############################################################################### ## ## MODULE : isplot.m ## DESCRIPTION : Determines if we should plot ## COPYRIGHT : (C) 2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= isplot (cmds, line) trimmed_line = strtrim(line); [r, c]= size(cmds); ret= false; for i=1:c if (strncmpi (trimmed_line, cmds{i}, length (cmds{i}))) ret= true; return else ret= false; endif endfor endfunction
github
timy/texmacs-master
tmrepl.m
.m
texmacs-master/plugins/octave/octave/tm/tmrepl.m
2,091
ibm852
5cf82cb66c7969c6fcd6b389cefbff9e
############################################################################### ## ## MODULE : tmrepl.m ## DESCRIPTION : REPL loop ## COPYRIGHT : (C) 2004-2010 Joris van der Hoeven ## (C) 2014 François Poulain ## (C) 2020-2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function tmrepl() cmds_for_plot= plot_cmds(); while (true) # If it was cleared, initialize it again if exist ("cmds_for_plot") != 1 cmds_for_plot= plot_cmds(); endif line = input ("", "s"); code = line; if (index(line, char(16)) == 1) flush_scheme (complete (parse_complete (substr (line, 2)))); continue else line = input ("", "s"); while (!strcmp (line, "<EOF>")) code = [code, "\n", line]; line = input ("", "s"); endwhile endif if code(length (code)) != ";" disp_ans= true; else disp_ans= false; endif trimed_r= strtrim (code); if isvarname (trimed_r) && exist (trimed_r) == 1 code= sprintf ("ans= %s;", code); else # Reset ans to empty string ans= ""; # Suppress the output code= sprintf ("%s;", code); endif # NOTE: the evaled code will use the polluted env eval (code, "tmlasterr"); # For `clear` or `clear all`, disp_ans will be cleared if exist ("disp_ans") == 0 disp_ans= false; endif if disp_ans if (isplot (cmds_for_plot, code)) plotted= tmplot (); ## call TeXmacs plotting interface if plotted disp_ans= false; endif endif endif if disp_ans && isnewans (ans) tmdisp (ans); else flush_verbatim ("\n"); endif flush_prompt (PS1 ()); # Debugging Hints: # fid= fopen ("/tmp/octave.log", "a"); # fprintf (fid, "command: %s\n", r); # fclose (fid); endwhile endfunction
github
timy/texmacs-master
parse_complete.m
.m
texmacs-master/plugins/octave/octave/tm/parse_complete.m
672
utf_8
8422b13fafa71db78a9c6480f1597b57
############################################################################### ## ## MODULE : parse_complete.m ## DESCRIPTION : Parse Completion Command ## COPYRIGHT : (C) 2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. # example line: (complete "hel" 3) function ret= parse_complete (line) for x=strsplit(line, " ") if starts_with(x{1}, "\"") && ends_with(x{1}, "\"") ret= unquote(x{1}); return endif endfor ret= "" endfunction
github
timy/texmacs-master
tmlasterr.m
.m
texmacs-master/plugins/octave/octave/tm/tmlasterr.m
489
utf_8
d4156413169db97e3af0b715b67c7698
############################################################################### ## ## MODULE : tmlasterr.m ## COPYRIGHT : (C) 2004 Joris van der Hoeven ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function tmlasterr () eval ("fdisp(stderr,lasterr)","fdisp(stderr,'error')"); endfunction
github
timy/texmacs-master
isnewans.m
.m
texmacs-master/plugins/octave/octave/tm/isnewans.m
881
ibm852
1009ac2f17f3d134718f11eb2a895471
############################################################################### ## ## MODULE : isnewans.m ## DESCRIPTION : Determines if we should display an answer ## COPYRIGHT : (C) 2004 Joris van der Hoeven ## (C) 2014 François Poulain ## (C) 2020 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= isnewans (A) # typeinfo (A) is not string/sq_string/dq_string if !strcmp(typeinfo (A), "string") && ... !strcmp(typeinfo (A), "sq_string") && ... !strcmp(typeinfo (A), "dq_string") ret= true; # A is not an empty string elseif !strcmp(A, "") ret= true; else ret= false; endif endfunction
github
timy/texmacs-master
tmdisp.m
.m
texmacs-master/plugins/octave/octave/tm/tmdisp.m
703
utf_8
00d307554de35eaf72400782970e5d3c
############################################################################### ## ## MODULE : tmdisp.m ## DESCRIPTION : Displays the Octave object via the TeXmacs interface ## COPYRIGHT : (C) 2002 Michael Graffam [email protected] ## 2004 Joris van der Hoeven ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function tmdisp (M) scheme_to_flush= obj2scm (M); if length (scheme_to_flush) == 0 flush_verbatim (M); else flush_scheme (scheme_to_flush); endif endfunction
github
timy/texmacs-master
unquote.m
.m
texmacs-master/plugins/octave/octave/kernel/unquote.m
632
utf_8
5bde94361111557fccfbdcc5a35f1c5a
############################################################################### ## ## MODULE : unquote.m ## DESCRIPTION : unquote a string ## COPYRIGHT : (C) 2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= unquote (content) if length(content) > 2 && starts_with (content, "\"") && ends_with (content, "\"") ret = substr(content, 2, length(content)-2); else ret = content; endif endfunction
github
timy/texmacs-master
ends_with.m
.m
texmacs-master/plugins/octave/octave/kernel/ends_with.m
530
utf_8
d0103259fb0f06664039dc1d6d329208
############################################################################### ## ## MODULE : ends_with.m ## DESCRIPTION : Test if a string ends with ## COPYRIGHT : (C) 2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= ends_with (str, x) ret= strncmp(substr(str, -length(x)), x, length(x)); endfunction
github
timy/texmacs-master
starts_with.m
.m
texmacs-master/plugins/octave/octave/kernel/starts_with.m
518
utf_8
42fa5ba9b5759fc5bc78d263c519fbe2
############################################################################### ## ## MODULE : starts_with.m ## DESCRIPTION : Test if a string starts with ## COPYRIGHT : (C) 2021 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= starts_with (str, x) ret= strncmp (str, x, length (x)); endfunction
github
timy/texmacs-master
dquote.m
.m
texmacs-master/plugins/octave/octave/kernel/dquote.m
491
utf_8
67d306837b4fc39604325d9a21523ba0
############################################################################### ## ## MODULE : dquote.m ## DESCRIPTION : dquote a string ## COPYRIGHT : (C) 2020 Darcy Shen ## ## This software falls under the GNU general public license version 3 or later. ## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE ## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. function ret= dquote (content) ret= ["\"", content, "\""]; endfunction
github
cszn/FFDNet-master
Cal_PSNRSSIM.m
.m
FFDNet-master/utilities/Cal_PSNRSSIM.m
6,569
utf_8
c726759a14c4754004b2fbbec4ebbf36
function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col) [n,m,ch]=size(B); A = A(row+1:n-row,col+1:m-col,:); B = B(row+1:n-row,col+1:m-col,:); A=double(A); % Ground-truth B=double(B); % e=A(:)-B(:); mse=mean(e.^2); psnr_cur=10*log10(255^2/mse); if ch==1 [ssim_cur, ~] = ssim_index(A, B); else ssim_cur = (ssim_index(A(:,:,1), B(:,:,1)) + ssim_index(A(:,:,2), B(:,:,2)) + ssim_index(A(:,:,3), B(:,:,3)))/3; end function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L) %======================================================================== %SSIM Index, Version 1.0 %Copyright(c) 2003 Zhou Wang %All Rights Reserved. % %The author is with Howard Hughes Medical Institute, and Laboratory %for Computational Vision at Center for Neural Science and Courant %Institute of Mathematical Sciences, New York University. % %---------------------------------------------------------------------- %Permission to use, copy, or modify this software and its documentation %for educational and research purposes only and without fee is hereby %granted, provided that this copyright notice and the original authors' %names appear on all copies and supporting documentation. This program %shall not be used, rewritten, or adapted as the basis of a commercial %software or hardware product without first obtaining permission of the %authors. The authors make no representations about the suitability of %this software for any purpose. It is provided "as is" without express %or implied warranty. %---------------------------------------------------------------------- % %This is an implementation of the algorithm for calculating the %Structural SIMilarity (SSIM) index between two images. Please refer %to the following paper: % %Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image %quality assessment: From error measurement to structural similarity" %IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004. % %Kindly report any suggestions or corrections to [email protected] % %---------------------------------------------------------------------- % %Input : (1) img1: the first image being compared % (2) img2: the second image being compared % (3) K: constants in the SSIM index formula (see the above % reference). defualt value: K = [0.01 0.03] % (4) window: local window for statistics (see the above % reference). default widnow is Gaussian given by % window = fspecial('gaussian', 11, 1.5); % (5) L: dynamic range of the images. default: L = 255 % %Output: (1) mssim: the mean SSIM index value between 2 images. % If one of the images being compared is regarded as % perfect quality, then mssim can be considered as the % quality measure of the other image. % If img1 = img2, then mssim = 1. % (2) ssim_map: the SSIM index map of the test image. The map % has a smaller size than the input images. The actual size: % size(img1) - size(window) + 1. % %Default Usage: % Given 2 test images img1 and img2, whose dynamic range is 0-255 % % [mssim ssim_map] = ssim_index(img1, img2); % %Advanced Usage: % User defined parameters. For example % % K = [0.05 0.05]; % window = ones(8); % L = 100; % [mssim ssim_map] = ssim_index(img1, img2, K, window, L); % %See the results: % % mssim %Gives the mssim value % imshow(max(0, ssim_map).^4) %Shows the SSIM index map % %======================================================================== if (nargin < 2 || nargin > 5) ssim_index = -Inf; ssim_map = -Inf; return; end if (size(img1) ~= size(img2)) ssim_index = -Inf; ssim_map = -Inf; return; end [M N] = size(img1); if (nargin == 2) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); % K(1) = 0.01; % default settings K(2) = 0.03; % L = 255; % end if (nargin == 3) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 4) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 5) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end C1 = (K(1)*L)^2; C2 = (K(2)*L)^2; window = window/sum(sum(window)); img1 = double(img1); img2 = double(img2); mu1 = filter2(window, img1, 'valid'); mu2 = filter2(window, img2, 'valid'); mu1_sq = mu1.*mu1; mu2_sq = mu2.*mu2; mu1_mu2 = mu1.*mu2; sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq; sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq; sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2; if (C1 > 0 & C2 > 0) ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)); else numerator1 = 2*mu1_mu2 + C1; numerator2 = 2*sigma12 + C2; denominator1 = mu1_sq + mu2_sq + C1; denominator2 = sigma1_sq + sigma2_sq + C2; ssim_map = ones(size(mu1)); index = (denominator1.*denominator2 > 0); ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index)); index = (denominator1 ~= 0) & (denominator2 == 0); ssim_map(index) = numerator1(index)./denominator1(index); end mssim = mean2(ssim_map); return
github
cszn/FFDNet-master
model_init_FFDNet_gray.m
.m
FFDNet-master/TrainingCodes/FFDNet_TrainingCodes_v1.0/model_init_FFDNet_gray.m
2,824
utf_8
f72ef6df0ddf9b9959ebba4d7ec8e9f5
function net = model_init_FFDNet_gray lr11 = [1 1]; lr10 = [1 0]; weightDecay = [1 1]; nCh = 64; % number of channels fSz = 3; % fize size nNm = 1; % number of noise level map useBnorm = 0; % if useBnorm = 0, you should also use adam. nsubimage = 4; % 4 for grayscale image, 12 for color image % Define network net.layers = {} ; net.layers{end+1} = struct('type', 'SubP','scale',1/2) ; net.layers{end+1} = struct('type', 'concat') ; net.layers{end+1} = struct('type', 'conv', ... 'weights', {{orthrize2(sqrt(2/(9*nCh))*randn(fSz,fSz,nsubimage+nNm,nCh,'single')), zeros(nCh,1,'single')}}, ... 'stride', 1, ... 'pad', 1, ... 'dilate',1, ... 'learningRate',lr11, ... 'weightDecay',weightDecay, ... 'opts',{{}}) ; net.layers{end+1} = struct('type', 'relu','leak',0) ; for i = 1:1:13 if useBnorm == 0 net.layers{end+1} = struct('type', 'conv', ... 'weights', {{orthrize2(sqrt(2/(9*nCh))*randn(fSz,fSz,nCh,nCh,'single')), zeros(nCh,1,'single')}}, ... 'stride', 1, ... 'learningRate',lr11, ... 'dilate',1, ... 'weightDecay',weightDecay, ... 'pad', 1, 'opts', {{}}) ; else net.layers{end+1} = struct('type', 'conv', ... 'weights', {{orthrize2(sqrt(2/(9*nCh))*randn(fSz,fSz,nCh,nCh,'single')), zeros(nCh,1,'single')}}, ... 'stride', 1, ... 'learningRate',lr10, ... 'dilate',1, ... 'weightDecay',weightDecay, ... 'pad', 1, 'opts', {{}}) ; net.layers{end+1} = struct('type', 'bnorm', ... 'weights', {{ones(nCh,1,'single'), zeros(nCh,1,'single'),[zeros(nCh,1,'single'), ones(nCh,1,'single')]}}, ... 'learningRate', [1 1 1], ... 'weightDecay', [0 0]) ; end net.layers{end+1} = struct('type', 'relu','leak',0) ; end net.layers{end+1} = struct('type', 'conv', ... 'weights', {{orthrize2(sqrt(2/(9*nCh))*randn(fSz,fSz,nCh,nsubimage,'single')), zeros(nsubimage,1,'single')}}, ... 'stride', 1, ... 'learningRate',lr10, ... 'dilate',1, ... 'weightDecay',weightDecay, ... 'pad', 1, 'opts', {{}}) ; net.layers{end+1} = struct('type', 'SubP','scale',2) ; net.layers{end+1} = struct('type', 'loss') ; % make sure the new 'vl_nnloss.m' is in the same folder. % Fill in default values net = vl_simplenn_tidy(net); end function W = orthrize2(a) s_ = size(a); a = reshape(a,[size(a,1)*size(a,2)*size(a,3),size(a,4),1,1]); [u,d,v] = svd(a, 'econ'); if(size(a,1) < size(a, 2)) u = v'; end %W = sqrt(2).*reshape(u, s_); W = reshape(u, s_); end function A = clipping2(A,b) A(A<b(1)) = b(1); A(A>b(2)) = b(2); end function A = clipping(A,b) A(A>=0&A<b) = b; A(A<0&A>-b) = -b; end
github
cszn/FFDNet-master
model_train.m
.m
FFDNet-master/TrainingCodes/FFDNet_TrainingCodes_v1.0/model_train.m
9,175
utf_8
614e813f6525a25d76e1b2cdd7b584cf
function [net, state] = model_train(net, varargin) % simple code % The function automatically restarts after each training epoch by % checkpointing. % % The function supports training on CPU or on one or more GPUs % (specify the list of GPU IDs in the `gpus` option). % Copyright (C) 2014-16 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). %------------------------------------------------------------------------- % solver: Adam %------------------------------------------------------------------------- opts.beta1 = 0.9; opts.beta2 = 0.999; opts.alpha = 0.01; opts.epsilon = 1e-8; opts.weightDecay = 0.0001; %------------------------------------------------------------------------- % setting for simplenn %------------------------------------------------------------------------- opts.conserveMemory = true; opts.mode = 'normal'; opts.cudnn = true ; opts.backPropDepth = +inf ; opts.skipForward = false; opts.numSubBatches = 1; %------------------------------------------------------------------------- % setting for model %------------------------------------------------------------------------- opts.batchSize = 128 ; opts.gpus = []; opts.numEpochs = 300 ; opts.learningRate = 0.0001*ones(1,100,'single'); opts.modelName = 'model'; opts.expDir = fullfile('data',opts.modelName) ; %------------------------------------------------------------------------- % update settings %------------------------------------------------------------------------- opts = vl_argparse(opts, varargin); opts.numEpochs = numel(opts.learningRate); if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end %------------------------------------------------------------------------- % Initialization %------------------------------------------------------------------------- net = vl_simplenn_tidy(net); %%% fill in some eventually missing values net.layers{end-1}.precious = 1; vl_simplenn_display(net, 'batchSize', opts.batchSize) ; state.getBatch = getBatch ; %------------------------------------------------------------------------- % Train and Test %------------------------------------------------------------------------- modelPath = @(ep) fullfile(opts.expDir, sprintf([opts.modelName,'-epoch-%d.mat'], ep)); start = findLastCheckpoint(opts.expDir,opts.modelName) ; if start >= 1 fprintf('%s: resuming by loading epoch %d', mfilename, start) ; load(modelPath(start), 'net') ; % net = vl_simplenn_tidy(net) ; end imdb = []; for epoch = start+1 : opts.numEpochs % Train for one epoch. state.epoch = epoch ; state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))); if numel(opts.gpus) == 1 net = vl_simplenn_move(net, 'gpu') ; end %------------------------------------------------------------------------- % generate training data %------------------------------------------------------------------------- if mod(epoch,10)~=1 && isfield(imdb,'set') ~= 0 else clear imdb; [imdb] = generatepatches; end opts.train = find(imdb.set==1); state.train = opts.train(randperm(numel(opts.train))) ; % shuffle [net, state] = process_epoch(net, state, imdb, opts, 'train'); %net.layers{end}.class =[]; net = vl_simplenn_move(net, 'cpu'); % save current model save(modelPath(epoch), 'net') end function [net, state] = process_epoch(net, state, imdb, opts, mode) if strcmp(mode,'train') % solver: Adam for i = 1:numel(net.layers) if isfield(net.layers{i}, 'weights') for j = 1:numel(net.layers{i}.weights) state.layers{i}.t{j} = 0; state.layers{i}.m{j} = 0; state.layers{i}.v{j} = 0; end end end end subset = state.(mode) ; num = 0 ; res = []; for t=1:opts.batchSize:numel(subset) for s=1:opts.numSubBatches % get this image batch batchStart = t + (s-1); batchEnd = min(t+opts.batchSize-1, numel(subset)); batch = subset(batchStart : opts.numSubBatches : batchEnd) ; num = num + numel(batch) ; if numel(batch) == 0, continue ; end [inputs,labels] = state.getBatch(imdb, batch) ; if numel(opts.gpus) >= 1 inputs = gpuArray(inputs); labels = gpuArray(labels); end if strcmp(mode, 'train') dzdy = single(1); evalMode = 'normal';% forward and backward else dzdy = [] ; evalMode = 'test'; % forward only end net.layers{end}.class = labels ; res = vl_simplenn(net, inputs, dzdy, res, ... 'accumulate', s ~= 1, ... 'mode', evalMode, ... 'conserveMemory', opts.conserveMemory, ... 'backPropDepth', opts.backPropDepth, ... 'cudnn', opts.cudnn) ; end if strcmp(mode, 'train') [state, net] = params_updates(state, net, res, opts, opts.batchSize) ; end lossL2 = gather(res(end).x) ; %--------add your code here------------------------ %-------------------------------------------------- fprintf('%s: epoch %02d : %3d/%3d: loss: %4.4f \n', mode, state.epoch, ... fix((t-1)/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize),lossL2) ; % fprintf('loss: %4.4f \n', lossL2) ; end function [state, net] = params_updates(state, net, res, opts, batchSize) % solver: Adam for l=numel(net.layers):-1:1 for j=1:numel(res(l).dzdw) if j == 3 && strcmp(net.layers{l}.type, 'bnorm') % special case for learning bnorm moments thisLR = net.layers{l}.learningRate(j); net.layers{l}.weights{j} = vl_taccum(... 1 - thisLR, ... net.layers{l}.weights{j}, ... thisLR / batchSize, ... res(l).dzdw{j}) ; else % if j == 1 && strcmp(net.layers{l}.type, 'bnorm') % c = net.layers{l}.weights{j}; % net.layers{l}.weights{j} = clipping(c,mean(abs(c))/2); % end thisLR = state.learningRate * net.layers{l}.learningRate(j); state.layers{l}.t{j} = state.layers{l}.t{j} + 1; t = state.layers{l}.t{j}; alpha = thisLR; lr = alpha * sqrt(1 - opts.beta2^t) / (1 - opts.beta1^t); state.layers{l}.m{j} = state.layers{l}.m{j} + (1 - opts.beta1) .* (res(l).dzdw{j} - state.layers{l}.m{j}); state.layers{l}.v{j} = state.layers{l}.v{j} + (1 - opts.beta2) .* (res(l).dzdw{j} .* res(l).dzdw{j} - state.layers{l}.v{j}); % weight decay net.layers{l}.weights{j} = net.layers{l}.weights{j} - thisLR * opts.weightDecay * net.layers{l}.weightDecay(j) * net.layers{l}.weights{j}; % update weights net.layers{l}.weights{j} = net.layers{l}.weights{j} - lr * state.layers{l}.m{j} ./ (sqrt(state.layers{l}.v{j}) + opts.epsilon) ; %--------add your own code to update the parameters here------- if rand > 0.99 A = net.layers{l}.weights{j}; if numel(A)>=3*3*64 A = reshape(A,[size(A,1)*size(A,2)*size(A,3),size(A,4),1,1]); if size(A,1)> size(A,2) [U,S,V] = svd(A,0); else [U,S,V] = svd(A,'econ'); end S1 =smallClipping2(diag(S),1.1,0.9); A = U*diag(S1)*V'; A = reshape(A,size(net.layers{l}.weights{j})); net.layers{l}.weights{j} = A; end end %-------------------------------------------------------------- end end end %end function epoch = findLastCheckpoint(modelDir,modelName) list = dir(fullfile(modelDir, [modelName,'-epoch-*.mat'])) ; tokens = regexp({list.name}, [modelName,'-epoch-([\d]+).mat'], 'tokens') ; epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ; epoch = max([epoch 0]) ; function A = smallClipping(A, theta) A(A>theta) = A(A>theta) -0.000001; A(A<-theta) = A(A<-theta)+0.000001; function A = smallClipping2(A, theta1,theta2) A(A>theta1) = A(A>theta1)-0.00001; A(A<theta2) = A(A<theta2)+0.00001; function fn = getBatch fn = @(x,y) getSimpleNNBatch(x,y); function [inputs,labels] = getSimpleNNBatch(imdb, batch) global sigmas; K = randi(8); labels = imdb.HRlabels(:,:,:,batch); labels = data_augmentation(labels,K); sigma_max = 75; sigmas = (rand(1,size(labels,4))*sigma_max)/255; %sigmas = round(7*chi2rnd(3,[1,size(labels,4)]))/255; inputs = labels + bsxfun(@times,randn(size(labels)), reshape(sigmas,[1,1,1,size(labels,4)]));
github
cszn/FFDNet-master
Cal_PSNRSSIM.m
.m
FFDNet-master/TrainingCodes/FFDNet_TrainingCodes_v1.0/utilities/Cal_PSNRSSIM.m
6,569
utf_8
c726759a14c4754004b2fbbec4ebbf36
function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col) [n,m,ch]=size(B); A = A(row+1:n-row,col+1:m-col,:); B = B(row+1:n-row,col+1:m-col,:); A=double(A); % Ground-truth B=double(B); % e=A(:)-B(:); mse=mean(e.^2); psnr_cur=10*log10(255^2/mse); if ch==1 [ssim_cur, ~] = ssim_index(A, B); else ssim_cur = (ssim_index(A(:,:,1), B(:,:,1)) + ssim_index(A(:,:,2), B(:,:,2)) + ssim_index(A(:,:,3), B(:,:,3)))/3; end function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L) %======================================================================== %SSIM Index, Version 1.0 %Copyright(c) 2003 Zhou Wang %All Rights Reserved. % %The author is with Howard Hughes Medical Institute, and Laboratory %for Computational Vision at Center for Neural Science and Courant %Institute of Mathematical Sciences, New York University. % %---------------------------------------------------------------------- %Permission to use, copy, or modify this software and its documentation %for educational and research purposes only and without fee is hereby %granted, provided that this copyright notice and the original authors' %names appear on all copies and supporting documentation. This program %shall not be used, rewritten, or adapted as the basis of a commercial %software or hardware product without first obtaining permission of the %authors. The authors make no representations about the suitability of %this software for any purpose. It is provided "as is" without express %or implied warranty. %---------------------------------------------------------------------- % %This is an implementation of the algorithm for calculating the %Structural SIMilarity (SSIM) index between two images. Please refer %to the following paper: % %Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image %quality assessment: From error measurement to structural similarity" %IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004. % %Kindly report any suggestions or corrections to [email protected] % %---------------------------------------------------------------------- % %Input : (1) img1: the first image being compared % (2) img2: the second image being compared % (3) K: constants in the SSIM index formula (see the above % reference). defualt value: K = [0.01 0.03] % (4) window: local window for statistics (see the above % reference). default widnow is Gaussian given by % window = fspecial('gaussian', 11, 1.5); % (5) L: dynamic range of the images. default: L = 255 % %Output: (1) mssim: the mean SSIM index value between 2 images. % If one of the images being compared is regarded as % perfect quality, then mssim can be considered as the % quality measure of the other image. % If img1 = img2, then mssim = 1. % (2) ssim_map: the SSIM index map of the test image. The map % has a smaller size than the input images. The actual size: % size(img1) - size(window) + 1. % %Default Usage: % Given 2 test images img1 and img2, whose dynamic range is 0-255 % % [mssim ssim_map] = ssim_index(img1, img2); % %Advanced Usage: % User defined parameters. For example % % K = [0.05 0.05]; % window = ones(8); % L = 100; % [mssim ssim_map] = ssim_index(img1, img2, K, window, L); % %See the results: % % mssim %Gives the mssim value % imshow(max(0, ssim_map).^4) %Shows the SSIM index map % %======================================================================== if (nargin < 2 || nargin > 5) ssim_index = -Inf; ssim_map = -Inf; return; end if (size(img1) ~= size(img2)) ssim_index = -Inf; ssim_map = -Inf; return; end [M N] = size(img1); if (nargin == 2) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); % K(1) = 0.01; % default settings K(2) = 0.03; % L = 255; % end if (nargin == 3) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 4) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 5) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end C1 = (K(1)*L)^2; C2 = (K(2)*L)^2; window = window/sum(sum(window)); img1 = double(img1); img2 = double(img2); mu1 = filter2(window, img1, 'valid'); mu2 = filter2(window, img2, 'valid'); mu1_sq = mu1.*mu1; mu2_sq = mu2.*mu2; mu1_mu2 = mu1.*mu2; sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq; sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq; sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2; if (C1 > 0 & C2 > 0) ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)); else numerator1 = 2*mu1_mu2 + C1; numerator2 = 2*sigma12 + C2; denominator1 = mu1_sq + mu2_sq + C1; denominator2 = sigma1_sq + sigma2_sq + C2; ssim_map = ones(size(mu1)); index = (denominator1.*denominator2 > 0); ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index)); index = (denominator1 ~= 0) & (denominator2 == 0); ssim_map(index) = numerator1(index)./denominator1(index); end mssim = mean2(ssim_map); return
github
lxmzb/Artificial-Bee-Colony-Algorithm1-master
GreedySelection.m
.m
Artificial-Bee-Colony-Algorithm1-master/GreedySelection.m
1,109
utf_8
01aee25215f23518c5b2fab80fc2c2bc
function [Colony Obj Fit oBas]=GreedySelection(Colony1,Colony2,ObjEmp,ObjEmp2,FitEmp,FitEmp2,fbas,ABCOpts,i) % [Employed ObjEmp FitEmp Bas]=GreedySelection(Employed,Employed2,ObjEmp,ObjEmp2,FitEmp,FitEmp2,Bas,ABCOpts); oBas=fbas; Obj=ObjEmp; Fit=FitEmp; Colony=Colony1; if (nargin==8) %Inside the body of a user-defined function, NARGIN returns the number of input arguments that were used to call the function. for ind=1:size(Colony1,1) % 1-50 if (FitEmp2(ind)>FitEmp(ind)) oBas(ind)=0; Fit(ind)=FitEmp2(ind); Obj(ind)=ObjEmp2(ind); Colony(ind,:)=Colony2(ind,:); else oBas(ind)=fbas(ind)+1; Fit(ind)=FitEmp(ind); Obj(ind)=ObjEmp(ind); Colony(ind,:)=Colony1(ind,:); end; end; %for end; %if if(nargin==9) ind=i; if (FitEmp2(ind)>FitEmp(ind)) oBas(ind)=0; Fit(ind)=FitEmp2(ind); Obj(ind)=ObjEmp2(ind); Colony(ind,:)=Colony2(ind,:); else oBas(ind)=fbas(ind)+1; Fit(ind)=FitEmp(ind); Obj(ind)=ObjEmp(ind); Colony(ind,:)=Colony1(ind,:); end; end;
github
copenhaver/trimmedlasso-master
tl_apx_envelope.m
.m
trimmedlasso-master/MATLAB/tl_apx_envelope.m
863
utf_8
2d6d3bb0651d8ffa7bb8f8bac283b54b
%%% % A MATLAB implementation of algorithms from BCM17 % Written by Martin S. Copenhaver (www.mit.edu/~mcopen) %%% function [betar] = tl_apx_envelope(p,k,y,X,mu,lambda) % throwbinding is considered an optional final argument if nargin ~= 6 disp('Incorrect number of arguments provided. Halting execution.'); return; end if ( p ~= size(X,2) ) disp('Specified p is not equal to row dimension of X. Halting execution.'); return; end cvx_begin variable gammar(p) variable betar(p) variable envelop minimize( 0.5*betar'*X'*X*betar - y'*X*betar+dot(y,y)/2 + mu*sum(gammar)+ lambda*envelop ) subject to envelop >= 0; gammar >= 0; gammar >= betar; gammar >= -betar; envelop >= sum(gammar) - k; cvx_end end
github
copenhaver/trimmedlasso-master
instance_creator.m
.m
trimmedlasso-master/MATLAB/instance_creator.m
1,251
utf_8
a3138a062772c38f270fddadcab31552
% Creates problem instances for use in the demo (demo.m) % Written by Martin S. Copenhaver (www.mit.edu/~mcopen) function [y, X, beta0] = instance_creator(n,p,k,SNR,egclass) SS = eye(p,p); beta0 = zeros(p,1); %% based on class, develop special example if egclass == 1 rho = 0.8; ir = round(p/k); for i=1:p if mod(i,ir) == 1 % then beta0[i] = 1 beta0(i) = 1; end for j = 1:p SS(i,j) = rho^abs(i-j); end end end % if egclass == 2 % for i=1:5 % beta0[i] = 1; % end % end % if egclass == 3 % for i=1:10 % beta0[i] = 1/2 + 10/9*.95*(i-1); % end % end % if egclass == 4 % for i=1:6 % beta0[i] = -14 + 4*i; % end % % end % if egclass == 5 % for i=1:6 % beta0[i] = 1/2 + 10/9*.95*(i-1)^5; % end % beta0 = beta0/norm(beta0); % end %% for all, define y = Xb+eps sig = sqrt(beta0'*SS*beta0/SNR); eps = sig*randn(n,1); X = mvnrnd(zeros(n,p),SS); % normalize columns of X to have ell2 norm of 1 for i=1:p X(:,i) = X(:,i)/norm(X(:,i)); end y = X*beta0 + eps; return ; % y, X, beta0; end
github
copenhaver/trimmedlasso-master
tl_exact_bigM.m
.m
trimmedlasso-master/MATLAB/tl_exact_bigM.m
1,475
utf_8
16965c1b541c07762d7f4dee27ac8cbc
%%% % A MATLAB implementation of exact algorithm from BCM17 % for solving trimmed Lasso problem % Written by Martin S. Copenhaver (www.mit.edu/~mcopen) %%% function [betar] = tl_exact_bigM(p,k,y,X,mu,lambda,bigM,throwbinding) % throwbinding is an optional final argument if nargin == 7 throwbinding = true; end if ( p ~= size(X,2) ) disp('Specified p is not equal to row dimension of X. Halting execution.'); return; end if ~( bigM >= 0 && bigM < inf ) disp('Invalid big-M value supplied. Halting execution.'); end cvx_begin variable gammar(p) variable a(p) variable betar(p) variable z(p) binary minimize( 0.5*betar'*X'*X*betar - y'*X*betar+dot(y,y)/2 + mu*sum(gammar)+lambda*sum(a) ) subject to gammar >= 0; a >= 0; gammar >= betar; gammar >= -betar; a >= bigM*z + gammar - bigM*ones(p,1); betar <= bigM; betar >= -bigM; sum(z) == p-k; cvx_end binding = false; for i=1:p if abs(betar(i)) >= bigM - 1e-3 binding = true; end end if (binding && throwbinding) disp('Warning: big-M constraint is binding -- you should increase big-M and resolve. Otherwise, re-use same big-M and set optional argument `throwbinding=false`.'); betar = NaN; return; else return; end end
github
copenhaver/trimmedlasso-master
tl_apx_altmin.m
.m
trimmedlasso-master/MATLAB/tl_apx_altmin.m
2,157
utf_8
1201a883299460b70d6255e3db98964b
%%% % A MATLAB implementation of Algorithm 1 from BCM17 % Written by Martin S. Copenhaver (www.mit.edu/~mcopen) %%% function [betar] = tl_apx_altmin(p,k,y,X,mu,lambda,tol,max_iters) % check argument count (final two arguments, tol and max_iters, are optional) if (nargin ~= 6) && (nargin ~=7) && (nargin ~= 8) disp('Incorrect number of arguments provided. Halting execution.'); return; else if (nargin == 6) tol = 1e-3; max_iters = 1000; else if (nargin == 7) max_iters = 1000; end end end if ( p ~= size(X,2) ) disp('Specified p is not equal to row dimension of X. Halting execution.'); return; end % perform alternating minimization in gamma and betar until convergence % criteria is satisfied % initial beta with random value betar = randn(p,1); prev_imp = Inf; cur_obj = Inf; iter = 0; while (prev_imp > tol) && (iter < max_iters) iter = iter + 1; %% wrt gammar (betar fixed) % ***N.B.***: We do not include the special cases as detailed in % BCM17 in Appendix C. These are included in the julia % implementation, but not here because we want the Matlab % implementation to be as rudimentary as possible. % need to sort entries of betar res = sortrows([abs(betar)';1:p;betar']'); gammar = zeros(p,1); for i=(p-k+1):p gammar(res(i,2)) = lambda*sign(res(i,3)); end %% wrt betar (gammar fixed) cvx_begin quiet variable betar(p) minimize( 0.5*betar'*X'*X*betar - (gammar'+y'*X)*betar+dot(y,y)/2 + (mu+lambda)*sum(abs(betar)) ) cvx_end %% update objectives prev_obj = cur_obj; tl_pen = sort(abs(betar)); cur_obj = 0.5*betar'*X'*X*betar - y'*X*betar+dot(y,y)/2 + mu*sum(abs(betar)) + lambda*sum(tl_pen(1:(p-k))); prev_imp = prev_obj - cur_obj; end return; end
github
ridhomahesa/Brain-Tumor-Classification-master
brain_tumor_classify.m
.m
Brain-Tumor-Classification-master/brain_tumor_classify.m
29,726
utf_8
8e933ef90006a20e14adc422f774fb78
function varargout = brain_tumor_classify(varargin) % BRAIN_TUMOR_CLASSIFY MATLAB code for brain_tumor_classify.fig % BRAIN_TUMOR_CLASSIFY, by itself, creates a new BRAIN_TUMOR_CLASSIFY or raises the existing % singleton*. % % H = BRAIN_TUMOR_CLASSIFY returns the handle to a new BRAIN_TUMOR_CLASSIFY or the handle to % the existing singleton*. % % BRAIN_TUMOR_CLASSIFY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in BRAIN_TUMOR_CLASSIFY.M with the given input arguments. % % BRAIN_TUMOR_CLASSIFY('Property','Value',...) creates a new BRAIN_TUMOR_CLASSIFY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before brain_tumor_classify_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to brain_tumor_classify_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 brain_tumor_classify % Last Modified by GUIDE v2.5 13-Jul-2017 09:33:39 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @brain_tumor_classify_OpeningFcn, ... 'gui_OutputFcn', @brain_tumor_classify_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 brain_tumor_classify is made visible. function brain_tumor_classify_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 brain_tumor_classify (see VARARGIN) % Choose default command line output for brain_tumor_classify handles.output = hObject; % Update handles structure setappdata(0,'datacontainer',hObject); movegui(hObject,'onscreen')% To display application onscreen movegui(hObject,'center') % To display application in the center of screen % UIWAIT makes brain_tumor_classify wait for user response (see UIRESUME) % uiwait(handles.figure1); clear clc warning off all % --- Outputs from this function are returned to the command line. function varargout = brain_tumor_classify_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 % INPUT FILE CITRA % --- 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) [nama_file,nama_path] = uigetfile({'*.png*'}); if ~isequal(nama_file,0) img = imread(fullfile(nama_path,nama_file)); axes(handles.axes1) imshow(img) handles.img = img; guidata(hObject,handles) else return end textLabel = sprintf('%s ',nama_path); set(handles.edit15, 'String', textLabel); % PENGUJIAN % --- 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) global kelas; img = handles.img; % Preprocessing img_gray=rgb2gray(img); cc = medfilt2(img_gray); T = 155; bw = im2bw(cc,T/255); % Morphological Operation SE = strel('disk',2); bw1 = imerode(bw,SE); bw2 = imdilate(bw1,SE); SE2 = strel('disk',4); bw3 = imerode(bw2,SE2); SE3 = strel('disk',4); bw4 = imdilate(bw3,SE3); bw6 = bwareaopen(bw4,350,8); bw6a = imfill(bw6, 'holes'); SE5 = strel('disk',3); bw7 = imdilate(bw6a,SE5); % Jika tidak ada yang tersegmentasi if bw7 == 0 cc_resize = 255*uint8(bw7); brain1 = cc_resize; brain_glcm = double(cc_resize); brain_glcm(brain_glcm==0) = NaN; else cc2 = cc; cc2(~bw7)=0; % Mengembalikan ke grayscale cc_resize = imresize(cc2, [256 256]); brain1 = cc_resize(cc_resize>0); brain_glcm = double(cc_resize); brain_glcm(brain_glcm==0) = NaN; end axes(handles.axes11); imshow(cc_resize); [N,M,L] = size(brain1); His2 =imhist(brain1)/(N*M); % Normalized Histogram Mean = 0; for zi = 0:255 Mean = Mean + (zi*His2(zi+1)); %Mean end set(handles.edit1,'String',Mean); Std2 = 0; for zi = 0:255 Std2 = Std2 + ((zi-Mean).^2*His2(zi+1)); end Std2 = sqrt(Std2); %Standard Deviation set(handles.edit2,'String',Std2); Ent = 0; for zi = 0:255 if His2(zi+1)>0 Ent = Ent - (His2(zi+1)*log2(His2(zi+1))); %Entropy end end set(handles.edit3,'String',Ent); % GLCM Texture Feature Extraction jarak = 1; %distance beetwen pixel warning('off','Images:graycomatrix:scaledImageContainsNan'); GLCM = graycomatrix(brain_glcm,'NumLevels',8, 'GrayLimits',[], 'Offset',[0 jarak; -jarak jarak; -jarak 0; -jarak -jarak]); stats = graycoprops(GLCM,{'contrast','homogeneity'}); warning('on','Images:graycomatrix:scaledImageContainsNan'); contrast = stats.Contrast; contrast0 = contrast(1); set(handles.edit19,'String',contrast0); contrast45 = contrast(2); set(handles.edit20,'String',contrast45); contrast90 = contrast(3); set(handles.edit21,'String',contrast90); contrast135 = contrast(4); set(handles.edit22,'String',contrast135); homogeneity = stats.Homogeneity; homogeneity0 = homogeneity(1); set(handles.edit4,'String',homogeneity0); homogeneity45 = homogeneity(2); set(handles.edit17,'String',homogeneity45); homogeneity90 = homogeneity(3); set(handles.edit5,'String',homogeneity90); homogeneity135 = homogeneity(4); set(handles.edit18,'String',homogeneity135); input = [Mean;Std2;Ent;contrast0;contrast45;contrast90;contrast135;homogeneity0;homogeneity45;homogeneity90;homogeneity135] a = 0; b = 255; ra = 0.9; rb = 0.1; norm = (((ra-rb) * (input - a)) / (b - a)) + rb load jst output = sim(net,norm) keluaran = vec2ind(output) % Find largest element in vector if keluaran == 1 kelas = 'Glioma'; %Target Class set(handles.edit6,'String',kelas); set(handles.edit6,'ForegroundColor','blue'); elseif keluaran == 2 kelas = 'Meningioma'; set(handles.edit6,'String',kelas); set(handles.edit6,'ForegroundColor','red'); elseif keluaran == 3 kelas = 'Metastatic Bronchogenic Carcinoma'; set(handles.edit6,'String',kelas); set(handles.edit6,'ForegroundColor','green'); elseif keluaran == 4 kelas = 'Normal'; set(handles.edit6,'String',kelas); set(handles.edit6,'ForegroundColor','black'); else kelas = 'Unknown'; set(handles.edit6,'String',kelas); set(handles.edit6,'ForegroundColor','cyan'); end function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (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 edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (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 edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (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 edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (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 edit3_Callback(hObject, eventdata, handles) % hObject handle to edit3 (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 edit3 as text % str2double(get(hObject,'String')) returns contents of edit3 as a double % --- Executes during object creation, after setting all properties. function edit3_CreateFcn(hObject, eventdata, handles) % hObject handle to edit3 (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 edit4_Callback(hObject, eventdata, handles) % hObject handle to edit4 (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 edit4 as text % str2double(get(hObject,'String')) returns contents of edit4 as a double % --- Executes during object creation, after setting all properties. function edit4_CreateFcn(hObject, eventdata, handles) % hObject handle to edit4 (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 edit5_Callback(hObject, eventdata, handles) % hObject handle to edit5 (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 edit5 as text % str2double(get(hObject,'String')) returns contents of edit5 as a double % --- Executes during object creation, after setting all properties. function edit5_CreateFcn(hObject, eventdata, handles) % hObject handle to edit5 (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 edit6_Callback(hObject, eventdata, handles) % hObject handle to edit6 (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 edit6 as text % str2double(get(hObject,'String')) returns contents of edit6 as a double % --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles) % hObject handle to edit6 (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 % PELATIHAN % --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, handles) % hObject handle to pushbutton5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) d = uigetdir(pwd, 'Select a folder'); files = dir(fullfile(d, '*.png')); textLabel = sprintf('%s ',d); set(handles.edit14, 'String', textLabel); total_images = numel(files) for n = 1:total_images full_name = fullfile(d, files(n).name); %Prerpocessing img = imread(full_name); img_gray=rgb2gray(img); cc = medfilt2(img_gray); %Tumor Segmentation T = 155; bw = im2bw(cc,T/255); SE = strel('disk',2); bw1 = imerode(bw,SE); bw2 = imdilate(bw1,SE); SE2 = strel('disk',4); bw3 = imerode(bw2,SE2); SE3 = strel('disk',4); bw4 = imdilate(bw3,SE3); bw6 = bwareaopen(bw4,350,8); bw6a = imfill(bw6, 'holes'); SE5 = strel('disk',3); bw7 = imdilate(bw6a,SE5); if bw7 == 0 brain1 = 255*uint8(bw7); brain_glcm = double(brain1); brain_glcm(brain_glcm==0) = NaN; else cc2 = cc; cc2(~bw7)=0; cc_resize = imresize(cc2, [256 256]); brain1 = cc_resize(cc_resize>0); brain_glcm = double(cc_resize); brain_glcm(brain_glcm==0) = NaN; end [N,M,L] = size(brain1); His2 =imhist(brain1)/(N*M); % Normalized Histogram Mean(n) = 0; for zi = 0:255 Mean(n) = Mean(n) + (zi*His2(zi+1)); %Mean end Std2(n) = 0; for zi = 0:255 Std2(n) = Std2(n) + ((zi-Mean(n)).^2*His2(zi+1)); end Std2(n) = sqrt(Std2(n)); %Standard Deviation Ent(n) = 0; for zi = 0:255 if His2(zi+1)>0 Ent(n) = Ent(n) - (His2(zi+1)*log2(His2(zi+1))); %Entropy end end %%Gray Level Coocurence Matrix (GLCM) Texture Feature Extraction jarak = 1; warning('off','Images:graycomatrix:scaledImageContainsNan'); GLCM = graycomatrix(brain_glcm,'NumLevels',8, 'GrayLimits',[], 'Offset',[0 jarak; -jarak jarak; -jarak 0; -jarak -jarak]); stats = graycoprops(GLCM,{'contrast','homogeneity'}); warning('on','Images:graycomatrix:scaledImageContainsNan'); contrast = stats.Contrast; contrast0(n) = contrast(1); contrast45(n) = contrast(2); contrast90(n) = contrast(3); contrast135(n) = contrast(4); homogeneity = stats.Homogeneity; homogeneity0(n) = homogeneity(1); homogeneity45(n) = homogeneity(2); homogeneity90(n) = homogeneity(3); homogeneity135(n) = homogeneity(4); end input = [Mean;Std2;Ent;contrast0;contrast45;contrast90;contrast135;homogeneity0;homogeneity45;homogeneity90;homogeneity135] [~,N] = size(input); t1 = [1;0;0;0]; %Glioma t2 = [0;1;0;0]; %Meningioma t3 = [0;0;1;0]; %Metastatic t4 = [0;0;0;1]; %Normal target = [t1 t1 t1 t1 t1 t1 t1 t1 t1 t1 t1 t1 t1 t2 t2 t2 t3 t3 t3 t3 t3 t3 t3 t4 t4 t4 t4 t4 t4 t4 t4 t4 t4 t4 t4] rng(27); a = 0; b = 255; ra = 0.9; rb = 0.1; pa = (((ra-rb) * (input - a)) / (b - a)) + rb %train using BPNN net = newff(pa,target,str2double(get(handles.edit27,'String')),{'logsig','tansig'},'traingd'); %Desain Jaringan % net.IW{1,1} = [-0.1920,-0.4876,-1.1113,1.3023,1.1390;... % 1.7783,-0.5090,-0.6322,0.8257,0.0001;... % 0.1504,1.5682,0.5776,1.2974,-0.0645;... % 0.0551,-1.2048,-0.9473,1.0189,1.0549;... % -1.0248,1.4706,0.8446,-0.6332,0.4195;... % -0.0383,1.4274,-1.3556,0.6851,0.4056;... % 0.4467,1.0665,0.5537,-1.0882,1.2943;... % 0.5339,-1.1961,-0.0174,-1.3992,0.9105]; % % net.b{1,1} = [2.1220;-1.5157;-0.9094;-0.3031;-0.3031;-0.9094;1.5157;2.1220]; % % net.LW{2,1} = [0.1534,-0.6342,-0.5201,0.7730,-0.9427,-0.0202,-0.6641,0.9574]; % % net.b{2,1} = [0.4254]; bobot_hidden1 = net.IW{1,1} bias_hidden1 = net.b{1,1} bobot_keluaran1 = net.LW{2,1} bias_keluaran1 = net.b{2,1} net.trainParam.showWindow = true; net.trainParam.showCommandLine = true; net.trainParam.epochs = str2double(get(handles.edit25,'String')); net.performFcn = 'mse'; net.trainParam.lr = str2double(get(handles.edit26,'String')); net.trainParam.goal = 0.02; net.divideFcn = ''; [net, tr, Y, ee] = train(net,pa,target); output = sim(net,pa) trainIndices = vec2ind(output) hasilbobot_hidden = net.IW{1,1} hasilbias_hidden = net.b{1,1} hasilbobot_keluaran = net.LW{2,1} hasilbias_keluaran = net.b{2,1} jumlah_iterasi = tr.num_epochs %number of iteration nilai_keluaran = Y %output value nilai_error = ee %error value D = abs(nilai_error).^2; error_MSE = sum(D(:))/numel(nilai_error) set(handles.edit24,'String',error_MSE); save jst.mat net function edit14_Callback(hObject, eventdata, handles) % hObject handle to edit14 (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 edit14 as text % str2double(get(hObject,'String')) returns contents of edit14 as a double % --- Executes during object creation, after setting all properties. function edit14_CreateFcn(hObject, eventdata, handles) % hObject handle to edit14 (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 edit15_Callback(hObject, eventdata, handles) % hObject handle to edit15 (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 edit15 as text % str2double(get(hObject,'String')) returns contents of edit15 as a double % --- Executes during object creation, after setting all properties. function edit15_CreateFcn(hObject, eventdata, handles) % hObject handle to edit15 (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 edit16_Callback(hObject, eventdata, handles) % hObject handle to edit16 (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 edit16 as text % str2double(get(hObject,'String')) returns contents of edit16 as a double % --- Executes during object creation, after setting all properties. function edit16_CreateFcn(hObject, eventdata, handles) % hObject handle to edit16 (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 edit17_Callback(hObject, eventdata, handles) % hObject handle to edit17 (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 edit17 as text % str2double(get(hObject,'String')) returns contents of edit17 as a double % --- Executes during object creation, after setting all properties. function edit17_CreateFcn(hObject, eventdata, handles) % hObject handle to edit17 (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 edit18_Callback(hObject, eventdata, handles) % hObject handle to edit18 (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 edit18 as text % str2double(get(hObject,'String')) returns contents of edit18 as a double % --- Executes during object creation, after setting all properties. function edit18_CreateFcn(hObject, eventdata, handles) % hObject handle to edit18 (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 edit19_Callback(hObject, eventdata, handles) % hObject handle to edit19 (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 edit19 as text % str2double(get(hObject,'String')) returns contents of edit19 as a double % --- Executes during object creation, after setting all properties. function edit19_CreateFcn(hObject, eventdata, handles) % hObject handle to edit19 (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 edit20_Callback(hObject, eventdata, handles) % hObject handle to edit20 (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 edit20 as text % str2double(get(hObject,'String')) returns contents of edit20 as a double % --- Executes during object creation, after setting all properties. function edit20_CreateFcn(hObject, eventdata, handles) % hObject handle to edit20 (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 edit21_Callback(hObject, eventdata, handles) % hObject handle to edit21 (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 edit21 as text % str2double(get(hObject,'String')) returns contents of edit21 as a double % --- Executes during object creation, after setting all properties. function edit21_CreateFcn(hObject, eventdata, handles) % hObject handle to edit21 (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 edit22_Callback(hObject, eventdata, handles) % hObject handle to edit22 (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 edit22 as text % str2double(get(hObject,'String')) returns contents of edit22 as a double % --- Executes during object creation, after setting all properties. function edit22_CreateFcn(hObject, eventdata, handles) % hObject handle to edit22 (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 edit24_Callback(hObject, eventdata, handles) % hObject handle to edit24 (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 edit24 as text % str2double(get(hObject,'String')) returns contents of edit24 as a double % --- Executes during object creation, after setting all properties. function edit24_CreateFcn(hObject, eventdata, handles) % hObject handle to edit24 (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 edit25_Callback(hObject, eventdata, handles) % hObject handle to edit25 (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 edit25 as text % str2double(get(hObject,'String')) returns contents of edit25 as a double % --- Executes during object creation, after setting all properties. function edit25_CreateFcn(hObject, eventdata, handles) % hObject handle to edit25 (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 edit26_Callback(hObject, eventdata, handles) % hObject handle to edit26 (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 edit26 as text % str2double(get(hObject,'String')) returns contents of edit26 as a double % --- Executes during object creation, after setting all properties. function edit26_CreateFcn(hObject, eventdata, handles) % hObject handle to edit26 (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 edit27_Callback(hObject, eventdata, handles) % hObject handle to edit27 (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 edit27 as text % str2double(get(hObject,'String')) returns contents of edit27 as a double % --- Executes during object creation, after setting all properties. function edit27_CreateFcn(hObject, eventdata, handles) % hObject handle to edit27 (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
github
HongtengXu/Quaternion-Sparse-Coding-master
Qmult.m
.m
Quaternion-Sparse-Coding-master/Quaternion dictionary training in KQSVD/Qmult.m
612
utf_8
4e983c570ce27c601be1085012e07d1b
% input a and b are quaternion matrices % output y is also a quaternion matrix, which is the result of the % multiplication of input a and b function y = Qmult(a,b) [ax, ay] = size(a(:,:,1)); [bx, by] = size(b(:,:,1)); y = zeros(ax, by, 4); y(:,:,1) = a(:,:,1)*b(:,:,1) - a(:,:,2)*b(:,:,2) - a(:,:,3)*b(:,:,3) - a(:,:,4)*b(:,:,4); y(:,:,2) = a(:,:,1)*b(:,:,2) + a(:,:,2)*b(:,:,1) + a(:,:,3)*b(:,:,4) - a(:,:,4)*b(:,:,3); y(:,:,3) = a(:,:,1)*b(:,:,3) + a(:,:,3)*b(:,:,1) + a(:,:,4)*b(:,:,2) - a(:,:,2)*b(:,:,4); y(:,:,4) = a(:,:,1)*b(:,:,4) + a(:,:,4)*b(:,:,1) + a(:,:,2)*b(:,:,3) - a(:,:,3)*b(:,:,2);
github
HongtengXu/Quaternion-Sparse-Coding-master
Qmult.m
.m
Quaternion-Sparse-Coding-master/Color Image denoising using KQSVD/Qmult.m
612
utf_8
4e983c570ce27c601be1085012e07d1b
% input a and b are quaternion matrices % output y is also a quaternion matrix, which is the result of the % multiplication of input a and b function y = Qmult(a,b) [ax, ay] = size(a(:,:,1)); [bx, by] = size(b(:,:,1)); y = zeros(ax, by, 4); y(:,:,1) = a(:,:,1)*b(:,:,1) - a(:,:,2)*b(:,:,2) - a(:,:,3)*b(:,:,3) - a(:,:,4)*b(:,:,4); y(:,:,2) = a(:,:,1)*b(:,:,2) + a(:,:,2)*b(:,:,1) + a(:,:,3)*b(:,:,4) - a(:,:,4)*b(:,:,3); y(:,:,3) = a(:,:,1)*b(:,:,3) + a(:,:,3)*b(:,:,1) + a(:,:,4)*b(:,:,2) - a(:,:,2)*b(:,:,4); y(:,:,4) = a(:,:,1)*b(:,:,4) + a(:,:,4)*b(:,:,1) + a(:,:,2)*b(:,:,3) - a(:,:,3)*b(:,:,2);
github
CU-UQ/BASE_PC-master
mcmc_sampler.m
.m
BASE_PC-master/base_pc_v1/sampler/mcmc_sampler.m
4,322
utf_8
3fed14a180a022ec214c0720e115a9ff
% generates samples via mcmc for sample initialization % ----- % sample = mcmc_sampler(sample, basis, n_samps, sample_opt, eval_opt) % ----- % Input % ----- % sample = sample object % basis = basis object % n_samps = number of samples to generate % samp_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object function sample = mcmc_sampler(sample, basis, n_samps, sample_opt, eval_opt) t_samps = ceil(n_samps/sample_opt.n_workers); spmd (sample_opt.n_workers) [lhs, rv, w, p, p_rat, rej_rate, rej_con, rej_con_history, n_tries] = serial_mcmc_init(basis, t_samps, sample.rej_rate, sample.rej_con, sample.n_tries, sample_opt, eval_opt); end n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; sample.lhs = cell2mat(lhs(:)); sample.lhs = sample.lhs(1:(n_rows*n_samps),:); sample.rv = cell2mat(rv(:)); sample.rv = sample.rv(1:n_samps,:); sample.p = cell2mat(p(:)); sample.p = sample.p(1:n_samps); sample.w = cell2mat(w(:)); sample.w = sample.w(1:n_samps); sample.p_rat = cell2mat(p_rat(:)); sample.p_rat = sample.p_rat(1:n_samps,:); sample.rej_con_history = cell2mat(rej_con_history(:)); sample.rej_con_history = sample.rej_con_history(1:n_samps); sample.n_samps = n_samps; sample.wlhs = apply_weights(sample.w,sample.lhs); sample.rej_rate = sum(cell2mat(rej_rate(:)))/sample_opt.n_workers; % rejection rate estimates sample.rej_con = cell2mat(rej_con(randi(sample_opt.n_workers))); % rej_con from random chain (accelerates any future sampling) sample.n_tries = sum(cell2mat(n_tries(:))); % Number of tries used to compute rejection rate end function [lhs, rv, w, p, p_rat, rej_rate, rej_con, rej_con_history, n_tries] = serial_mcmc_init(basis, n_samps, rej_rate, rej_con, n_tries, samp_opt, eval_opt) n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; lhs = zeros(n_samps*n_rows,basis.n_elems); rv = zeros(n_samps,eval_opt.max_dim); w = zeros(n_samps,1); p = zeros(n_samps,1); p_rat = zeros(n_samps,1); rej_con_history = zeros(n_samps,1); cur_samp = []; cur_samp.rej_con = rej_con; rej_s = 0; for k = 1:samp_opt.burn_in % Initial opt.burn_in tunes sampler. These samples are not kept. [cur_samp, rej] = mcmc_try(basis, cur_samp, samp_opt, eval_opt); rej_s = rej_s + rej; end rej_rate = rej_rate*n_tries/(n_tries+samp_opt.burn_in)+ rej_s/(n_tries+samp_opt.burn_in); n_tries = n_tries + samp_opt.burn_in; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); serial_red = min(serial_red,samp_opt.burn_in); for k = 1:n_samps % Generate samples to keep while true % Remove Collision based duplicates rej_s = 0; for kkk = 1:serial_red; % Reduces serial correlation [cur_samp, rej] = mcmc_try(basis, cur_samp, samp_opt, eval_opt); rej_s = rej_s + rej; end rej_rate = rej_rate*n_tries/(n_tries+serial_red)+ rej_s/(n_tries+serial_red); % Adjustment to rejection rate n_tries = n_tries+serial_red; serial_red_old = serial_red; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); if(rej_s < serial_red_old) % We don't keep duplicated samples break end end lhs((1+(k-1)*n_rows:k*n_rows),:) = cur_samp.lhs; rv(k,:) = cur_samp.rv; w(k) = cur_samp.w; p(k) = cur_samp.p; p_rat(k) = cur_samp.p_rat; rej_con_history(k) = cur_samp.rej_con; rej_con = cur_samp.rej_con; end end function [cur_samp, rej] = mcmc_try(basis, cur_samp, sample_opt, eval_opt) [t_rv, t_p, p_rat] = sample_opt.prop_handle(sample_opt, eval_opt); t_lhs = basis_eval(basis,t_rv,eval_opt); t_w = sample_opt.w_handle(t_lhs, t_rv, t_p, p_rat, sample_opt); % Many things potentially useful for weight evalution tc = (t_w)^(-2)/p_rat; rej = 1; % return 1 if rejected if rand < tc/cur_samp.rej_con % rejection decision cur_samp.lhs = t_lhs; cur_samp.w = t_w; cur_samp.p = t_p; cur_samp.p_rat = p_rat; cur_samp.rv = t_rv; cur_samp.rej_con = tc; rej = 0; % return 0 if accepeted end end
github
CU-UQ/BASE_PC-master
sample_expand.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_expand.m
4,990
utf_8
6c3eac20ae823b7d8d26754c12d08018
% applies correction sampling to sample_old % ----- % sample_new = sample_expand(basis, sample_old, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample_old = sample object % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample_new = sample object with correction sampling function sample_new = sample_expand(basis, sample_old, sample_opt, eval_opt) % Expands samples for new basis % generate additional samples for new basis sample_new = sample_init(basis, sample_opt, eval_opt); % Need normalizing constant for new sample to adjust several paraemeters full_samps = ceil(basis.n_elems*sample_opt.min_sample_percent); % Number of samples after adjustment trans_samps = max(ceil(sample_old.n_samps*sample_opt.min_sample_percent),full_samps - sample_old.n_samps); % Number of transition samples is at least a fraction of the number of available samples max_samps = min(sample_opt.max_samps,ceil(sample_old.n_samps*sample_opt.max_sample_percent)); % Maximum number of samples based on number of available samples full_samps = sample_old.n_samps + trans_samps; % This is the actual sample size that is kept actual_alpha = sample_old.n_samps/full_samps; % This is the actual alpha, the fraction of old samples sample_opt.ac = actual_alpha*sample_old.nc/sample_new.nc; % Adjustment constant (alpha) for adjusting sample adj_con = sample_opt.ac; % Will be adjusted as needed % Test if further corrections needed sample_trans.rej_con = 0; % Initialize value for rej_con (0 implies chain initialization) sample_trans.rej_rate = 0; % Initialize value for rej_rate sample_trans.n_tries = 0; % Initialize number of tries. Is used to compute rejection rate. flag = 1; while flag [sample_trans, flag] = mcmc_correction_sampler(sample_trans, basis, trans_samps, sample_opt, eval_opt); % If goes through, then all samples are adjusted if flag % Sampling not enough to adjust sample_opt.ac = flag; sample_trans.rej_con = 0; % Reset value sample_trans.rej_rate = 0; % Reset value sample_trans.n_tries = 0; % Reset number of tries. % Adjusts sample size towards maximum or what ac suggests if trans_samps < max_samps % No need to check if trans_samps >= max_samps prop_rate = (trans_samps*adj_con/sample_opt.ac)/sample_old.n_samps; fprintf('Increasing Sample Size. Proposed Sample Rate: %f\n', prop_rate) test_val = ceil(trans_samps*adj_con/sample_opt.ac); % Would be our new number of samples if test_val >= max_samps; trans_samps = max_samps; % We can only sample up to max_samps full_samps = sample_old.n_samps + trans_samps; % full_samps is adjusted actual_alpha = sample_old.n_samps/full_samps; % actual_alpha is adjusted adj_con = (actual_alpha*sample_old.nc/sample_new.nc); % New adjusting constant has hit its maximum fprintf('Maximum Sample Size Exceeded for Perfect Correction.\n') else trans_samps = test_val; % Adjust up to test_val samps full_samps = sample_old.n_samps + trans_samps; % full_samps is adjusted actual_alpha = sample_old.n_samps/full_samps; % actual_alpha is adjusted adj_con = (actual_alpha*sample_old.nc/sample_new.nc); % New adjusting constant for sample sample_opt.ac = adj_con; % because ac is slightly bigger than needed for integerizing. end end end end adj_con = sample_opt.ac/adj_con; % For weight correction, if ac smaller, than some effective sampling lost % Concatenate samples sample_new.n_samps = full_samps; sample_new.lhs = vertcat(sample_old.lhs, sample_trans.lhs); % Important that sample_old.lhs has been adjusted to new basis sample_new.rv = vertcat(sample_old.rv, sample_trans.rv); sample_new.p = vertcat(sample_old.p,sample_trans.p); % These numbers will not change sample_new.p_rat = vertcat(sample_old.p_rat,sample_trans.p_rat); % These numbers are kept to numbers at the time of sampling sample_new.rej_con_history = vertcat(sample_old.rej_con_history,sample_trans.rej_con_history); % These numbers are kept to numbers at the time of sampling sample_new.w = vertcat(adj_con*sample_old.w*sample_old.nc, sample_trans.w)/sample_new.nc; % Important that sample_old.w has been adjusted to new basis sample_old.w already normalized by normalizing constant sample_new.wlhs = apply_weights(sample_new.w,sample_new.lhs); % apply weights sample_new.rhs = vertcat(sample_old.rhs,eval_opt.qoi_handle(sample_trans.rv,eval_opt)); % Old rhs plus new evaluations sample_new.wrhs = apply_weights(sample_new.w,sample_new.rhs); % apply weights end
github
CU-UQ/BASE_PC-master
sample_adjust.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_adjust.m
888
utf_8
637cfdf3e5745bc2c3a5d6b903521cf6
% adjusts sample for use with basis % ----- % sample = sample_adjust(basis, sample, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample_old = sample object % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object adjusted to basis function sample = sample_adjust(basis, sample, sample_opt, eval_opt) sample.lhs = basis_eval(basis,sample.rv,eval_opt); n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; for k = 1:sample.n_samps; sample.w(k) = sample_opt.w_handle(sample.lhs((1+(k-1)*n_rows:k*n_rows),:), sample.rv(k,:), sample.p(k), sample.p_rat(k), sample_opt); sample.w(k) = sample.w(k)/sample.nc; end sample.wlhs = apply_weights(sample.w,sample.lhs); % Apply weights sample.wrhs = apply_weights(sample.w,sample.rhs); % Apply weights end
github
CU-UQ/BASE_PC-master
rv_gen.m
.m
BASE_PC-master/base_pc_v1/sampler/rv_gen.m
1,514
utf_8
e0291daf017d6ec6eccc149e4f94bcff
% Generates random variable from orthogonality distribution (no importance sampling) % ----- % [rv, p] = rv_gen(opt) % ----- % Input % ----- % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % rv = random vector % p = probability of draw function [rv,p] = rv_gen(eval_opt) rv = zeros(1,eval_opt.max_dim); p = 1; for kk = 1: eval_opt.max_dim % Generate test random variable switch eval_opt.p_type(kk) case 'H' % hermite/normal with scale/location rv(kk) = randn; p = p*normpdf(rv(kk)); rv(kk) = rv(kk)*eval_opt.sig(kk) + eval_opt.mu(kk); case 'h' % hermite/normal rv(kk) = randn; p = p*normpdf(rv(kk)); case 'l' % Legendre for uniform [0,1] rv(kk) = rand; case 'L' % Legendre for uniform [-1,1] rv(kk) = 2*rand-1; p = 1/2*p; % Uniform rv on [-1,1] case 'a' % laguerre/gamma rv(kk) = gamrnd(eval_opt.alpha(kk),1); p = p*gampdf(rv(kk),eval_opt.alpha(kk),1); case 'j' % jacobi/beta [-1,1] rv(kk) = betarnd(eval_opt.beta(kk)+1,eval_opt.alpha(kk)+1); % Not yet stretched to [-1, 1] p = p*0.5*betapdf(rv(kk),eval_opt.alpha(kk),eval_opt.beta(kk)); % Half probability due to stretch rv(kk) = 2*rv(kk)-1; % Jacobi rv we place in [-1,1] here, as opposed to the legendre rv. end end end
github
CU-UQ/BASE_PC-master
sample_init.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_init.m
1,673
utf_8
6ffeb22a5d108b87a783ff0add89fbc5
% constructs sample opbject % ----- % sample = sample_init(basis, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object function sample = sample_init(basis, sample_opt, eval_opt) n_samps = ceil(sample_opt.initial_size); % Number of samples initially is predefined as often initial basis warrants different sampling rate. nc_old = 0; sample.rej_con = 0; % Initialize value for rej_con (0 implies chain initialization) sample.rej_rate = 0; % Initialize value for rej_rate sample.n_tries = 0; % Initialize number of tries. Is used to compute rejection rate. w = []; while true sample = mcmc_sampler(sample, basis, n_samps, sample_opt, eval_opt); w = vertcat(w,sample.w); %#ok<AGROW> nc_new = norm(w,2)/size(w,1); % Normalizing constant estimate for working with sampling distribution if (nc_new-nc_old)/nc_old < 0.001 % Guages convergence of chain and normalizing constant estimation. Convergence criteria loosens as sampling increases. sample.nc = nc_new; % This constant is not often needed to be very accurate to insure quality sampling, if expensive to evaluate. break end nc_old = nc_new; end sample.w = sample.w/sample.nc; % Adjust weights to .nc sample.wlhs = sample.wlhs/sample.nc; % Adjust weights to .nc sample.rhs = eval_opt.qoi_handle(sample.rv,eval_opt);%qoi_eval(sample_trans.rv,eval_opt)); % Old rhs plus new evaluations sample.wrhs = sample.w.*sample.rhs; % Weights applied end
github
CU-UQ/BASE_PC-master
orth_sampler.m
.m
BASE_PC-master/base_pc_v1/sampler/orth_sampler.m
1,330
utf_8
c2bebcfd3b01de5153e0939b11aa265b
% constructs sample object through sampling of orthogonality distribution % ----- % sample = orth_sampler(basis, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample_opt = options for sampling inputs % sample_opt.n_workers = number of workers in pool % sample_opt.initial_size = number of samples to generate % eval_opt = options for evaluating input and QoI % eval_opt.max_dim = maximum dimension of the problem % eval_opt.qoi_handle = for rhs evaluations % ------ % Output % ------ % sample = sample object function sample = orth_sampler(sample_opt, eval_opt) n_samps = ceil(sample_opt.initial_size); % number of samples initially is predefined as often initial basis warrants different sampling rate t_samps = ceil(n_samps/sample_opt.n_workers); spmd (sample_opt.n_workers) rv = zeros(t_samps,eval_opt.max_dim); p = zeros(t_samps,1); for k = 1:t_samps [rv(k,:),p(k)] = rv_gen(eval_opt); end end sample.rv = cell2mat(rv(:)); sample.rv = sample.rv(1:n_samps,:); sample.p = cell2mat(p(:)); sample.p = sample.p(1:n_samps,:); sample.p_rat = ones(n_samps,1); % Sampling from ortho dist always gives p_rat = 1 sample.rhs = eval_opt.qoi_handle(sample.rv,eval_opt); % rhs evaluations sample.n_samps = n_samps; end
github
CU-UQ/BASE_PC-master
mcmc_sampler_with_flag.m
.m
BASE_PC-master/base_pc_v1/sampler/mcmc_sampler_with_flag.m
3,816
utf_8
f089dbb3b46950a0b9b1cbb4c1b436ac
% generates samples via mcmc with potential to flow flags in weight evaluation % ----- % [sample,flag] = mcmc_sampler_with_flag(basis, n_samps, samp_opt, eval_opt) % ----- % Input % ----- % basis = basis object % n_samps = number of samples to generate % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object % flag = flag returned by weight function to indicate insufficient samples for adaptation function [sample,flag] = mcmc_sampler_with_flag(basis, n_samps, samp_opt, eval_opt) t_samps = ceil(n_samps/samp_opt.n_workers); spmd (samp_opt.n_workers) [lhs, rv, w, p, flag] = serial_mcmc_init(basis,t_samps, samp_opt, eval_opt); end if sum(flag ~= 0) % Return if any flags non-zero sample = []; return end n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; sample.lhs = cell2mat(lhs(:)); sample.lhs = sample.lhs(1:(n_rows*n_samps),:); sample.rv = cell2mat(rv(:)); sample.rv = sample.rv(1:n_samps,:); sample.p = cell2mat(p(:)); sample.p = sample.p(1:n_samps); sample.w = cell2mat(w(:)); sample.w = sample.w(1:n_samps); sample.n_samps = n_samps; set1 = 1:n_rows; sample.wlhs = zeros(n_samps*n_rows,basis.n_elems); for k = 1:n_samps sample.wlhs(set1,:) = sample.w(k)*sample.lhs(set1,:); set1 = set1+n_rows; end end function [lhs, rv, w, p, rej_rate, flag] = serial_mcmc_init(basis, n_samps, samp_opt, eval_opt) flag = []; rej_rate = 0; % rejection rate turns serial_red n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; lhs = zeros(n_samps*n_rows,basis.n_elems); w = zeros(n_samps,1); p = zeros(n_samps,1); rv = zeros(n_samps,eval_opt.max_dim); cur_samp.rej_con = 0; b = []; for k = 1:samp_opt.burn_in % Initial opt.burn_in tunes sampler. [cur_samp, rej, flag] = mcmc_try(basis, cur_samp, samp_opt); if flag return end rej_rate = rej_rate + rej; end rej_rate = rej_rate/samp_opt.burn_in; n_tries = samp_opt.burn_in; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); serial_red = min(serial_red,samp_opt.burn_in); for k = 1:n_samps % Generate samples to keep while true % Remove Collision based duplicates rej_s = 0; for kkk = 1:serial_red; % Reduces serial correlation [b, rej_con, rej, flag] = mcmc_try(basis, b, rej_con, samp_opt); if flag return end rej_s = rej_s + rej; end rej_rate = rej_rate*n_tries/(n_tries+serial_red)+ rej_s/(n_tries+serial_red); % Adjustment to rejection rate n_tries = n_tries+serial_red; serial_red_old = serial_red; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); if(rej_s < serial_red_old) break end end lhs((1+(k-1)*n_rows:k*n_rows),:) = b.lhs; rv(k,:) = b.rv; w(k) = b.w; p(k) = b.p; end end function [cur_samp, rej, flag] = mcmc_try(basis, cur_samp, samp_opt, eval_opt) [t_rv,t_p, p_rat] = samp_opt.prop_handle(samp_opt); t_lhs = basis_eval(basis,t_rv,eval_opt); old_lhs = basis_eval(sample_opt.old_basis,t_rv,eval_opt); [t_w,flag] = sample_opt.w_handle(t_lhs, old_lhs, t_rv, t_p, p_rat, sample_opt); % Many things potentially useful for weight evalution tc = p_rat^2*(t_w)^(-2); rej = 1; % return 1 if rejected if rand < tc/cur_samp.tcp % rejection decision cur_samp.lhs = t_lhs; cur_samp.w = t_w; cur_samp.p = t_p; cur_samp.rv = t_rv; cur_samp.rej_con = tc; rej = 0; % return 0 if accepeted end end
github
CU-UQ/BASE_PC-master
sample_identify.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_identify.m
796
utf_8
8a8698b98d6d0ac74b07be10d0ab6f1f
% updates sample object % ----- % sample = sample_identify(basis, sample, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample = sample object % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object function sample = sample_identify(basis, sample, sample_opt, eval_opt) sample_opt.old_basis = basis; % Old basis needed to correct samples sample = sample_adjust(basis, sample, sample_opt, eval_opt); % Adjusts old samples to new basis, applies correction weights sample = sample_expand(basis, sample, sample_opt, eval_opt); % Expands samples for new basis sampling, using correction sampling sample = folds_identify(sample, solver_opt); % Identification of folds end
github
CU-UQ/BASE_PC-master
mcmc_correction_sampler.m
.m
BASE_PC-master/base_pc_v1/sampler/mcmc_correction_sampler.m
4,763
utf_8
01aa40ce88fad56dbfdc1ef9f3878e52
% generates samples via mcmc for sample correction % ----- % [sample, flag] = mcmc_sampler_basis_correction(sample, basis, n_samps, sample_opt, eval_opt) % ----- % Input % ----- % sample = sample object % basis = basis object % n_samps = number of samples to generate % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % sample = sample object % flag = flag returned by weight function indicating impossible exact correction function [sample, flag] = mcmc_correction_sampler(sample, basis, n_samps, sample_opt, eval_opt) t_samps = ceil(n_samps/sample_opt.n_workers); spmd (sample_opt.n_workers) [lhs, rv, w, p, p_rat, rej_rate, rej_con, rej_con_history, n_tries, flag] = serial_mcmc_init(basis, t_samps, sample.rej_rate, sample.rej_con, sample.n_tries, sample_opt, eval_opt); end flag = max(cell2mat(flag(:))); % To get appropriate value returned if flag % Invert if non-zero flag = 1/flag; % Return smallest of inverse flags end n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; sample.lhs = cell2mat(lhs(:)); sample.lhs = sample.lhs(1:(n_rows*n_samps),:); sample.rv = cell2mat(rv(:)); sample.rv = sample.rv(1:n_samps,:); sample.p = cell2mat(p(:)); sample.p = sample.p(1:n_samps); sample.w = cell2mat(w(:)); sample.w = sample.w(1:n_samps); sample.p_rat = cell2mat(p_rat(:)); sample.p_rat = sample.p_rat(1:n_samps,:); sample.rej_con_history = cell2mat(rej_con_history(:)); sample.rej_con_history = sample.rej_con_history(1:n_samps); sample.n_samps = n_samps; sample.wlhs = apply_weights(sample.w,sample.lhs); sample.rej_rate = sum(cell2mat(rej_rate(:)))/sample_opt.n_workers; % rejection rate estimates sample.rej_con = cell2mat(rej_con(randi(sample_opt.n_workers))); % rej_con from random chain (accelerates any future sampling) sample.n_tries = sum(cell2mat(n_tries(:))); % Number of tries used to compute rejection rate end function [lhs, rv, w, p, p_rat, rej_rate, rej_con, rej_con_history, n_tries, flag] = serial_mcmc_init(basis, n_samps, rej_rate, rej_con, n_tries, samp_opt, eval_opt) n_rows = min(eval_opt.grad_dim,basis.n_dim)+1; lhs = zeros(n_samps*n_rows,basis.n_elems); rv = zeros(n_samps,eval_opt.max_dim); w = zeros(n_samps,1); p = zeros(n_samps,1); p_rat = zeros(n_samps,1); rej_con_history = zeros(n_samps,1); cur_samp = []; cur_samp.rej_con = rej_con; rej_s = 0; for k = 1:samp_opt.burn_in % Initial opt.burn_in tunes sampler. These samples are not kept. [cur_samp, rej, flag] = mcmc_try(basis, cur_samp, samp_opt, eval_opt); if flag return end rej_s = rej_s + rej; end rej_rate = rej_rate*n_tries/(n_tries+samp_opt.burn_in)+ rej_s/(n_tries+samp_opt.burn_in); n_tries = n_tries + samp_opt.burn_in; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); serial_red = min(serial_red,samp_opt.burn_in); for k = 1:n_samps % Generate samples to keep while true % Remove Collision based duplicates rej_s = 0; for kkk = 1:serial_red; % Reduces serial correlation [cur_samp, rej, flag] = mcmc_try(basis, cur_samp, samp_opt, eval_opt); if flag return end rej_s = rej_s + rej; end rej_rate = rej_rate*n_tries/(n_tries+serial_red)+ rej_s/(n_tries+serial_red); % Adjustment to rejection rate n_tries = n_tries+serial_red; serial_red_old = serial_red; serial_red = max(1,ceil(samp_opt.log_col_rate/log(rej_rate))); if(rej_s < serial_red_old) break end end lhs((1+(k-1)*n_rows:k*n_rows),:) = cur_samp.lhs; rv(k,:) = cur_samp.rv; w(k) = cur_samp.w; p(k) = cur_samp.p; p_rat(k) = cur_samp.p_rat; rej_con_history(k) = cur_samp.rej_con; rej_con = cur_samp.rej_con; end end function [cur_samp, rej, flag] = mcmc_try(basis, cur_samp, sample_opt, eval_opt) [t_rv,t_p, p_rat] = sample_opt.prop_handle(sample_opt, eval_opt); t_lhs = basis_eval(basis,t_rv,eval_opt); old_lhs = basis_eval(sample_opt.old_basis,t_rv,eval_opt); [t_w, t_c, flag] = sample_opt.w_correction_handle(t_lhs,old_lhs,t_rv,t_p, p_rat, sample_opt); tc = p_rat^(-1)*t_c; rej = 1; % return 1 if rejected if rand < tc/cur_samp.rej_con % rejection decision cur_samp.lhs = t_lhs; cur_samp.w = t_w; cur_samp.p = t_p; cur_samp.p_rat = p_rat; cur_samp.rv = t_rv; cur_samp.rej_con = tc; rej = 0; % return 0 if accepeted end end
github
CU-UQ/BASE_PC-master
proposal_sampler.m
.m
BASE_PC-master/base_pc_v1/sampler/proposal_sampler.m
1,477
utf_8
1efb3c649c639a4a8d4c1f2839ab15ba
% constructs sample object through sampling of specified distribution % ----- % sample = proposal_sampler(basis, sample_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample_opt = options for sampling inputs % sample_opt.n_workers = number of workers in pool % sample_opt.initial_size = number of samples to generate % sample_opt.prop_handle = distribution go generate samples from % eval_opt = options for evaluating input and QoI % eval_opt.max_dim = maximum dimension of the problem % eval_opt.qoi_handle = for rhs evaluations % ------ % Output % ------ % sample = sample object function sample = proposal_sampler(sample_opt, eval_opt) n_samps = ceil(sample_opt.initial_size); % Number of samples initially is predefined as often initial basis warrants different sampling rate t_samps = ceil(n_samps/sample_opt.n_workers); spmd (sample_opt.n_workers) rv = zeros(t_samps,eval_opt.max_dim); p = zeros(t_samps,1); p_rat = zeros(t_samps,1); for k = 1:t_samps [rv(k,:), p(k), p_rat(k)] = sample_opt.prop_handle(sample_opt, eval_opt); end end sample.rv = cell2mat(rv(:)); sample.rv = sample.rv(1:n_samps,:); sample.p = cell2mat(p(:)); sample.p = sample.p(1:n_samps,:); sample.p_rat = cell2mat(p_rat(:)); sample.p_rat = sample.p_rat(1:n_samps,:); sample.rhs = eval_opt.qoi_handle(sample.rv,eval_opt); % rhs evaluations sample.n_samps = n_samps; end
github
CU-UQ/BASE_PC-master
orth_prop.m
.m
BASE_PC-master/base_pc_v1/sampler/proposals/orth_prop.m
598
utf_8
1b8faf0a6b676b9c97a772408bb10b0a
% proposal distribution based on orthogonality distribution % ----- % [rv,p,p_rat] = orth_prop(sample_opt, eval_opt) % ----- % Input % ----- % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % rv = sampled inputs % p = probability of sample in orthogonality distribution. Used for diagnostics % p_rat = ratio of proposal distribution over orthogonality distribution. Used for MCMC sampler function [rv,p,p_rat] = orth_prop(~, eval_opt) [rv,p] = rv_gen(eval_opt); p_rat=1; % ratio is 1 for orthogonality distribution end
github
CU-UQ/BASE_PC-master
asym_prop.m
.m
BASE_PC-master/base_pc_v1/sampler/proposals/asym_prop.m
2,390
utf_8
52af04e11e75008324d656c8426e27c8
% proposal distribution based on asymptotically motivated distributions depending on inputs % ----- % [rv,p,p_rat] = asym_prop(sample_opt, eval_opt) % ----- % Input % ----- % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % rv = sampled inputs % p = probability of sample in orthogonality distribution. Used for diagnostics % p_rat = ratio of proposal distribution over orthogonality distribution. Used for MCMC sampler function [rv,p,p_rat] = asym_prop(sample_opt, eval_opt) rv = zeros(1,eval_opt.max_dim); p = 1; p_rat = 1; for k = 1: eval_opt.max_dim %% Generate test random variable switch eval_opt.p_type(k) case 'h' % hermite/normal Asymp approx is uniform (Note this is individual dimension `asymptotic', and not even true asymptotic) r = sqrt(2)*sqrt(2*sample_opt.order(k)+2); % radius, provides diameter of uniform sampling rv(k) = r*(2*rand-1); temp = normpdf(rv(k)); p = p*temp; p_rat = p_rat*(2*r)/temp; case 'l' % legendre/uniform [0,1] Asymp is shifted Cheby rv(k) = 0.5*cos(pi*rand)+0.5; % Rescale so rv is in [0,1] %p = p; % pdf = 1 p_rat = p_rat*2/(pi*(1-(2*rv(k)-1)^2)^(0.5)); % Appropriate ratio for rv in [0,1] case 'L' % legendre/uniform [-1,1] Asymp is cheby rv(k) = cos(pi*rand); % rv in [-1,1] p = 1/2*p; p_rat = p_rat*2/(pi*(1-rv(k)^2)^(0.5)); % Appropriate ratio for rv in [-1,1] case 'a' % laguerre/gamma Asymp is different gamma rv(k) = gamrnd(eval_opt.alpha(k)+2,1); temp = gampdf(rv(k),eval_opt.alpha(k)+1,1); p = p*temp; p_rat = p_rat*gampdf(rv(k),sample_opt.alpha(k)+2,1)/temp; case 'j' % jacobi/beta [-1,1] Asymp is different beta rv(k) = betarnd(eval_opt.beta(k)+0.5,eval_opt.alpha(k)+0.5); % Not yet stretched to [-1, 1] temp = 0.5*betapdf(rv(k),eval_opt.beta(k)+0.5,eval_opt.alpha(k)+0.5); p = p*temp; % Half probability due to stretch p_rat = p_rat*0.5*betapdf(rv(k),eval_opt.beta(k)+1,eval_opt.alpha(k)+1)/temp; rv(k) = 2*rv(k)-1; % Jacobi rv in [-1,1] end end end
github
CU-UQ/BASE_PC-master
herm_elliptic_prop.m
.m
BASE_PC-master/base_pc_v1/sampler/proposals/herm_elliptic_prop.m
1,160
utf_8
ce3a24a1213c8bb0c2773d5f0bce2fd6
% proposal distribution from ellipsoid for use with Hermite polynomials % ----- % [rv,p,p_rat] = herm_elliptic_prop(sample_opt, eval_opt) % ----- % Input % ----- % sample_opt = options for sampling inputs % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % rv = sampled inputs % p = probability of sample in orthogonality distribution. Used for diagnostics % p_rat = ratio of proposal distribution over orthogonality distribution. Used for MCMC sampler function [rv,p,p_rat] = herm_elliptic_prop(sample_opt, ~) r = sqrt(2).*sqrt(2.*sample_opt.order+1); % Can increased size for slight increase in rejection rate and higher accuracy rv = randn(1,sample_opt.r_dim); rv = rv/norm(rv,2); % Randomly samples from unit sphere x = rand^(1/sample_opt.r_dim).*r; % Determines how far inside along radial axes to move rv = x.*rv; % Samples appropriately form interior of ellipsoid p = sqrt(2*pi)*exp(-0.5*(rv*rv')); % norm pdf p_rat = pi^(0.5*sample_opt.r_dim)/gamma(sample_opt.r_dim/2+1)*prod(r); % Volume of ellipsoid p_rat = p_rat/p; % p_rat = ratio of proposal distribution to orthogonality distribution end
github
CU-UQ/BASE_PC-master
herm_sphere_prop.m
.m
BASE_PC-master/base_pc_v1/sampler/proposals/herm_sphere_prop.m
1,059
utf_8
dc432bb7e96bed40675363720a2760f1
% proposal distribution from sphere for use with Hermite polynomials % ----- % [rv,p,p_rat] = herm_sphere_prop(sample_opt, eval_opt) % ----- % Input % ----- % sample_opt = options for sampling inputs % sample_opt.order = order (total-order) of PCE used for determining radius % sample_opt.r_dim = dimension of input % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % rv = sampled inputs % p = probability of sample in orthogonality distribution. Used for diagnostics % p_rat = ratio of proposal distribution over orthogonality distribution. Used for MCMC sampler function [rv,p,p_rat] = herm_sphere_prop(sample_opt, ~) r = sqrt(2)*sqrt(2*max(sample_opt.order)+1); % Can increase size for slight increase in rejection rate and higher accuracy rv = randn(1,sample_opt.r_dim); rv = rv/norm(rv,2); x = rand^(1/sample_opt.r_dim)*r; rv = x*rv; p = sqrt(2*pi)*exp(-0.5*(rv*rv')); % normal pdf p_rat = pi^(0.5*sample_opt.r_dim)/gamma(sample_opt.r_dim/2+1)*r^sample_opt.r_dim/p; % Volume of d-ball over p end
github
CU-UQ/BASE_PC-master
linf_correction_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/linf_correction_w.m
807
utf_8
d69e9fa4d43a1bd4d70cb4c0efa3b41a
% weight function for correction of l1 coherence-optimal sampling % ----- % [w, t_c, flag] = linf_correction_w(lhs_new, lhs_old, sample_opt) % ----- % Input % ----- % lhs_new = vector to associate with weight, associated with a single input % lhs_old = same input from old basis to be corrected from % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs_new % t_c = used for accurate correction sampling % flag = returned if t_c is zero to indicate sample deficiency function [w, tc, flag] = linf_correction_w(lhs_new,lhs_old,~,~, ~,sample_opt) flag = 0; w = 1/norm(lhs_new,inf); wold = norm(lhs_old,inf); tc = 1/w^2 - sample_opt.ac*wold^2; if tc < 0 flag = w^2*wold^2; % 1/o.ac that would have given tc = 0. end end
github
CU-UQ/BASE_PC-master
one_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/one_w.m
365
utf_8
5636336170713c1fa6550cde8d8e5898
% unit weight function, useful for draws from orthogonality distribution % ----- % w = one_w(lhs,sample_opt) % ----- % Input % ----- % lhs = vector to associate with weight, associated with a single input % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs function w = one_w(~, ~, ~, ~, ~) w = 1; end
github
CU-UQ/BASE_PC-master
l2_grad_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/l2_grad_w.m
574
utf_8
4e77258494c31b35e5ef9b4b251bbc11
% weight function with l_2 norm for use with gradients % ----- % w = l2_grad_w(lhs,sample_opt) % ----- % Input % ----- % lhs = vector to associate with weight, associated with a single input % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs function w = l2_grad_w(lhs, ~, ~, ~, sample_opt) n_rows = sample_opt.n_grad_dims_plus_one; n_samps = size(lhs,1)/n_rows; w = zeros(n_samps,1); set = 1:n_rows; for k = 1:n_samps w(k) = 1/norm(lhs(set,:),2); set = set+n_rows; end end
github
CU-UQ/BASE_PC-master
p_rat_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/p_rat_w.m
405
utf_8
d2994a8fae10fa0e804e04a994cf1e12
% p_rat weight function, useful for draws from proposal distribution that % are not passed through mcmc sampler % ----- % w = p_rat_w(lhs,sample_opt) % Actually depends on rv not lhs % ----- % Input % ----- % p_rat = ratio of proposal distribution to orthogonality distribution % ------ % Output % ------ % w = weight value to be paired with lhs function w = p_rat_w(~, ~, ~, p_rat, ~) w = p_rat; end
github
CU-UQ/BASE_PC-master
l2_correction_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/l2_correction_w.m
934
utf_8
3fe063279480f447cf92beb37d4792e2
% weight function for correction of l2 coherence-optimal sampling % ----- % [w, t_c, flag] = l2_correction_w(lhs_new, lhs_old, sample_opt) % ----- % Input % ----- % lhs_new = vector to associate with weight, associated with a single input % lhs_old = same input from old basis to be corrected from % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs_new % t_c = used for accurate correction sampling % flag = returned if t_c is zero to indicate sample deficiency function [w, t_c, flag] = l2_correction_w(lhs_new,lhs_old,~,~,~,sample_opt) flag = 0; w = 1/norm(lhs_new,2); % value of new weight wold = norm(lhs_old,2); % inverse of old weight, but we don't need old weight t_c = 1/w^2 - sample_opt.ac*wold^2; if t_c < 0 % Correction Sampling is impossible with these parameters flag = w^2*wold^2; % 1/o.ac that would have given tc = 0. end end
github
CU-UQ/BASE_PC-master
linf_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/linf_w.m
392
utf_8
e5c2f9588ae8df6f460891e372ffbd74
% weight function with l_infinity norm, useful for l1-coherence optimal sampling % ----- % w = linf_w(lhs,sample_opt) % ----- % Input % ----- % lhs = vector to associate with weight, associated with a single input % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs function w = linf_w(lhs, ~, ~, ~, ~) w = 1./norm(lhs,inf); end
github
CU-UQ/BASE_PC-master
l2_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/l2_w.m
380
utf_8
2face1df4de57be7d35858153ca1b89c
% weight function with l_2 norm, useful for l2-coherence optimal sampling % ----- % w = l2_w(lhs,sample_opt) % ----- % Input % ----- % lhs = vector to associate with weight, associated with a single input % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs function w = l2_w(lhs, ~, ~, ~, ~) w = 1./norm(lhs,2); end
github
CU-UQ/BASE_PC-master
linf_grad_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/linf_grad_w.m
591
utf_8
19109078114f45eac72c52758395356d
% weight function with l_inf norm for use with gradients % ----- % w = linf_grad_w(lhs,sample_opt) % ----- % Input % ----- % lhs = vector to associate with weight, associated with a single input % sample_opt = options for sampling inputs % ------ % Output % ------ % w = weight value to be paired with lhs function w = linf_grad_w(lhs, ~, ~, ~, sample_opt) n_rows = sample_opt.n_grad_dims_plus_one; n_samps = size(lhs,1)/n_rows; w = zeros(n_samps,1); set = 1:n_rows; for k = 1:n_samps w(k) = 1/sqrt(max(sum(lhs(set,:).^2))); set = set+n_rows; end end
github
CU-UQ/BASE_PC-master
one_correction_w.m
.m
BASE_PC-master/base_pc_v1/sampler/sample_weight_functions/one_correction_w.m
506
utf_8
39cd398b8f224b407f8d475a2f3521b3
% weight function for correction of l2 coherence-optimal sampling % ----- % [w, t_c, flag] = one_correction_w(lhs_new, lhs_old, sample_opt) % ----- % Input % ----- % No input for this function, but must meet params requirement % ------ % Output % ------ % w = weight value to be paired with lhs_new % t_c = used for accurate correction sampling % flag = returned if t_c is zero to indicate sample deficiency function [w, t_c, flag] = one_correction_w(~,~,~,~,~,~) flag = 0; w = 1; t_c = 1; end
github
CU-UQ/BASE_PC-master
sa_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/sa_eval.m
909
utf_8
6576dd5092817ac55152361d2dfa61e8
% Generates QoI from surface adsoprtion problem % ----- % output = sa_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = sa_eval(input,eval_opt) n_inputs = size(input,1); alpha = .1 + exp(10.*input(:,1)); %input(1) normal gamma = .001 + .001.*exp(10*input(:,2)); %input(2) normal r_0 = 0.9*ones(n_inputs,1); % Integration time tint = 0:0.01:4; % ODE45 options opt = odeset('RelTol',1e-5); [~,rho] = ode45(@(t,r,a,g) surface_abs(r,alpha,gamma),tint,r_0,opt); output = rho(end,:)'; end function drho = surface_abs(rho,alpha,gamma) % Defines the surface absorption forcing beta = 10; drho = alpha.*(1-rho) - gamma.*rho - beta.*(1-rho).^2.*rho; end
github
CU-UQ/BASE_PC-master
basis_handle_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/basis_handle_eval.m
438
utf_8
7863d9d170956ae11e18864e1ba17cfb
% Generates QoI from predetermined basis and coefficients % ----- % output = basis_handle_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = basis_handle_eval(input, eval_opt) output = basis_eval(eval_opt.eval_basis,input,eval_opt)*eval_opt.eval_coefs; end
github
CU-UQ/BASE_PC-master
sa_eval_forward_euler.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/sa_eval_forward_euler.m
891
utf_8
758988254277b5c69b8a6f98aa667710
% Generates QoI from surface adsoprtion problem % ----- % output = sa_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = sa_eval_forward_euler(input,eval_opt) n_inputs = size(input,1); alpha = .1 + exp(10.*input(:,1)); %input(1) normal gamma = .001 + .001.*exp(10*input(:,2)); %input(2) normal rho = 0.9*ones(n_inputs,1); beta = 10; % Simple Forward Euler Solver for this h = 10^(-5); % Step Size tint = 0:h:4; n_ints = size(tint,2); for k = 1:n_ints step = h*(alpha.*(1-rho) - gamma.*rho - beta.*(1-rho).^2.*rho); step = max(step,-rho); step = min(step,1-rho); rho = rho + step; end output = rho; end
github
CU-UQ/BASE_PC-master
duffing_hermite_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/duffing_hermite_eval.m
552
utf_8
7d03205622daeff1b06b1b67b26d10a3
function output = duffing_hermite_eval(inputs, eval_opt) n_runs = size(inputs,1); output = zeros(n_runs,1); t0 = 0; tend = 5; tstep = 500; for k = 1 : n_runs [T,x] = ode45(@(t,y)le_duffing(t,y, inputs(k,:)),linspace(t0,tend,tstep),[1; 0]'); output(k) = interp1(T,x(:,1),4); end end function dxdt = le_duffing(~, x, inputs) epsilon =exp(-0.1*inputs(1)^2); omega = exp(-0.1*inputs(2)^2); xi = exp(-0.1*inputs(3)^2); dxdt = [x(2); -2*xi*x(2) - omega*(x(1) - epsilon*x(1)^3)]; end
github
CU-UQ/BASE_PC-master
white_noise_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/white_noise_eval.m
390
utf_8
39155c30e21dc199dfb3d76bb1bf2a62
% Generates QoI that is white noise % ----- % output = white_noise_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = white_noise_eval(input,eval_opt) output = rand(size(input,1),1)*eval_opt.noise_level; end
github
CU-UQ/BASE_PC-master
high_order_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/high_order_eval.m
499
utf_8
e86a249d333bd96ff2be2e73218ef25e
% Generates QoI evaluating a high order of sum of inputs % ----- % output = high_order_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = high_order_eval(input,eval_opt) output = (input(:,1) + input(:,2) - 1).^eval_opt.power; % Is small outside circle, is large inside, depending on eval_opt.modulation_constant end
github
CU-UQ/BASE_PC-master
duffing_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/duffing_eval.m
519
utf_8
456e8017872a1caec7bd4286b1a6b5d2
function output = duffing_eval(inputs, eval_opt) n_runs = size(inputs,1); output = zeros(n_runs,1); t0 = 0; tend = 5; tstep = 500; for k = 1 : n_runs [T,x] = ode45(@(t,y)le_duffing(t,y, inputs(k,:)),linspace(t0,tend,tstep),[1; 0]'); output(k) = interp1(T,x(:,1),4); end end function dxdt = le_duffing(~, x, inputs) epsilon = inputs(1); omega = inputs(2); xi = inputs(3); dxdt = [x(2); -2*omega*xi*x(2) - omega^2*(x(1) - epsilon*x(1)^3)]; end
github
CU-UQ/BASE_PC-master
modulated_exp_sine_decay_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/modulated_exp_sine_decay_eval.m
799
utf_8
f76c54d808823848e283b916c79900e7
% Generates QoI having exponential decay with non-monotonic decay in dimension % ----- % output = exp_sine_decay_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = modulated_exp_sine_decay_eval(input,eval_opt) output = eval_opt.exp_const; modulation = 1 - 1./(1+exp(-2*eval_opt.modulation_constant*((input(:,1)-0.5).^2+2*(input(:,2)-0.5).^2-0.25))); % Is small outside circle, is large inside, depending on eval_opt.modulation_constant for k = 3:eval_opt.max_dim output = output-eval_opt.exp_decay_init.*input(:,k).*sin(k)./k.^eval_opt.exp_decay_exp; end output = modulation.*exp(output); end
github
CU-UQ/BASE_PC-master
exp_decay_grad_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/exp_decay_grad_eval.m
820
utf_8
52747d73a0c8f45cfeeb1ffd4ef20416
% Generates QoI having exponential decay with gradient information % ----- % output = exp_decay_grad_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI and gradient information function output = exp_decay_grad_eval(input,eval_opt) output = zeros(eval_opt.grad_dim+1,1); output(1) = eval_opt.exp_const; for k = 1:eval_opt.max_dim output(1) = output(1)-eval_opt.decay_init*input(k)/k^exp_decay_exp; if k <= eval_opt.grad_dim output(k+1) = -eval_opt.decay_init/k^eval_opt.exp_decay_exp; end end output(1) = exp(output(1)); output(2:(eval_opt.grad_dim+1)) = output(1)*output(2:(eval_opt.grad_dim+1)); end
github
CU-UQ/BASE_PC-master
zero_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/zero_eval.m
369
utf_8
b01d8632982c34b55f9588919581296e
% Generates QoI that is always zero % ----- % output = zero_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = zero_eval(input,eval_opt) %#ok<INUSD> output = zeros(size(input,1),1); end
github
CU-UQ/BASE_PC-master
multi_basis_handle_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/multi_basis_handle_eval.m
610
utf_8
8127e57b3699c30ff2439f72612a835b
% Generates QoI from likelihood_eval (using PC approximation) % ----- % output = multi_basis_handle_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = multi_basis_handle_eval(input,eval_opt) output = zeros(1,eval_opt.data_dim); % Row vector for k = 1:eval_opt.data_dim output(k) = basis_eval(eval_opt.eval_basis{k},input,eval_opt)*eval_opt.eval_coefs{k}; % assume normal pdf with data mean and variances end end
github
CU-UQ/BASE_PC-master
exp_sine_decay_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/exp_sine_decay_eval.m
576
utf_8
ebf6c24373a56b2753b8efce3c5a4165
% Generates QoI having exponential decay with non-monotonic decay in dimension % ----- % output = exp_sine_decay_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = exp_sine_decay_eval(input,eval_opt) output = eval_opt.exp_const; for k = 1:eval_opt.max_dim output = output-eval_opt.exp_decay_init.*input(:,k).*sin(k)./k.^eval_opt.exp_decay_exp; end output = exp(output); end
github
CU-UQ/BASE_PC-master
exp_decay_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/exp_decay_eval.m
519
utf_8
c4dbb979070b873669847b1ca305dde8
% Generates QoI having exponential decay % ----- % output = exp_decay_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = exp_decay_eval(input,eval_opt) output = eval_opt.exp_const; for k = 1:eval_opt.max_dim output = output-eval_opt.exp_decay_init.*input(:,k)./k.^eval_opt.exp_decay_exp; end output = exp(output); end
github
CU-UQ/BASE_PC-master
franke_eval.m
.m
BASE_PC-master/base_pc_v1/qoi_evals/franke_eval.m
624
utf_8
92ae6f972def69ec23db8d0588f74c5d
% Generates QoI from Franke function % ----- % output = franke_eval(input, eval_opt) % ----- % Input % ----- % input = points where QoI is evaluated. May be multiple rows % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % output = evaluated QoI function output = franke_eval(input,eval_opt) %#ok<INUSD> output = 0.75*exp(-0.25*((9*input(:,1)-2).^2 + (9*input(:,2)-2).^2)) + ... 0.75*exp(-(9*input(:,1)+1).^2./49 - (9*input(:,2)+1)./10) + ... 0.5*exp(-0.25*((9*input(:,1)-7).^2 + (9*input(:,2)-3).^2)) - ... 0.2*exp(-(9*input(:,1)-4).^2 - (9*input(:,2)-7).^2); end
github
CU-UQ/BASE_PC-master
basis_order_bounds.m
.m
BASE_PC-master/base_pc_v1/basis/basis_order_bounds.m
1,368
utf_8
eaa1e4aaa4495f0a46bd63207ae56b8e
% computes order bounds for high-dimensional problems (upper bound only) % basis_opt = basis_order_bounds(basis_opt, eval_opt) % ----- % Input % ----- % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_opt = options associated with basis function basis_opt = basis_order_bounds(basis_opt, eval_opt) [orders,indices] = unique(basis_opt.ord, 'last'); % Here using global minimum order 1 all dimensions if isempty(indices) % Sometimes nothing in indices % basis_opt.lb = [ones(1,basis_opt.dim_add) zeros(1,eval_opt.max_dim-basis_opt.dim_add)]; % Here using global minimum order 1 all dimensions, otherwise must be computed differently basis_opt.ub = basis_opt.lb; return end ub_indices = min(indices+basis_opt.dim_add,eval_opt.max_dim); basis_opt.ub = zeros(1,eval_opt.max_dim); for kkk = 1:size(orders,2) basis_opt.ub(1:ub_indices(kkk)) = max(basis_opt.ub(1:ub_indices(kkk)),orders(kkk)); end basis_opt.ub(1:basis_opt.dim_add) = basis_opt.ub(1:basis_opt.dim_add)+1; % o = horzcat(basis_opt.ord,zeros(1,eval_opt.max_dim-basis_opt.dim)); % basis_opt.lb = max([ones(1,basis_opt.dim_add) zeros(1,eval_opt.max_dim-basis_opt.dim_add)],o-1); % Here using global minimum order 1 all dimensions, otherwise must be computed differently end
github
CU-UQ/BASE_PC-master
basis_eval.m
.m
BASE_PC-master/base_pc_v1/basis/basis_eval.m
4,601
utf_8
3a40a84cad1287470b23a84817ca787d
% evaluates basis functions at input % ----- % lhs = basis_eval(basis, input) % ----- % Input % ----- % basis = basis object % input = input evaluated according to basis % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % lhs = matrix of basis functions evaluated at input function lhs = basis_eval(basis,input,eval_opt) n_samps = size(input,1); n1 = min(eval_opt.grad_dim,basis.n_dim)+1; n_rows = n1*n_samps; lhs = ones(n_rows,basis.n_elems); for k=1:basis.n_dim % iterates over dimension % May be more prudent iteration over basis functions if floor(basis.max(k)) > 0 % nothing to do if no effective order if eval_opt.grad && k <= eval_opt.grad_dim f_set = 1:n1:n_rows; fp_set = (k+1):n1:n_rows; switch eval_opt.p_type(k) case 'H' % Hermite/ normal with location/scale parameter ord = floor(basis.max(k)); [f, fp] = hermite_eval_gradient(ord,(input(:,k)-eval_opt.mu(k))/eval_opt.sig(k)); nc = 1; for kk = 1:ord nc = nc*eval_opt.sig(k); f(:,kk) = f(:,kk)/nc; fp(:,kk) = f(:,kk)/nc; end % Repositions/Rescales hermite polynomials case 'h' % Hermite/ normal [f,fp] = hermite_eval_gradient(floor(basis.max(k)),input(:,k)); case 'l' % Legendre/ Uniform [0,1] [f,fp] = legendre_eval_gradient(floor(basis.max(k)),2*input(:,k)-1); % Adjusts for differences between poly orthogonality and rv gen case 'L' % Legendre/ Uniform [-1,1] [f,fp] = legendre_eval_gradient(floor(basis.max(k)),input(:,k)); % Adjusts for differences between poly orthogonality and rv gen case 'a' % Laguerre / Gamma [f,fp] = laguerre_eval_gradient(floor(basis.max(k)),input(:,k),eval_opt.alpha(k)-1); % Adjusts for differences between poly orthogonality and rv gen case 'j' % Jacobi / Beta [-1,1] [f,fp] = jacobi_eval_gradient(basis.max(k),input(:,k),eval_opt.beta(k)-1,eval_opt.alpha(k)-1); % Adjusts for differences between poly orthogonality and rv gen end else switch eval_opt.p_type(k) case 'H' % Hermite/ normal with location/scale parameter ord = floor(basis.max(k)); f = hermite_eval(ord,(input(:,k)-eval_opt.mu(k))/eval_opt.sig(k)); % Repositions/Rescales hermite polynomials nc = 1; for kk = 1:ord nc = nc*eval_opt.sig(k); f(:,kk) = f(:,kk)/nc; end case 'h' % Hermite/ normal f = hermite_eval(floor(basis.max(k)),input(:,k)); case 'l' % Legendre/ Uniform [0,1] f = legendre_eval(floor(basis.max(k)),2*input(:,k)-1); % Adjusts for differences between poly/rv case 'L' % Legendre/ Uniform [-1,1] f = legendre_eval(floor(basis.max(k)),input(:,k)); % Adjusts for differences between poly/rv case 'a' % Laguerre / Gamma f = laguerre_eval(floor(basis.max(k)),input(:,k),eval_opt.alpha(k)-1); % Adjusts for differences between poly/rv case 'j' % Jacobi / Beta [-1,1] f = jacobi_eval(floor(basis.max(k)),input(:,k),eval_opt.beta(k)-1,eval_opt.alpha(k)-1); % Adjusts for differences between poly/rv end end end for kk = 1:basis.n_elems % iterates over basis functions l = find(basis.dim{kk} == k,1); % find appropriate dimension index if eval_opt.grad && k <= eval_opt.grad_dim if isempty(l) lhs(fp_set,kk) = zeros(n_samps,1); % derivative of constant is zero else lhs(f_set,kk) = lhs(f_set,kk).*f(:,basis.ord{kk}(l)); lhs(fp_set,kk) = lhs(fp_set,kk).*fp(:,basis.ord{kk}(l)); end else if ~isempty(l) lhs(:,kk) = lhs(:,kk).*f(:,basis.ord{kk}(l)); end end end end if basis.pc_flag lhs = lhs*basis.pc; end end
github
CU-UQ/BASE_PC-master
basis_identify.m
.m
BASE_PC-master/base_pc_v1/basis/basis_identify.m
1,606
utf_8
e8698a1ab8fe805c2e9cbb27a5560075
% updates basis object % ----- % basis = basis_identify(basis_opt, eval_opt) % ----- % Input % ----- % basis = basis object % sample = sample object % sol = solution object % basis_opt = options to identify basis % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % min_basis = basis object % min_basis_opt = basis options % min_solver_opt = solver options % min_sample = sample object adjusted for new basis % min_sol = solution object adjusted for new basis function [min_basis, min_basis_opt, min_solver_opt, min_sample, min_sol] = basis_identify(basis, sample, sol, basis_opt, eval_opt, solver_opt) % can be modified for different bases val_err = inf; min_basis = basis; min_basis_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; for k = 1:basis_opt.validation_iters [basis1, basis_opt, solver_opt, sample, sol, exit_flag] = basis_opt.basis_identify_handle(basis, sample, sol, basis_opt, eval_opt, solver_opt); if sol.err < val_err val_err = sol.err; min_basis = basis1; min_basis_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end fprintf('Basis Adaptation Iteration: %i Complete. Validation Error: %f Number of Basis Elements: %i \n', k, val_err, min_basis.n_elems) if exit_flag % original basis was selected, future iterations unneeded return else basis = basis1; end end fprintf('Basis Adaptation Complete.\n') end
github
CU-UQ/BASE_PC-master
basis_init.m
.m
BASE_PC-master/base_pc_v1/basis/basis_init.m
1,496
utf_8
ae7be19e925b1b2e66504de5f9be508f
% constructs initial basis opbject % ----- % basis = basis_init(basis_opt, eval_opt) % ----- % Input % ----- % basis_opt = options to identify basis % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % basis = basis object function basis = basis_init(basis_opt, eval_opt) % can be modified for different bases % Identifies basis based on ib_handle basis = basis_opt.type_handle(basis_opt); % If preconditioning is applied if basis_opt.pc_flag if isfield(basis_opt, 'pc_handle') basis.pc = basis_opt.pc_handle(basis, basis_opt); else % The below process is slow and perhaps inaccurate, and should probably be removed. n_samps = min(10^4,max(10,basis_opt.sr)*basis.n_elems); rv = zeros(n_samps,basis_opt.max_dim); basis.pc_flag = false; for k = 1:n_samps rv(k,:) = rv_gen(basis_opt); end mat = basis_eval(basis,rv, basis_opt, eval_opt); mat = mat'*mat/n_samps; for kk = 2:basis_opt.burn_in parfor k = 1:n_samps rv(k,:) = rv_gen(eval_opt); end mat1 = basis_eval(basis,rv, basis_opt, eval_opt); mat1 = mat1'*mat1/n_samps; mat = mat*(kk-1)/kk + mat1/kk; basis.pc = inv(chol(mat)); end end basis.pc_flag = true; else basis.pc_flag = false; end end
github
CU-UQ/BASE_PC-master
jacobi_eval_gradient.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/jacobi_eval_gradient.m
2,138
utf_8
2d6b4b683e6a22b4437242bfc6ae54ae
% evaluates set of orthonormal Jacobi polynomials with derivative % orthogonal with respect to 2*betarnd(b+1,a+1)-1; % ----- % f_o = jacobi_eval_gradient(ord,f_i,a,b); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % a: jacobi alpha % b: jacobi beta % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order % fp: rows of function derivative evaluations, column is order function [f, fp] = jacobi_eval_gradient(ord,f_i,a,b) n = size(f_i,1); f = zeros(n,ord); fp = zeros(n,ord); % These combinations can be used frequently ab = a+b; ab1 = a+b+1; a1 = a+1; ab2 = a+b+2; a2 = a+2; ab3 = a+b+3; ab4 = a+b+4; a_1 = a-1; b_1 = b-1; b1 = b+1; ab_1 = a+b-1; ab_2 = a+b-2; asq_bsq = a^2-b^2; switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = 0.5*(2*(a1)+(ab2)*(f_i-1)); %needs normalized f(:,1) = f(:,1)*sqrt(ab3*gamma(2)*gamma(ab2)/(gamma(a2)*gamma(b+2)))*sqrt(beta(a1,b1)); fp(:,1) = ones(n,1)*0.5*ab2; return end f(:,1) = 0.5*(2*a1+ab2*(f_i-1)); fp(:,1) = ones(n,1); f(:,2) = 0.125*(4*a1*a2+4*ab3*a2*(f_i-1)+ab3*ab4*(f_i-1).^2); fp(:,2) = 0.5*(2*a2+ab4*(f_i-1)); for k = 3:ord % three term recurrence f(:,k) = (2*k+ab_1)*((2*k+ab)*(2*k+ab_2)*f_i+asq_bsq).*f(:,k-1)-2*(k+a_1)*(k+b_1)*(2*k+ab)*f(:,k-2); f(:,k) = f(:,k)/(2*k*(k+ab)*(2*k+ab_2)); fp(:,k) = (2*k+ab_1)*((2*k+ab)*(2*k+ab_2)*f_i+asq_bsq).*fp(:,k-1)-2*(k+a_1)*(k+b_1)*(2*k+ab)*fp(:,k-2); fp(:,k) = fp(:,k)/(2*(k-1)*(k+ab1)*(2*k+ab_2)); end for k = 1:ord % correct to finish derivative evaluation fp(:,k) = fp(:,k)*0.5*(k+ab3); end nc = sqrt(beta(a1,b1));% nc = 1/sqrt(ab1*gamma(a1)*gamma(b1)/gamma(ab1)); for k = 1:ord % normalization to orthonormality tc = sqrt((2*k+ab1)*gamma(k+1)*gamma(ab1+k)/(gamma(a1+k)*gamma(b1+k)))*nc; f(:,k) = f(:,k)*tc; fp(:,k) = fp(:,k)*tc; %normalization to derivative as well end end
github
CU-UQ/BASE_PC-master
jacobi_eval.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/jacobi_eval.m
1,534
utf_8
73b6420fb348e91d900e8b72be56c4a1
% evaluates set of orthonormal Jacobi polynomials % orthogonal with respect to 2*betarnd(b+1,a+1)-1; % ----- % f_o = jacobi_eval(ord,f_i,a,b); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % a: jacobi alpha % b: jacobi beta % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order function f = jacobi_eval(ord,f_i,a,b) f = zeros(size(f_i,1),ord); % These combinations can be used frequently ab = a+b; ab1 = a+b+1; a1 = a+1; ab2 = a+b+2; a2 = a+2; ab3 = a+b+3; ab4 = a+b+4; a_1 = a-1; b_1 = b-1; b1 = b+1; ab_1 = a+b-1; ab_2 = a+b-2; asq_bsq = a^2-b^2; switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = 0.5*(2*(a1)+(ab2)*(f_i-1)); %needs normalized f(:,1) = f(:,1)*sqrt(ab3*gamma(2)*gamma(ab2)/(gamma(a2)*gamma(b+2)))*sqrt(beta(a1,b1)); return end f(:,1) = 0.5*(2*a1+ab2*(f_i-1)); f(:,2) = 0.125*(4*a1*a2+4*ab3*a2*(f_i-1)+ab3*ab4*(f_i-1).^2); for k = 3:ord % three term recurrence f(:,k) = (2*k+ab_1)*((2*k+ab)*(2*k+ab_2)*f_i+asq_bsq).*f(:,k-1)-2*(k+a_1)*(k+b_1)*(2*k+ab)*f(:,k-2); f(:,k) = f(:,k)/(2*k*(k+ab)*(2*k+ab_2)); end nc = sqrt(beta(a1,b1));% nc = 1/sqrt(ab1*gamma(a1)*gamma(b1)/gamma(ab1)); for k = 1:ord % normalization to orthonormality f(:,k) = f(:,k)*sqrt((2*k+ab1)*gamma(k+1)*gamma(ab1+k)/(gamma(a1+k)*gamma(b1+k)))*nc; end end
github
CU-UQ/BASE_PC-master
hermite_eval.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/hermite_eval.m
841
utf_8
bded50e9e7aedf28fe4398b2535f0366
% evaluates set of orthonormal Hermite polynomials (probabilist) % orthogonal with respect to randn % ----- % f_o = hermite_eval(ord,f_i); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order function f = hermite_eval(ord,f_i) f = zeros(size(f_i,1),ord); switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = f_i; return end f(:,1) = f_i; f(:,2) = f_i.*f(:,1)-1; for k = 3:ord % three term recurrence f(:,k) = f_i.*f(:,k-1)-(k-1)*f(:,k-2); end fact = 1; for k = 2:ord % normalization fact = fact*k; f(:,k) = f(:,k)/sqrt(fact); end end
github
CU-UQ/BASE_PC-master
legendre_eval.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/legendre_eval.m
868
utf_8
97d27d103af10f2af5d4e00efa95fddd
% Evaluates set of orthonormal Legendre polynomials % orthogonal with respect to 2*rand-1 % ----- % f_o = legendre_eval(ord,f_i); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order function f = legendre_eval(ord,f_i) f = zeros(size(f_i,1),ord); switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = f_i*sqrt(3); return end f(:,1) = f_i; f(:,2) = (3*f_i.^2-1)/2; for i = 3:ord % three term recurrence t = 1/i; f(:,i) = (2-t)*f_i.*f(:,i-1) - (1-t)* f(:,i-2); end for i=1:ord % normalization f(:,i) = f(:,i)*sqrt(2*i+1); end end
github
CU-UQ/BASE_PC-master
laguerre_eval.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/laguerre_eval.m
1,046
utf_8
ce70c74c28f76cad29cf8e546875b098
% evaluates set of orthonormal Laguerre polynomials % orthogonal with respect to gamrnd(a+1,1) % ----- % f_o = laguerre_eval(ord,f_i); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % a: Laguerre alpha % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order function f = laguerre_eval(ord,f_i,a) % These combinations can be used frequently a1 = a+1; a2 = a+2; a_1 = a-1; f = zeros(size(f_i,1),ord); switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = 1+a-f_i; return end f(:,1) = 1+a-f_i; f(:,2) = 0.5*f_i.^2-a2*f_i+0.5*a2*a1; for k = 3:ord % three term recurrence f(:,k) = (2*k+a_1-f_i).*f(:,k-1)-(k+a_1)*f(:,k-2); f(:,k) = f(:,k)/k; end nc = sqrt(gamma(a1)); fact = 1; for k = 1:ord % normalization fact = fact*k; f(:,k) = f(:,k)*nc*sqrt(fact/gamma(k+a1)); end end
github
CU-UQ/BASE_PC-master
legendre_eval_gradient.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/legendre_eval_gradient.m
1,196
utf_8
414a8ef101837cf945d5215c0455aad2
% evaluates set of orthonormal Legendre polynomials % orthogonal with respect to 2*rand-1 % ----- % f_o = legendre_eval(ord,f_i); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order % fp: rows of function derivative evaluations, column is order function [f,fp] = legendre_eval_gradient(ord,f_i) n = size(f_i,1); f = zeros(n,ord); fp = zeros(n,ord); switch ord case 0 return case 1 fp(:,1) = ones(n,1)*sqrt(3); f(:,1) = f_i*sqrt(3); return otherwise fp(:,1) = ones(n,1); fp(:,2) = 3*f_i; f(:,1) = f_i; f(:,2) = (1.5)*f_i.*f(:,1) - .5; for k = 3:ord % recurrence f(:,k) = (2-1/k)*f_i.*f(:,k-1) - (1-1/k)* f(:,k-2); end end for k = 3:ord fp(:,k) = k*f(:,k-1)+ f_i.*fp(:,k-1); end for k = 1:ord % normalization f(:,k) = f(:,k)*sqrt(2*k+1); fp(:,k) = fp(:,k)*sqrt(2*k+1); end end
github
CU-UQ/BASE_PC-master
hermite_eval_gradient.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/hermite_eval_gradient.m
1,023
utf_8
df2d1345099594a86cf1245845da90b0
% evaluates set of orthonormal hermite polynomials (probabilist) with derivatives % orthogonal with respect to randn % ----- % [f, fp] = hermite_eval_gradient(ord,f_i) % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % Output % ------ % f : rows of function evaluations, column corresponds to order % fp: rows of function derivative evaluations, column is order function [f, fp] = hermite_eval_gradient(ord,f_i) n = size(f_i,1); f = zeros(n,ord); fp = zeros(n,ord); switch ord case 0 return case 1 f(:,1) = f_i; otherwise f(:,1) = f_i; f(:,2) = f_i.*f(:,1)-1; for k = 2:ord-1 f(:,k+1) = f_i.*f(:,k)-k*f(:,k-1); end end % fac = 1; fp(:,1) = ones(n,1); for k = 2:ord fac = fac*k; f(:,k) = f(:,k)/sqrt(fac); fp(:,k) = sqrt(k)*f(:,k-1); end end
github
CU-UQ/BASE_PC-master
laguerre_eval_gradient.m
.m
BASE_PC-master/base_pc_v1/basis/poly_evals/laguerre_eval_gradient.m
1,427
utf_8
a1d20060472ef9e955760bc62fcc26fb
% evaluates set of orthonormal Laguerre polynomials % orthogonal with respect to gamrnd(a+1,1) % ----- % f_o = laguerre_eval_gradient(ord,f_i); % ----- % Input % ----- % ord: maximum order of polynomial % f_i: column vector of points being evaluated % a: Laguerre alpha % ------ % Output % ------ % f: rows of function evaluations, column corresponds to order % fp: rows of function derivative evaluations, column is order function [f,fp] = laguerre_eval_gradient(ord,f_i,a) n = size(f_i,1); f = zeros(n,ord); fp = zeros(n,ord); % These combinations can be used frequently a1 = a+1; a2 = a+2; a_1 = a-1; switch ord % before 3 term is effective case 0 % this case should not be used return case 1 f(:,1) = 1+a-f_i; fp(:,1) = -1*ones(n,1); return end f(:,1) = 1+a-f_i; f(:,2) = 0.5*f_i.^2-a2*f_i+0.5*a2*a1; for k = 3:ord % three term recurrence f(:,k) = (2*k+a_1-f_i).*f(:,k-1)-(k+a_1)*f(:,k-2); f(:,k) = f(:,k)/k; end fp(:,1) = 1; % forming poly for alpha+1 by sum equality for k = 2:ord fp(:,k)= fp(:,k-1)+f(:,k-1); end fp = -fp; % minus sign completes derivative computation nc = sqrt(gamma(a1)); fact = 1; for k = 1:ord % normalization fact = fact*k; c=nc*sqrt(fact/gamma(k+a1)); f(:,k) = f(:,k)*c; fp(:,k) = fp(:,k)*c; end end
github
CU-UQ/BASE_PC-master
l2_nc.m
.m
BASE_PC-master/base_pc_v1/basis/explicit_normalizations/l2_nc.m
289
utf_8
ed7d0c4a294bec162e9c465a0b364661
% normalization constant for l2-coh-opt sampling % ----------- % c = l2_nc(basis,o) % ----------- % Input % ----- % basis = basis_object % o = option parameters, not used here % ------ % Output % ------ % c = normalizing constant function c = l2_nc(basis,o) c = sqrt(basis.n_elems); end
github
CU-UQ/BASE_PC-master
basis_total_order.m
.m
BASE_PC-master/base_pc_v1/basis/order_definitions/basis_total_order.m
2,558
utf_8
93ed6759c96b975051dd1a4837b257cf
% returns total order basis object % ----------- % basis = basis_total_order(basis_opt) % ----------- % Input % ----- % basis_opt = options to describe basis % ------ % Output % ------ % basis = basis object function basis = basis_total_order(basis_opt) % Can be made more efficient through vectorization basis.n_dim = basis_opt.dim; basis.max = basis_opt.ord.*ones(1,basis_opt.dim); basis.max_ord = basis_opt.ord; switch basis_opt.ord % A few easy cases case 0 basis.ord={[]}; basis.dim={[]}; basis.n_elems = 1; return case 1 basis.dim = [{[]}; num2cell((1:basis_opt.dim)')]; basis.ord = [{[]}; num2cell(ones(basis_opt.dim,1))]; basis.n_elems = basis_opt.dim+1; return end if basis_opt.dim == 1 % Another easy cases basis.dim = [{[]}; num2cell(ones(basis_opt.ord,1))]; basis.ord = [{[]}; num2cell((1:basis_opt.ord)')]; basis.n_elems = basis_opt.ord+1; return end d_minus = basis_opt.dim-1; c_test = 1:d_minus; % General case basis.n_elems = round(exp(gammaln(basis_opt.ord+basis_opt.dim+1)-gammaln(basis_opt.ord+1)-gammaln(basis_opt.dim+1))); basis.ord = cell(basis.n_elems,1); basis.dim = cell(basis.n_elems,1); basis_vec = zeros(1,basis_opt.dim); n = 1; t = zeros(1,d_minus); for c_ord = 1:basis_opt.ord end_gen = 0; first_this_order = 0; c_test = c_test + 1; while (end_gen == 0) n = n+1; if (first_this_order == 0) t = 1:d_minus; first_this_order = 1; else l = find(t < c_test ,1,'last'); % Find index to increment t(l:d_minus) = (t(l)+1):(t(l)+basis_opt.dim-l); % Increment t(l) and all t(k) for k > l to be t(l) + k-l. end basis_vec(1) = t(1)-1; basis_vec(2:d_minus) = t(2:d_minus) - t(1:(d_minus-1)) - 1; % Subsequent orders are t(k) - t(k-1) - 1 Do not need to check higher dimensions until c_ord increased basis_vec(basis_opt.dim) = basis_opt.dim+c_ord-t(d_minus)-1; if (t(1) == c_ord+1) end_gen = end_gen + 1; end act_opt = find(basis_vec~=0); % Puts into our basis definition basis.dim{n} = act_opt; % Active dimensions basis.ord{n} = basis_vec(act_opt); % Active orders end end end
github
CU-UQ/BASE_PC-master
basis_anisotropic_hyperbolic_order.m
.m
BASE_PC-master/base_pc_v1/basis/order_definitions/basis_anisotropic_hyperbolic_order.m
2,352
utf_8
538b3c94dc1caf1705723033f6be1079
% returns anisotropic, hyperbolic, total order basis object % ----------- % basis = basis_anisotropic_hyperbolic_order(basis_opt) % ----------- % Input % ----- % basis_opt = options to describe basis % ------ % Output % ------ % basis = basis object function basis = basis_anisotropic_hyperbolic_order(basis_opt) % total order is somewhat analogous to the sum of orders max_ord = max(basis_opt.ord); basis.max_ord = max(basis_opt.ord); basis.max = basis_opt.ord; basis.hyp = basis_opt.hyp; basis.n_dim = basis_opt.dim; d_minus = basis_opt.dim-1; n = 1; t = zeros(1,d_minus); basis.ord={[]}; basis.dim={[]}; % The basis functions are generated and tested for c_ord = 1:max_ord % Loop over potential basis functions first_this = 0; basis_array_prop = zeros(1,basis_opt.dim); while true % break loop if condition follows if (first_this == 0) for k=1:d_minus t(k) = k; end first_this = 1; else if (t(d_minus) < d_minus + c_ord) t(d_minus) = t(d_minus) + 1; else l=d_minus; while (t(l) == l+c_ord) l=l-1; end t(l) = t(l)+1; for k =l+1:d_minus t(k) = t(l)+k-l; end end end basis_array_prop(1) = t(1)-1; for k= 2:d_minus basis_array_prop(k) = t(k)-t(k-1)-1; end basis_array_prop(basis_opt.dim) = basis_opt.dim+c_ord-t(d_minus)-1; % Final entry treated a bit differently if(sum((basis_array_prop./basis_opt.ord).^basis_opt.hyp) <= 1) n = n+1; act_dim = find(basis_array_prop~=0); act_ord = basis_array_prop(act_dim); basis.dim{n} = act_dim; basis.ord{n} = act_ord; if sum(act_ord) > basis.max_ord; basis.max_ord = sum(act_ord); end end if (t(1) == c_ord+1) break % break loop end end end basis.dim = basis.dim'; basis.ord = basis.ord'; basis.n_elems = n; end
github
CU-UQ/BASE_PC-master
basis_anisotropic_total_order.m
.m
BASE_PC-master/base_pc_v1/basis/order_definitions/basis_anisotropic_total_order.m
3,490
utf_8
4b387e11cc6fd37f3ab786e1918b7a0a
% returns anisotropic total order basis object % ----------- % basis = basis_anisotropic_total_order(basis_opt) % ----------- % Input % ----- % basis_opt = options to describe basis % ------ % Output % ------ % basis = basis object function basis = basis_anisotropic_total_order(basis_opt) % total order is somewhat analogous to the sum of orders max_ord = max(basis_opt.ord); basis.max = basis_opt.ord; basis.max_ord = max(basis_opt.ord); basis.n_dim = basis_opt.dim; if basis.n_dim == 1 % We only allow dimensions to be defined from first. This one is done. basis.ord={[]}; basis.dim={[]}; for k = 1:basis_opt.ord(1) basis.dim{k+1} = 1; basis.ord{k+1} = k; end basis.dim = basis.dim'; basis.ord = basis.ord'; basis.n_elems = basis_opt.ord(1)+1; return end d_minus = basis_opt.dim-1; % we use this dim-1 repeatedly n = 1; t = zeros(1,d_minus); % loops over potential basis functions basis.ord={[]}; basis.dim={[]}; c_test = 1:d_minus; [m_ord, index] = sort(basis_opt.ord, 'ascend'); % We sort this ascending to determine break point. [~, index] = sort(index); % This is the permutation indices we require % The basis functions are generated and tested for c_ord = 1:max_ord % Loop over potential basis functions c_test = c_test + 1; % Increment c_test first_this = 0; basis_array_prop = zeros(1,basis_opt.dim); while true % break loop if condition follows if (first_this == 0) t = 1:d_minus; % Corresponds to many zero orders first_this = 1; % After initialization no longer needed else l = find(t < c_test ,1,'last'); % Find index to increment t(l:d_minus) = (t(l)+1):(t(l)+basis_opt.dim-l); % Increment t(l) and all t(k) for k > l to be t(l) + k-l. % can perhaps accelerate this more by redefining d_minus appropriately. Many t(k) are redefined to same value end basis_array_prop(1) = t(1)-1; % First order is t(1)-1 basis_array_prop(2:d_minus) = t(2:d_minus) - t(1:(d_minus-1)) - 1; % Subsequent orders are t(k) - t(k-1) - 1 Do not need to check higher dimensions until c_ord increased basis_array_prop(basis_opt.dim) = basis_opt.dim+c_ord-t(d_minus)-1; % Final entry fills in gap to c_ord if(sum(basis_array_prop./m_ord) <= 1.0 + 1e-12) n = n+1; basis_array_prop = basis_array_prop(index); act_dim = find(basis_array_prop~=0); act_ord = basis_array_prop(basis_array_prop~=0); % Order for active dimensions basis.dim{n} = act_dim; % How basis dimension is stored basis.ord{n} = act_ord; % How basis order is stored else % If condition not held then can safely ignore a number of other vectors due to ascended sorting if(l == 1) % If on first dimension, no others fit break else % Can safely remove any other incrementation in this dimension t(l:d_minus) = c_test(l:d_minus); end end if (t(1) >= c_ord+1) % basis search exhausted for this c_ord break % break loop end end end basis.dim = basis.dim'; basis.ord = basis.ord'; basis.n_elems = n; end
github
CU-UQ/BASE_PC-master
basis_max_identify.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/basis_max_identify.m
904
utf_8
b377a9a54b380e6fdb0969c0ac3ed5ab
% contracts basis set based on solution coefficients % ----- % basis = basis_coord_max_identify(basis) % ----- % Input % ----- % basis = basis object % ------ % Output % ------ % basis = basis with corrected .max field function basis = basis_max_identify(basis) basis.max = zeros(1,basis.n_dim); % Must recompute maximum orders and dimension basis.max_ord = 0; basis.n_dim = 0; for k = 1:basis.n_elems this_ord = basis.ord{k}; this_dim = basis.dim{k}; x = size(this_dim,2); s = sum(this_ord); if sum(this_ord) > basis.max_ord basis.max_ord = s; end for kk = 1:x if(this_ord(kk) > basis.max(this_dim(kk))) basis.max(this_dim(kk)) = this_ord(kk); end if max(this_dim) > basis.n_dim basis.n_dim = max(this_dim); end end end basis.max = basis.max(1:basis.n_dim); basis.max_ord = max(basis.max); end
github
CU-UQ/BASE_PC-master
basis_anisotropic_validate.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/adaptation/basis_anisotropic_validate.m
9,033
utf_8
abe73ed43f91b6a4a8aecb370733972b
% validates new basis set from computed candidates % ----- %[basis_new, basis_opt, sample_rate_adj] = basis_validate(basis_old, c, tol, basis_opt, eval_opt) % ----- % Input % ----- % basis_old = old basis % sample = current sample % surrogate = surrogate information % tol = tolerance in solution computation % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_new = adjusted basis object % basis_opt = new basis_opt values % sample_rate_adj = flag returns true if sample_rate needs adjustment function [basis_new, basis_new_opt, min_solver_opt, min_sample, min_sol] = basis_anisotropic_validate(basis, sample, sol, basis_opt, eval_opt, solver_opt, max_elems) if ~solver_opt.basis_cross_validate % If false can significantly reduce computational cost return_to_cv_value = solver_opt.cross_validate; % Will overwrite this, so need to know to set it back; solver_opt.cross_validate = false; % Setting to false to speed computation end if norm(sol.c) == 0 % Here, c == 0, so no basis shape information. Expand and try. fprintf('Solution is zero vector.\n'); if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis, basis_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis basis_new = basis; basis_new_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end % First remove all zero coefficient elements if size(sol.c,1) == 1 % no contraction from one element fprintf('Basis has single function.\n'); basis_opt.ord = basis.max; if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis, basis_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis basis_new = basis; basis_new_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end [c_sorted, indices] = sort(abs(sol.c)); % Sort c basis.ord = basis.ord(indices); % Reorder these indices basis.dim = basis.dim(indices); % Reorder these indices ind = find(c_sorted>0,1); % First index remove_indices = 1:(ind-1); % Remove everything with zero indices % update basis to remove zero coefficients if ~isempty(remove_indices) % Sometimes nothing is removed active_indices = ind:basis.n_elems; % We remove first ind-1 elements basis.ord = basis.ord(active_indices); basis.dim = basis.dim(active_indices); basis.n_elems = basis.n_elems - ind + 1; basis = basis_max_identify(basis); end % This is our starting point. From here, we need only track when the % basis_max is lowered, inducing a change in basis_new. basis_opt.ord = basis.max; basis_opt.dim = basis.n_ if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis_exp, basis_exp_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis_exp,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights val_error = inf; if basis_exp.n_elems <= max_elems % If not need to contract until under element limit [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis val_error = sol.err; basis_new = basis_exp; basis_new_opt = basis_exp_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end % We now remove smallest coefficients until number of strikes is % reached or all indices are removed strikes = 0; cur_max = basis.max; cur_n_dim = basis.n_dim; while strikes < basis_opt.validation_strikes && 1 < basis.n_elems % 3 strikes typical for baseball analogy Loop over indices cur_ord = basis.ord{1}; % order associated with smallest coefficient cur_dim = basis.dim{1}; % dim associated with smallest coefficient basis.ord = basis.ord(2:basis.n_elems); % removed from basis basis.dim = basis.dim(2:basis.n_elems); % removed from basis basis.n_elems = basis.n_elems - 1; if sum(cur_ord == cur_max(cur_dim)) % Maximums may have changed with this element removed basis = basis_max_identify(basis); % Identify new maximum if basis.n_dim < cur_n_dim || sum(basis.max ~= cur_max) % Sometimes dimension is reduced, so evaluate that first or second will be error cur_max = basis.max; % Adjust these for future use cur_n_dim = basis.n_dim; basis_opt.ord = basis.max; basis_opt.dim = basis.n_dim; if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end basis_exp_opt = basis_expand_opt_identify(basis, basis_opt, eval_opt); % Id new basis opts. min_dim = min(basis_exp.n_dim,basis_exp_opt.dim); % Make appropriate changes to the basis, decreasing orders if they are smaller (max elems concerns complicates this slightly) basis_exp.max = basis_exp.max(1:min_dim); basis_exp.n_dim = min_dim; for k = 1: min_dim % Set maximum values basis_exp.max(k) = min(basis_exp_opt.ord(k),basis_exp.max(k)); end basis_exp.max_ord = max(basis_exp.max); removed_indices = []; for k = 1: basis_exp.n_elems; % Remove all appropriate basis functions from expanded basis cur_ord = basis_exp.ord{k}; cur_dim = basis_exp.dim{k}; if ~isempty(cur_dim) % We end up testing the constant function which messes up the next test if (max(cur_dim) > basis_exp.n_dim) || (sum(cur_ord./basis_exp.max(cur_dim)) > 1) % Again we test the condition first because 2nd will be error removed_indices = [removed_indices k]; %#ok<AGROW> Will remove that basis function end end end if ~isempty(removed_indices) % With removed indices from expanded basis, compute new cv solution. If max elems was hit, it's possible removed indices is blank. kept_indices = setdiff(1:basis_exp.n_elems, removed_indices); basis_exp.ord = basis_exp.ord(kept_indices); basis_exp.dim = basis_exp.dim(kept_indices); basis_exp.n_elems = size(basis_exp.ord,1); sample.lhs = sample.lhs(:,kept_indices); % As not fixing sampling yet, we just remove columns from lhs and wlhs sample.wlhs = sample.wlhs(:,kept_indices); if basis_exp.n_elems <= max_elems % Sometimes we need to contract to get under minimal element size [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis if (sol.err < val_error) % New minimizing basis and options. Only test if valid n_elems size basis_new = basis_exp; basis_new_opt = basis_exp_opt; val_error = sol.err; % New minimum error to beat min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; strikes = 0; % Reset strikes with identification of new minimum. else strikes = strikes+1; % Strike count if smaller basis didn't reduce error, break if too many strikes end end end end end end if ~solver_opt.basis_cross_validate % If false can significantly reduce computational cost min_solver_opt.cross_validate = return_to_cv_value; end end
github
CU-UQ/BASE_PC-master
basis_adjust.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/adaptation/basis_adjust.m
1,219
utf_8
dd9880be63df864abc92aa719f4dbb2a
% adjust basis set by contracting and expanding % ----- % basis_new = basis_adjust(basis_old, basis_opt, eval_opt) % ----- % Input % ----- % basis_old = old basis % c = coefficients for solution % tol = tolerance in solution computation % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_new = adjusted basis object % basis_opt = new basis_opt values function [basis, basis_opt, solver_opt, sol] = basis_adjust(basis, sample, sol, basis_opt, eval_opt, solver_opt, max_elems); if norm(sol.c) == 0 % Here, c == 0, so no basis shape information. fprintf('Solution is zero vector.\n'); basis_new = basis_old; return end basis_new = basis_contract(basis_old, sol, sol.err*basis_opt.remove_perc); % Contract basis based on validated error if basis_opt.order_bounds basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis_new, basis_opt] = basis_expand(basis_new, basis_opt, eval_opt); if basis.n_elems > max_elems basis.ord = basis.ord(1:max_elems); basis.dim = basis.dim(1:max_elems); basis = basis_max_identify(basis); % Identify new maximum end end
github
CU-UQ/BASE_PC-master
basis_adjust_with_validation.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/adaptation/basis_adjust_with_validation.m
5,782
utf_8
5685b8998470529f8449cb60bfd2eb33
% validates new basis set from computed candidates % ----- %[basis_new, basis_opt, sample_rate_adj] = basis_validate(basis_old, c, tol, basis_opt, eval_opt) % ----- % Input % ----- % basis_old = old basis % sample = current sample % surrogate = surrogate information % tol = tolerance in solution computation % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_new = adjusted basis object % basis_opt = new basis_opt values % sample_rate_adj = flag returns true if sample_rate needs adjustment function [basis_new, basis_new_opt] = basis_adjust_with_validation(basis, sample, surrogate, basis_opt, eval_opt) if norm(surrogate.c) == 0 % Here, c == 0, so no basis shape information. fprintf('Solution is zero vector.\n'); basis_new = basis; basis_new_opt = basis_opt; return end % First remove all zero coefficient elements if size(surrogate.c,1) == 1 % no contraction from one element fprintf('Basis has single function'); [basis_new, basis_new_opt] = basis_expand(basis,basis_opt,eval_opt); % Expand dand hope fixes problem. return end [c_sorted, indices] = sort(abs(surrogate.c)); % Sort c basis.ord = basis.ord(indices); % Reorder these indices basis.dim = basis.dim(indices); % Reorder these indices ind = find(c_sorted>0,1); % First index n_indices = size(indices,1); % total number of indices remove_indices = 1:(ind-1); % Remove everything with zero indices % update basis to remove zero coefficients if ~isempty(remove_indices) % Sometimes nothing is removed active_indices = ind:basis.n_elems; % We remove first ind-1 elements basis.ord = basis.ord(active_indices); basis.dim = basis.dim(active_indices); basis.n_elems = basis.n_elems - ind + 1; basis = basis_max_identify(basis); end % This is our starting point. From here, we need only track when the % basis_max is lowered, inducing a change in basis_new. [basis_new, basis_new_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis_new,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights basis_exp = basis_new; n_dims = size(basis_new.max,2); basis_exp_opt = basis_new_opt; sol = solution_identify(sample,solver_opt); % Solution in error in this basis val_error = sol.err; % We now remove smallest coefficients until number of strikes is % reached or all indices are removed strikes = 0; cur_max = basis.max; cur_max_ord = basis.max_ord; while strikes <= basis_opt.strikes && ind < n_indices % 3 strikes typical for baseball analogy Loop over indices cur_ord = basis.ord{ind}; cur_dim = basis.dim{ind}; basis.ord = basis.ord([1:ind-1 ind+1:basis.n_elems]); basis.dim = basis.dim([1:ind-1 ind+1:basis.n_elems]); basis.n_elems = basis.n_elems - 1; if sum(cur_ord == cur_max(cur_dim)) || sum(cur_ord) == cur_max_ord % Maximums may have changed with this element removed basis = basis_max_identify(basis); % Identify new maximum if sum(basis.max ~= cur_max) || basis.max_ord ~= cur_max_ord % One will hold if max is changed dif_max = basis.max - cur_max; % to adjust expanded basis cur_max = basis.max; % Whatever ord has changed cur_max_ord = basis.max_ord; % Whatever ord has changed dif_max = [dif_max,zeros(1,n_dims- size(dif_max,2))]; %#ok<AGROW> % Extend dif_max to new value basis_exp.max = basis_exp.max+dif_max; basis_exp.max_ord = max(basis_exp.max); n_elems = basis_exp.n_elems; removed_indices = []; for k = 1: n_elems % Remove all appropriate basis functions from expanded basis cur_ord = basis_exp.ord{k}; cur_dim = basis.dim{k}; if sum(cur_ord./basis_exp.max(cur_dim)) > 1 removed_indices = [removed_indices k]; %#ok<AGROW> basis_exp.ord = basis_exp.ord([1:k-1 k+1:basis_exp.n_elems]); basis_exp.dim = basis_exp.dim([1:k-1 k+1:basis_exp.n_elems]); basis_exp.n_elems = basis_exp.n_elems - 1; end end if ~isempty(removed_indices) % With removed indices from expanded basis, compute new cv solution indices_to_keep = setdiff(1:n_elems, removed_indices); sample.lhs = sample.lhs(:,indices_to_keep); % As not fixing sampling yet, we just remove columns from lhs and wlhs sample.wlhs = sample.wlhs(:,indices_to_keep); if basis_exp.n_elems <= max_elems % Sometimes we need to contract to get under minimal element size sol = solution_identify(sample,solver_opt); % Solution in error in this basis if (sol.err < val_error) % New minimizing basis basis_new = basis_exp; basis_exp_opt.ord = basis_exp.max; basis_new_opt = basis_exp_opt; val_error = sol_error; % New minimum error to beat else strikes = strikes+1; % Strike because smaller basis didn't reduce error end end end end end ind = ind+1; % Prepare to Remove next index end end
github
CU-UQ/BASE_PC-master
basis_update.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/adaptation/basis_update.m
2,851
utf_8
073c79e6a349339bfb88bdaa37ddcbf5
% adjust basis set by contracting and expanding % ----- % basis_new = basis_adjust(basis_old, basis_opt, eval_opt) % ----- % Input % ----- % basis_old = old basis % c = coefficients for solution % tol = tolerance in solution computation % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_new = adjusted basis object % basis_opt = new basis_opt values % sample_rate_adj = flag returns true if sample_rate needs adjustment function [min_basis, min_basis_opt] = basis_update(basis_old, sample, surrogate, tol, basis_opt, eval_opt, solver_opt, n_iters, max_elems) % initialize with initial basis min_err = surrogate.err; min_basis = basis_old; basis = basis_old; min_basis_opt = basis_opt; old_coeff = basis_opt.expand_coeff; % Lowered each iteration to attempt to identify less expansive expansions. old_dim_add = basis_opt.dim_add; for k = 1:n_iters % start with contraction amongst minimizing basis basis = basis_contract(basis, surrogate.c, tol, basis_opt.remove_perc); sample.lhs = basis_eval(basis,sample.rv,eval_opt); sample.wlhs = apply_weights(sample.w,sample.lhs); surrogate = id_coefficients(sample, solver_opt); % if error reduced over previous basis if surrogate.err < min_err min_basis = basis; min_basis_opt = basis_opt; min_err = surrogate.err; end var_coefs = variance_by_coord(basis,surrogate.c,1); var_ord = order_percentage(basis,1); ord_indices = max(var_coefs-var_ord,0); ord_indices = basis_opt.expand_coeff*ord_indices/max(ord_indices); % then expand new basis [basis, basis_opt] = basis_coord_expand(basis, basis_opt, eval_opt, ord_indices); if basis.n_elems > max_elems % occassionaly the number of elements can be too large. % Reduce basis to maximal size basis.ord = basis.ord(1:max_elems); basis.dim = basis.dim(1:max_elems); basis.n_elems = max_elems; end sample.lhs = basis_eval(basis,sample.rv,eval_opt); sample.wlhs = apply_weights(sample.w,sample.lhs); surrogate = id_coefficients(sample, solver_opt); % check again if surrogate.err < min_err min_basis = basis; min_basis_opt = basis_opt; min_err = surrogate.err; end % reduce tolerance for subsequent iterations tol = tol/3; % reduce expansion coefficient basis_opt.expand_coeff = sqrt(basis_opt.expand_coeff); % reduce new dimensions to add per iteration basis_opt.dim_add = max(1,ceil(basis_opt.dim_add/1.3)); end min_basis_opt.dim_add = old_dim_add; basis_opt.expand_coeff = old_coeff; end
github
CU-UQ/BASE_PC-master
basis_validation_anisotropic_total_order.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/adaptation/basis_validation_anisotropic_total_order.m
9,589
utf_8
a2edfa9f45653e532a3a1fd9c7568cb6
% validates new basis set from computed candidates % ----- %[basis_new, basis_opt, sample_rate_adj] = basis_validate(basis_old, c, tol, basis_opt, eval_opt) % ----- % Input % ----- % basis_old = old basis % sample = current sample % surrogate = surrogate information % tol = tolerance in solution computation % basis_opt = options associated with basis % eval_opt = options related to evaluation % ------ % Output % ------ % basis_new = adjusted basis object % basis_opt = new basis_opt values % sample_rate_adj = flag returns true if sample_rate needs adjustment function [basis_new, basis_new_opt, min_solver_opt, min_sample, min_sol, exit_flag] = basis_validation_anisotropic_total_order(basis, sample, sol, basis_opt, eval_opt, solver_opt) original_error = sol.err; original_sample = sample; original_basis = basis; original_basis_opt = basis_opt; original_solver_opt = solver_opt; original_sol = sol; exit_flag = false; if ~solver_opt.basis_cross_validate % If false can significantly reduce computational cost return_to_cv_value = solver_opt.cross_validate; % Will overwrite this, so need to know to set it back; solver_opt.cross_validate = false; % Setting to false to speed computation end if norm(sol.c) == 0 % Here, c == 0, so no basis shape information. Expand and try. fprintf('Solution is zero vector.\n'); if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis, basis_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis basis_new = basis; basis_new_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end % First remove all zero coefficient elements if size(sol.c,1) == 1 % no contraction from one element fprintf('Basis has single function.\n'); basis_opt.ord = basis.max; if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis, basis_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis basis_new = basis; basis_new_opt = basis_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end [c_sorted, indices] = sort(abs(sol.c)); % Sort c basis.ord = basis.ord(indices); % Reorder these indices basis.dim = basis.dim(indices); % Reorder these indices ind = find(c_sorted>0,1); % First index remove_indices = 1:(ind-1); % Remove everything with zero indices % update basis to remove zero coefficients if ~isempty(remove_indices) % Sometimes nothing is removed active_indices = ind:basis.n_elems; % We remove first ind-1 elements basis.ord = basis.ord(active_indices); basis.dim = basis.dim(active_indices); basis.n_elems = basis.n_elems - ind + 1; basis = basis_max_identify(basis); end % This is our starting point. From here, we need only track when the % basis_max is lowered, inducing a change in basis_new. basis_opt.ord = basis.max; basis_opt.dim = basis.n_dim; if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end [basis_exp, basis_exp_opt] = basis_expand(basis, basis_opt, eval_opt); % This is our new expanded basis sample.lhs = basis_eval(basis_exp,sample.rv,eval_opt); % We don't reset weights as not correction sampling yet sample.wlhs = apply_weights(sample.w,sample.lhs); % So we just apply known weights val_error = inf; if basis_exp.n_elems <= basis_opt.max_elems % If not need to contract until under element limit [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis val_error = sol.err; basis_new = basis_exp; basis_new_opt = basis_exp_opt; min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; end % We now remove smallest coefficients until number of strikes is % reached or all indices are removed strikes = 0; cur_max = basis.max; cur_n_dim = basis.n_dim; while strikes < basis_opt.validation_strikes && 1 < basis.n_elems % 3 strikes typical for baseball analogy Loop over indices cur_ord = basis.ord{1}; % order associated with smallest coefficient cur_dim = basis.dim{1}; % dim associated with smallest coefficient basis.ord = basis.ord(2:basis.n_elems); % removed from basis basis.dim = basis.dim(2:basis.n_elems); % removed from basis basis.n_elems = basis.n_elems - 1; if sum(cur_ord == cur_max(cur_dim)) % Maximums may have changed with this element removed basis = basis_max_identify(basis); % Identify new maximum if basis.n_dim < cur_n_dim || sum(basis.max ~= cur_max) % Sometimes dimension is reduced, so evaluate that first or second will be error cur_max = basis.max; % Adjust these for future use cur_n_dim = basis.n_dim; basis_opt.ord = basis.max; basis_opt.dim = basis.n_dim; if basis_opt.order_bounds % Update order bounds if appropriate basis_opt = basis_order_bounds(basis_opt, eval_opt); end basis_exp_opt = basis_expand_opt_identify(basis, basis_opt, eval_opt); % Id new basis opts. min_dim = min(basis_exp.n_dim,basis_exp_opt.dim); % Make appropriate changes to the basis, decreasing orders if they are smaller (max elems concerns complicates this slightly) basis_exp.max = basis_exp.max(1:min_dim); basis_exp.n_dim = min_dim; for k = 1: min_dim % Set maximum values basis_exp.max(k) = min(basis_exp_opt.ord(k),basis_exp.max(k)); end basis_exp.max_ord = max(basis_exp.max); removed_indices = []; for k = 1: basis_exp.n_elems; % Remove all appropriate basis functions from expanded basis cur_ord = basis_exp.ord{k}; cur_dim = basis_exp.dim{k}; if ~isempty(cur_dim) % We end up testing the constant function which messes up the next test if (max(cur_dim) > basis_exp.n_dim) || (sum(cur_ord./basis_exp.max(cur_dim)) > 1) % Again we test the condition first because 2nd will be error removed_indices = [removed_indices k]; %#ok<AGROW> Will remove that basis function end end end if ~isempty(removed_indices) % With removed indices from expanded basis, compute new cv solution. If max elems was hit, it's possible removed indices is blank. kept_indices = setdiff(1:basis_exp.n_elems, removed_indices); basis_exp.ord = basis_exp.ord(kept_indices); basis_exp.dim = basis_exp.dim(kept_indices); basis_exp.n_elems = size(basis_exp.ord,1); sample.lhs = sample.lhs(:,kept_indices); % As not fixing sampling yet, we just remove columns from lhs and wlhs sample.wlhs = sample.wlhs(:,kept_indices); if basis_exp.n_elems <= basis_opt.max_elems % Sometimes we need to contract to get under minimal element size [sol, solver_opt] = solution_identify(sample,solver_opt); % Solution in error in this basis if (sol.err < val_error) % New minimizing basis and options. Only test if valid n_elems size basis_new = basis_exp; basis_new_opt = basis_exp_opt; val_error = sol.err; % New minimum error to beat min_solver_opt = solver_opt; min_sample = sample; min_sol = sol; strikes = 0; % Reset strikes with identification of new minimum. else strikes = strikes+1; % Strike count if smaller basis didn't reduce error, break if too many strikes end end end end end end if ~solver_opt.basis_cross_validate % If false can significantly reduce computational cost min_solver_opt.cross_validate = return_to_cv_value; end if val_error >= original_error % Possible that all of these bases were bad min_sol = original_sol; min_sample = original_sample; basis_new = original_basis; basis_new_opt = original_basis_opt; min_solver_opt = original_solver_opt; exit_flag = true; end end
github
CU-UQ/BASE_PC-master
basis_contract.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/contraction/basis_contract.m
1,570
utf_8
3516bb2a58e83897a5ff19bc140a87d8
% contracts basis set based on solution coefficients % ----- % basis = basis_contract(basis, c, tol, remove_perc) % ----- % Input % ----- % basis = basis object % c = solution coefficients for corresponding basis % tol = solution tolerance % remove_perc = percentage of tolerance for discarding basis functions % ------ % Output % ------ % basis = contracted basis object function basis = basis_contract(basis, c, remove_perc) % First remove all zero coefficient elements if size(c,1) == 1 % no contraction from one element return end x = find(c == 0); c = abs(c); % Second remove smallest coefficients up to tol/3 threshold. i_sum = 0; c = c/norm(c,2); % Normalize so that entries correspond to fraction of variance explained roughly t_var = remove_perc; %Err on the side of taking extra basis functions remove coefficients up to removal_perc of tolerances while i_sum < t_var i = min(c(c>0)); if isempty(i) break end j = find(c==i,1); i_sum = i_sum+i^2; % Sum of variance kept to throw away if i_sum < t_var % Err on the side of taking extra basis functions x = [x; j]; %#ok<AGROW> c(j) = 0; end end % update basis appropriately if ~isempty(x) % Sometimes nothing is removed x = setdiff(1:basis.n_elems,x); % We tracked what we want to remove. basis.ord = basis.ord(x); basis.dim = basis.dim(x); basis.n_elems = size(basis.ord,1); basis_max_identify(basis); end end
github
CU-UQ/BASE_PC-master
basis_contract_by_number.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/contraction/basis_contract_by_number.m
1,286
utf_8
3408b419b5c05beeb705e7f343e751fe
% contracts basis set by specific number % ----- % basis = basis_contract_by_number(basis, c, number) % ----- % Input % ----- % basis = basis object % c = solution coefficients for corresponding basis % n_keep = approximate number of basis functions to keep % ------ % Output % ------ % basis = contracted basis object function basis = basis_contract_by_number(basis, c, n_keep) n_rem = basis.n_elems - n_keep; % Number of elements to remove % First remove all zero coefficient elements x = find(c == 0); % set of indices to be removed c = abs(c); % Second remove smallest coefficients up to tol/3 threshold. t_rem = size(x,1); while t_rem < n_rem i = min(c(c>0)); if isempty(i) break end j = find(c==i,1); t_rem = t_rem + 1; if t_rem < n_rem % Err on the side of an extra basis function x = [x; j]; %#ok<AGROW> c(j) = 0; end end % update basis appropriately if ~isempty(x) % Sometimes nothing is removed x = setdiff(1:basis.n_elems,x); % We tracked what we want to remove. basis.ord = basis.ord(x); basis.dim = basis.dim(x); basis.n_elems = size(basis.ord,1); basis = basis_max_identify(basis); end end
github
CU-UQ/BASE_PC-master
basis_expand_multiplicative.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/expansion/basis_expand_multiplicative.m
1,456
utf_8
8752ff719b0a7f31ccbaf7f03798c765
% expands basis set using given parameters % ----- % [basis_exp, basis_opt] = basis_expand(basis_c, basis_opt, eval_opt) % ----- % Input % ----- % basis_c = contracted basis % basis_opt = basis options % eval_opt = options related to evaluation % ------ % Output % ------ % basis_exp = expanded basis object % basis_opt = updated basis options function [basis_exp, basis_opt] = basis_expand_multiplicative(basis_c, basis_opt, eval_opt) basis_opt.dim = min(basis_c.n_dim+basis_opt.dim_add,eval_opt.max_dim); % In case of adaptive dimensionality ord = ceil(max(1,basis_c.max*basis_opt.expand_coeff)); % Increase order by at least 1 in each already on dimension (depending on present order), only by 1 in new dimensions % This number can be tuned basis_opt.ord = horzcat(ord, ones(1,basis_opt.dim-size(ord,2))); % Increase dim if needed if isfield(basis_c,'hyp') basis_opt.hyp = basis_c.hyp; % Hyperbolicity not adjusted end if basis_opt.order_bounds basis_opt.ord = horzcat(basis_opt.ord,zeros(1,size(basis_opt.ub,2)-size(basis_opt.ord,2))); % incase basis_opt.ord has dropped some dimensions basis_opt.ord = min(basis_opt.ord,basis_opt.ub); % basis_opt.ord = max(basis_opt.ord,basis_opt.lb); basis_opt.dim = find(basis_opt.ord>0,1,'last'); % Can change when using bounds. basis_opt.ord = basis_opt.ord(1:basis_opt.dim); end basis_exp = basis_init(basis_opt, eval_opt); end
github
CU-UQ/BASE_PC-master
basis_expand_opt_identify.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/expansion/basis_expand_opt_identify.m
1,465
utf_8
4fcaf2d6e1801af85a9bfcfd13444da9
% finds new basis_opt if expand were used, without identifying basis itself % ----- % [basis_exp, basis_opt] = basis_expand_opt_identify(basis_c, basis_opt, eval_opt) % ----- % Input % ----- % basis_c = contracted basis % basis_opt = basis options % eval_opt = options related to evaluation % ------ % Output % ------ % basis_opt = updated basis options function basis_opt = basis_expand_opt_identify(basis_c, basis_opt, eval_opt) basis_opt.dim = min(basis_c.n_dim+basis_opt.dim_add,eval_opt.max_dim); % In case of adaptive dimensionality ord = ceil(max(1,basis_c.max*basis_opt.expand_coeff)); % Increase order by at least 1 in each already on dimension (depending on present order), only by 1 in new dimensions % This number can be tuned basis_opt.ord = horzcat(ord, ones(1,basis_opt.dim-size(ord,2))); % Increase dim if needed if isfield(basis_c,'hyp') basis_opt.hyp = basis_c.hyp; % Hyperbolicity not adjusted end if isfield(basis_opt,'ub') basis_opt.ord = horzcat(basis_opt.ord,zeros(1,size(basis_opt.ub,2)-size(basis_opt.ord,2))); % incase basis_opt.ord has dropped some dimensions basis_opt.ord = min(basis_opt.ord,basis_opt.ub); if isfield(basis_opt,'lb') basis_opt.ord = max(basis_opt.ord,basis_opt.lb); end basis_opt.dim = find(basis_opt.ord>0,1,'last'); % Can change when using bounds. basis_opt.ord = basis_opt.ord(1:basis_opt.dim); end end
github
CU-UQ/BASE_PC-master
basis_coord_expand.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/expansion/basis_coord_expand.m
963
utf_8
0e3398eb6d60a924f07e5dddf4b76646
% expands basis set using given parameters % ----- % [basis_exp, basis_opt] = basis_coord_expand(basis_c, basis_opt, eval_opt) % ----- % Input % ----- % basis_c = contracted basis % basis_opt = basis options % eval_opt = options related to evaluation % ------ % Output % ------ % basis_exp = expanded basis object % basis_opt = updated basis options function [basis_exp, basis_opt] = basis_coord_expand(basis_c, basis_opt, eval_opt, ord_indices) basis_opt.ord = max(1,basis_c.max+ord_indices); % Increase order by 1 in new coordinate dimension basis_opt.dim = min(basis_c.n_dim+basis_opt.dim_add,eval_opt.max_dim); % In case of adaptive dimensionality basis_opt.ord = horzcat(basis_opt.ord, 1*ones(1,basis_opt.dim-size(basis_opt.ord,2))); % Increase dim if needed if isfield(basis_c,'hyp') % Not yet implemented well basis_opt.hyp = basis_c.hyp; % Hyperbolicity not adjusted end basis_exp = basis_init(basis_opt, eval_opt); end
github
CU-UQ/BASE_PC-master
basis_expand.m
.m
BASE_PC-master/base_pc_v1/basis/basis_adaptation/expansion/basis_expand.m
1,407
utf_8
d9e2ebfe0b8c4e30a9e8dff7b061099b
% expands basis set using given parameters % ----- % [basis_exp, basis_opt] = basis_expand(basis_c, basis_opt, eval_opt) % ----- % Input % ----- % basis_c = contracted basis % basis_opt = basis options % eval_opt = options related to evaluation % ------ % Output % ------ % basis_exp = expanded basis object % basis_opt = updated basis options function [basis_exp, basis_opt] = basis_expand(basis_c, basis_opt, eval_opt) basis_opt.dim = min(basis_c.n_dim+basis_opt.dim_add,eval_opt.max_dim); % In case of adaptive dimensionality ord = basis_c.max+1; % Increase order by at least 1 in each already on dimension (depending on present order), only by 1 in new dimensions % This number can be tuned basis_opt.ord = horzcat(ord, ones(1,basis_opt.dim-size(ord,2))); % Increase dim if needed if isfield(basis_c,'hyp') basis_opt.hyp = basis_c.hyp; % Hyperbolicity not adjusted end if basis_opt.order_bounds basis_opt.ord = horzcat(basis_opt.ord,zeros(1,size(basis_opt.ub,2)-size(basis_opt.ord,2))); % incase basis_opt.ord has dropped some dimensions basis_opt.ord = min(basis_opt.ord,basis_opt.ub); % basis_opt.ord = max(basis_opt.ord,basis_opt.lb); basis_opt.dim = find(basis_opt.ord>0,1,'last'); % Can change when using bounds. basis_opt.ord = basis_opt.ord(1:basis_opt.dim); end basis_exp = basis_init(basis_opt, eval_opt); end
github
CU-UQ/BASE_PC-master
qoi_eval.m
.m
BASE_PC-master/base_pc_v1/other/qoi_eval.m
1,329
utf_8
eb81164177fb68de7d8964f44520e6e7
% call to evaluate qoi % ----- % rhs = qoi_eval(input,eval_opt) % ----- % Input % ----- % input = point where qoi is evaluated % eval_opt = options for evaluating input and QoI % ------ % Output % ------ % qoi = vector of qoi and derivative information if requested, indexed appropriately function qoi = qoi_eval(input,eval_opt) n_evals = size(input,1); if eval_opt.grad n_rows = eval_opt.grad_dim+1; if eval_opt.parallel_qoi_eval qoi = zeros(n_evals,n_rows); parfor k = 1:n_evals % Probably easiest to reshape qoi for parallelization qoi(k,:) = eval_opt.qoi_handle(input(k,:),eval_opt)'; %#ok<PFBNS> end qoi = qoi(:); else qoi = zeros(n_rows*n_evals,1); set = 1:n_rows; for k = 1:n_evals qoi(set) = eval_opt.qoi_handle(input(k,:),eval_opt); set = set + n_rows; end end else qoi = zeros(n_evals,1); if eval_opt.parallel_qoi_eval parfor k = 1:n_evals qoi(k) = eval_opt.qoi_handle(input(k,:),eval_opt); %#ok<PFBNS> end else for k = 1:n_evals qoi(k) = eval_opt.qoi_handle(input(k,:),eval_opt); end end end end
github
CU-UQ/BASE_PC-master
order_by_coord.m
.m
BASE_PC-master/base_pc_v1/other/order_by_coord.m
673
utf_8
3a27a632c9285818dbd8a225d2151466
% percentage of basis order in each coordinate % ----- % v = order_by_coord(basis) % ----- % Input % ----- % basis = basis object % ------ % Output % ------ % v = fraction of basis order in each coordinate function v = order_by_coord(basis) v = zeros(1,basis.n_dim); tot_v = 0; for j = 1:basis.n_elems this_dim = basis.dim{j}; this_ord = basis.ord{j}; n_dims = size(this_dim,2); if(~isempty(basis.dim{j})) tot_v = tot_v+1; tot_ord = sum(this_ord); for i = 1:n_dims v(this_dim(i)) = v(this_dim(i)) + this_ord(i)/tot_ord; end end end v = v/tot_v; end
github
CU-UQ/BASE_PC-master
default_parameters.m
.m
BASE_PC-master/base_pc_v1/other/default_parameters.m
4,354
utf_8
a526d506380d946c760b8a3a3e7ad11a
% generates default options from few problem/computer dependent options % ----- % [basis_opt, eval_opt, sample_opt, solver_opt] = default_parameters(pool_data,dim,eval_type,qoi_handle) % ----- % Input % ----- % pool_data = grabs pool_data.NumWorkers for use % dim = dimension of problem (scalar) % eval_type = type of random variable (character) % qoi_handle = handle object for evaluating qoi (@zero_eval is a good choice if QoI not of interest or not called from MATLAB % ------ % Output % ------ % basis_opt = options associated with basis % eval_opt = options associated with evaluation % sample_opt = options associated with sample % solver_opt = options associated with solver function [basis_opt, eval_opt, sample_opt, solver_opt] = default_parameters(pool_data,dim,eval_type,qoi_handle) % Slated for removal eval_opt.parallel_qoi_eval = false; % Rarely useful for these implementations solver_opt.basis_cross_validate = true; % Maybe always utilize cross-validation in basis tuning : %Turn off cross validation in basis identification. Can save significant computation. basis_opt.expand_coeff = 1.1; % Should always use +1 order basis expansion % Order expansion is done multiplicatively (with ceiling function) Lower numbers insure+1 effectiveness. % solver_opt.n_folds = 24; % Number of cross-validation folds. Best just as solver_opt.n_folds_pw basis_opt.order_bounds = false; % Alternative expansion methods should render this unnecessary. % Evaluation Related Options eval_opt.grad = false; % Requires compatible RHS evaluation. Usually not used. eval_opt.grad_dim = 0; % Number of dimensions with gradients. Zero in this case. eval_opt.max_dim = dim; % Maximum dimension of problem. eval_opt.p_type = repmat(eval_type,1,eval_opt.max_dim); % Type of polynomial 'l' for legendre, 'h' for hermite. Also defines sample rvs. eval_opt.qoi_handle = qoi_handle; % Sample Related Options sample_opt.sr = 0; % Minimal Sampling Rate sample_opt.initial_size = 10; % Useful starting point for many problems. sample_opt.n_workers = pool_data.NumWorkers; sample_opt.min_sample_percent = 0.1; % Minimum fraction of current sample size to generate at each iteration sample_opt.max_sample_percent = 1; % Maximum fraction of current sample size to generate at each iteration sample_opt.burn_in = 5000; % Number of burn-in samples sample_opt.log_col_rate = -32; % Logarithm of collision rate (MCMC samples to be discarded) sample_opt.w_handle = @l2_w; % Minimize l2-coherence sample_opt.w_correction_handle = @l2_correction_w; % Minimize l2-coherence with correction sampling sample_opt.prop_handle = @orth_prop; % input proposals are from orthogonality measure sample_opt.max_samps = 3000; % Maximum number of aggregate samples % Solver Related Options solver_opt.cross_validate = true; % Enhances stability of estimates and accuracy of error estimate solver_opt.n_workers = pool_data.NumWorkers; % Number of parallel workers from pool to use solver_opt.n_folds_pw = 6; % Number of CV folds evaluated per worker solver_opt.cv_mesh_size = 20; % Number of error tolerances in each cross-validation search. solver_opt.solver_handle = @bpdn; % Solver used for regression solver_opt.log_tol_exp = 0.1; % Amount for tolerance adjustment self-adjusts well solver_opt.comp_samp_perc = 0.8; % Proportion of samples to use for computation, one minus this is proportion for validation basis_opt.max_elems = 3000; % Maximum number of elements in expansion, generally scales with sample_opt.max_samps basis_opt.type_handle = @basis_anisotropic_total_order; % Initial basis is 'to' total order basis_opt.dim = dim; % Number of initial dimensions basis_opt.ord = ones(1,basis_opt.dim); % Initial total order of approximation basis_opt.pc_flag = false; % Whether or not to identify preconditioner, mostly useful for gradient methods basis_opt.validation_strikes = 6; % Number of strikes for basis validation basis_opt.dim_add = 2; % Number of dimensions to add order 1 approximation to. basis_opt.validation_iters = 3; % Number of iterations for basis adaptation. basis_opt.basis_identify_handle = @basis_validation_anisotropic_total_order; % Validated basis are anisotropic total order end
github
CU-UQ/BASE_PC-master
variance_by_coord.m
.m
BASE_PC-master/base_pc_v1/other/variance_by_coord.m
759
utf_8
a5849cef29b0e54def83848b298ddc8c
% decomposes variance by coordinate using pce coefficients % ----- % v = variance_by_coord(basis,c) % ----- % Input % ----- % basis = basis object % c = solution coefficients % ------ % Output % ------ % v = fraction of variance in each coordiante function v = variance_by_coord(basis,c) v = zeros(1,basis.n_dim); tot_v = 0; for j = 1:basis.n_elems this_v = c(j)^2; this_dim = basis.dim{j}; this_ord = basis.ord{j}; n_dims = size(this_dim,2); if(~isempty(basis.dim{j})) tot_ord = sum(this_ord); tot_v = tot_v + this_v; for i = 1:n_dims v(this_dim(i)) = v(this_dim(i)) + this_v*this_ord(i)/tot_ord; end end end v = v/tot_v; end
github
CU-UQ/BASE_PC-master
sobol_indices.m
.m
BASE_PC-master/base_pc_v1/other/sobol_indices.m
789
utf_8
2f8104543db7f6f8293f016fe23140e4
% Computes Sobol Indices and estimate variance % ----- % [sobol, dim_index var] = sobol_indices(c, basis) % ----- % Input % ----- % c = coefficients associated with basis % basis = associated basis % ------ % Output % ------ % sobol = Sobol indices sorted in decreasing order % dim_index = dimensions sorted in decreasing order of sobol index % var = total estimated variance function [sobol, dim_index, var] = sobol_indices(c, basis) var = 0; % Will be computed as well sobol = zeros(basis.n_dim,1); for i = 1:basis.n_elems if ~isempty(basis.ord{i}) var = var + c(i).^2; for k = 1:size(basis.dim{i},2) sobol(basis.dim{i}(k)) = sobol(basis.dim{i}(k)) + c(i).^2; end end end sobol = sobol/var; [sobol,dim_index] = sort(sobol,'descend'); end
github
CU-UQ/BASE_PC-master
apply_weights.m
.m
BASE_PC-master/base_pc_v1/other/apply_weights.m
487
utf_8
5cf49bd587e516750e2af5d120dbda48
% applies weights to matrix % ----- % mat = apply_weights(w,mat); % ----- % Input % ----- % w = weights % mat = matrix to apply weights to % ------ % Output % ------ % mat = matrix with weights applied function mat = apply_weights(w,mat) n1 = size(w,1); n2 = size(mat,1); k = n2/n1; if k == 1 mat = bsxfun(@times, w, mat); return end set = 1:n1; for j = 1:k mat(set,:) = bsxfun(@times, w, mat(set,:)); set = set+1; end end
github
CU-UQ/BASE_PC-master
validate_coefficients.m
.m
BASE_PC-master/base_pc_v1/solver/validate_coefficients.m
2,336
utf_8
59f8cf05c6b7772ab2ef5b6d45c1ac33
% Computes solution and error estimate without cross-validating tolerance (uses specified tolerance parameter) % ----- % sol = validate_coefficients(sample,solver_opt) % ----- % Input % ----- % sample = sample object % solver_opt = options for identifying solution % ------ % Output % ------ % sol = solution object function sol = validate_coefficients(sample,solver_opt) index = 1:solver_opt.n_workers:sample.n_folds; % Main computation spmd (solver_opt.n_workers) % Loop over folds to compute error f_tol = sol_validate_serial(sample, sample.folds(index+labindex-1,:), solver_opt, solver_opt.sig); % No cross-validation of tolerance end % Combine the folds f_tol = sum(cell2mat(f_tol(:))); % Realizations of ratio of unexplained variance sol.c = solver_opt.solver_handle(sample.wlhs, sample.wrhs, solver_opt.sig); sol.err = sqrt(f_tol/(solver_opt.n_workers*solver_opt.n_folds_pw)); sol.sig = solver_opt.sig; end function f_tol = sol_validate_serial(sample, folds, solver_opt, tol) n_rows = floor(size(sample.wrhs,1)/sample.n_samps); % For gradient information inclusion c_samps = min(floor(solver_opt.comp_samp_perc*sample.n_samps),sample.n_samps-1); % Need at least 1 validation sample. v_samps = sample.n_samps - c_samps; % validation samples f_tol = 0; % Holding TVA for each tolerance for k = 1:solver_opt.n_folds_pw % Loop over number of folds this_fold = folds(k,:); comp_samps = zeros(n_rows*c_samps,1);% Acquire computation samples for j = 1:c_samps % Loop over the appropriate indices comp_samps(((j-1)*n_rows+1):(j*n_rows)) = (1+(this_fold(j)-1)*n_rows):(this_fold(j)*n_rows); end val_samps = zeros(n_rows*v_samps,1); % Acquire validation samples for j = 1:v_samps % Loop over the appropriate indices val_samps(((j-1)*n_rows+1):(j*n_rows)) = (1+(this_fold(j+c_samps)-1)*n_rows):(this_fold(j+c_samps)*n_rows); end c_hat = solver_opt.solver_handle(sample.wlhs(comp_samps,:), sample.wrhs(comp_samps), tol); % Compute solution from computation samples f_tol = f_tol + (norm(sample.wlhs(val_samps,:)*c_hat-sample.wrhs(val_samps))/norm(sample.wrhs(val_samps)))^2; % This sums estimates of Fraction of Variance Unexplained, computed from validation samples end end
github
CU-UQ/BASE_PC-master
solution_identify.m
.m
BASE_PC-master/base_pc_v1/solver/solution_identify.m
891
utf_8
54fe7a337fd3c0288d11a490e5d9105c
% calls for a new solution to be computed from a sample % ----- % sol = solution_identify(sample,solver_opt) % ----- % Input % ----- % sample = sample object % solver_opt = options for identifying solution % ------ % Output % ------ % sol = solution object function [sol, solver_opt] = solution_identify(sample,solver_opt) sample = folds_identify(sample, solver_opt); if ~isfield(solver_opt,'sig') solver_opt.sig = 1; % Initialize relative error to 1 for solver, as for using a zero surrogate. end if solver_opt.cross_validate % cross-validate sol = cross_validate_coefficients(sample,solver_opt); solver_opt.sig = min(1,max(sol.sig,sol.err)); % sol.sig is better, but if sol.err larger, indicates higher relative errors. Should always be less than 1 else % no cross-validation sol = validate_coefficients(sample,solver_opt); end end
github
CU-UQ/BASE_PC-master
folds_identify.m
.m
BASE_PC-master/base_pc_v1/solver/folds_identify.m
555
utf_8
cd42e2fb07fb836b45827d2779431a69
% identifies new validation folds when sample size is increased % ----- % sol = folds_identify(sample,solver_opt) % ----- % Input % ----- % sample = sample object % solver_opt = options for identifying solution % ------ % Output % ------ % sample = sample object function sample = folds_identify(sample, solver_opt) sample.n_folds = solver_opt.n_workers*solver_opt.n_folds_pw; sample.folds = zeros(sample.n_folds,sample.n_samps); for k = 1:sample.n_folds % Build fold sets sample.folds(k,:) = randperm(sample.n_samps); end end
github
CU-UQ/BASE_PC-master
cross_validate_coefficients.m
.m
BASE_PC-master/base_pc_v1/solver/cross_validate_coefficients.m
3,693
utf_8
14775fc02a0e02452f3085383e4888d1
% Computes solution with cross-validated error % ----- % sol = cross_validate_coefficients(sample,solver_opt) % ----- % Input % ----- % sample = sample object % solver_opt = options for identifying solution % ------ % Output % ------ % sol = solution object function sol = cross_validate_coefficients(sample,solver_opt) index = 1:solver_opt.n_workers:sample.n_folds; % Splits folds appropriately % Main computation min_log_tol = min(-2,solver_opt.log_tol_exp*log(solver_opt.sig+10^(-10))); % minimum log of tolerance considered here is always a bit lower than desired tolerance max_log_tol = min(0, log((solver_opt.log_tol_exp+1)*solver_opt.sig+10^(-10))); % maximum log of tolerance considered. solver_opt.sig is approximately of order of tolerance in ideal world. This gives leeway inc = (max_log_tol-min_log_tol)/(solver_opt.cv_mesh_size-2); t_tols = [0 exp(min_log_tol:inc:max_log_tol)]'; % Test Tolerances. spmd (solver_opt.n_workers) f_tols = sol_cv_serial(sample, sample.folds(index+labindex-1,:), solver_opt, t_tols); end % Combine the folds f_tols = cell2mat(f_tols(:)); % Realizations of ratio of unexplained variance n_tols = size(t_tols,1); f = zeros(n_tols,1); index = 1:n_tols; for k = 1:solver_opt.n_workers f = f+f_tols(index); % Sums all relevant realized errors over sample.n_folds (Fraction of variance unexplained) index = index+n_tols; end % Best_tol minimizes f over the folds [best_f, best_i] = min(f); best_sig = t_tols(best_i); sol.err = sqrt(best_f/(solver_opt.n_folds_pw*solver_opt.n_workers)); % This is the estimate of RRMSE (Relative Root Mean Square Error) sol.sig = best_sig; sol.c = solver_opt.solver_handle(sample.wlhs, sample.wrhs, best_sig); end function f_tols = sol_cv_serial(sample, folds, solver_opt, t_tols) n_rows = floor(size(sample.wrhs,1)/sample.n_samps); % For gradient information inclusion c_samps = min(floor(solver_opt.comp_samp_perc*sample.n_samps),sample.n_samps-1); % Need at least 1 validation sample. v_samps = sample.n_samps - c_samps; % validation samples n_tols = size(t_tols,1); % Number of tolerances considered f_tols = zeros(n_tols,1); % Holding TVA for each tolerance for kk = 1:n_tols % Loop over tolerances tol = t_tols(kk); for k = 1:solver_opt.n_folds_pw % Loop over number of folds this_fold = folds(k,:); if n_rows > 1 comp_samps = zeros(n_rows*c_samps,1);% Acquire computation samples for j = 1:c_samps % Loop over the appropriate indices comp_samps(((j-1)*n_rows+1):(j*n_rows)) = (1+(this_fold(j)-1)*n_rows):(this_fold(j)*n_rows); end val_samps = zeros(n_rows*v_samps,1); % Acquire validation samples for j = 1:v_samps % Loop over the appropriate indices val_samps(((j-1)*n_rows+1):(j*n_rows)) = (1+(this_fold(j+c_samps)-1)*n_rows):(this_fold(j+c_samps)*n_rows); end else comp_samps = this_fold(1:c_samps); % Conceptually much quicker when n_rows = 1 val_samps = this_fold(c_samps+1:sample.n_samps); % Conceptually much quicker when n_rows = 1 end c_hat = solver_opt.solver_handle(sample.wlhs(comp_samps,:), sample.wrhs(comp_samps), tol); % Compute solution vfom computation samples f_tols(kk) = f_tols(kk) + (norm(sample.wlhs(val_samps,:)*c_hat-sample.wrhs(val_samps))/norm(sample.wrhs(val_samps)))^2; % This sums estimates of Fraction of Variance Unexplained, computed from validation samples end end end
github
CU-UQ/BASE_PC-master
ell2solve.m
.m
BASE_PC-master/base_pc_v1/solver/solvers/ell2solve.m
409
utf_8
b63c99d4e2ac788047ac0becefe7e682
% Solves least squares, using mldivide % ----- % x = ell2solve(A,b,inv_lambda) % ----- % Input % ----- % A = lhs matrix % b = rhs vector % lambda = Tikhonov regularization parameter that may be cross-validated % ------ % Output % ------ % x = solution coeffs function x = ell2solve(A,b,lambda) if lambda > 0 nCols = size(A,2); A = [A; lambda*eye(nCols)]; b = [b; zeros(nCols,1)]; end x = A\b; end
github
CU-UQ/BASE_PC-master
bpdn.m
.m
BASE_PC-master/base_pc_v1/solver/solvers/bpdn.m
11,341
utf_8
0f7579b0aeb67a1f38e0da0adf49d392
% Solves BPDN % code modified from spgl1 https://www.math.ucdavis.edu/~mpf/spgl1/ % ----- % x = bpdn(A, b, sigma) % ----- % Input % ----- % A = lhs matrix % b = rhs vector % sigma = regularization parameter that may be cross-validated % ------ % Output % ------ % x = coefficient vector % % This code modifes spgl1.m and spg_bpdn.m as part of SPGL1 http://www.cs.ubc.ca/~mpf/spgl1/index.html having the following copyright % SPGL1 copyright % ------------------------------------------------------------------- % Copyright (C) 2007 Ewout van den Berg and Michael P. Friedlander, % Department of Computer Science, University of British Columbia, Canada. % All rights reserved. E-mail: <{ewout78,mpf}@cs.ubc.ca>. % % SPGL1 is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as % published by the Free Software Foundation; either version 2.1 of the % License, or (at your option) any later version. % % SPGL1 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 Lesser General % Public License for more details. % % You should have received a copy of the GNU Lesser General Public % License along with SPGL1; if not, write to the Free Software % Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 % USA % ---------------------------------------------------------------------- function x = bpdn(A,b,sigma) m = length(b); x = A\b; %%%%%%%%%%%%%%%%%%%% % function options % %%%%%%%%%%%%%%%%%%%% tau = 0; % Initialization of regularization parameter tau. maxIts = 1000*m; % 100 times standard size. Some problems require large numbers of iterations. However some problems seem to require very large iteration counts nPrevVals = 6; % twice standard size. Doesn't cost much. Can improve accuracy/speed. % bpTol = 1e-06; % We choose not to do this check (overlap with SUBOPTIMAL_BP SOL check) lsTol = 0.5e-09; % 0.0005 standard size. optTol = 1e-07; % reduced by 0.001 decTol = 1e-07; % reduced by 0.001 stepMin = 1e-16; stepMax = 1e+05; maxLineErrors = 20; % Maximum number of line-search failures. Twice typical value % Appropriate relativization of sigma for b. b_norm = norm(b); sigma = sigma*b_norm; % Normalizes sigma based on b_norm to be compatible across multiple rhs. %---------------------------------------------------------------------- % Initialize local variables. %---------------------------------------------------------------------- iter = 0; % Total SPGL1 iterations. lastFv = -inf(nPrevVals,1); % Last m function values. stat = false; testUpdateTau = 0; % Previous step did not update tau % Exit conditions (constants). EXIT_ROOT_FOUND = 1; %EXIT_BPSOL_FOUND = 2; EXIT_LEAST_SQUARES = 3; EXIT_ITERATIONS = 5; EXIT_LINE_ERROR = 6; EXIT_SUBOPTIMAL_BP = 7; % Project the starting point and evaluate function and gradient. x = project(x,tau); % Soft Thresholding with parameters determined by x,tau r = b - A*x; % Residual vector g = - A'*r; %Correlations with residuals f = r'*r / 2; % Residual Functional for many tests % Required for nonmonotone strategy. lastFv(1) = f; fBest = f; fOld = f; % Compute projected gradient direction and initial steplength. dx = project(x - g, tau) - x; dxNorm = norm(dx,inf); if dxNorm < (1 / stepMax) gStep = stepMax; else gStep = min(stepMax, max(stepMin, 1/dxNorm)); % stepMin > stepMax is possible. end while 1 % main loop % Compute quantities needed for log and exit conditions. gNorm = norm(g,inf); r_norm = norm(r, 2); gap = r'*(r-b) + tau*gNorm; rGap = abs(gap) / max(1,f); aError1 = r_norm - sigma; aError2 = f - sigma^2 / 2; rError1 = abs(aError1) / max(1,r_norm); rError2 = abs(aError2) / max(1,f); % If rNorm is small, least squares solution. Can occur % if oversampled or exceptional approximation. if gNorm <= lsTol * r_norm % Occurs if no column has significant correlation with residual stat = EXIT_LEAST_SQUARES; end if rGap <= max(optTol, rError2) || rError1 <= optTol % The problem is nearly optimal for the current tau. % Check optimality of the current root. %if r_norm <= bpTol, stat=EXIT_BPSOL_FOUND; end % Resid minim'zd -> BP sol. if rError1 <= optTol, stat=EXIT_ROOT_FOUND; end % Found approx root. if r_norm <= sigma, stat=EXIT_SUBOPTIMAL_BP; end % Found suboptimal BP sol. end testRelChange1 = (abs(f - fOld) <= decTol * f); testRelChange2 = (abs(f - fOld) <= 1e-1 * f * (abs(r_norm - sigma))); testUpdateTau = ((testRelChange1 && r_norm > 2 * sigma) || ... (testRelChange2 && r_norm <= 2 * sigma)) && ~stat && ~testUpdateTau; if testUpdateTau % Update tau. tauOld = tau; tau = max(0,tau + (r_norm * aError1) / gNorm); if tau < tauOld % if decrease, project x = project(x,tau); end end if ~stat && iter >= maxIts % iteration limit stat = EXIT_ITERATIONS; end if stat %disp(stat); break; end % If done, break. iter = iter + 1; xOld = x; fOld = f; gOld = g; % in case search fails %--------------------------------------------------------------- % Projected gradient step and linesearch. %--------------------------------------------------------------- [f,x,r,lnErr] = spgLineCurvy(x,gStep*g,max(lastFv),A,b,tau); if lnErr % Projected backtrack failed. Retry with feasible dir'n linesearch. x = xOld; f = fOld; dx = project(x - gStep*g, tau) - x; gtd = g'*dx; [f,x,r,lnErr] = spgLine(f,x,dx,gtd,max(lastFv),A,b); end if lnErr % Failed again. Revert to previous iterates and damp max BB step. x = xOld; f = fOld; if maxLineErrors <= 0 stat = EXIT_LINE_ERROR; else stepMax = stepMax / 10; maxLineErrors = maxLineErrors - 1; end end %--------------------------------------------------------------- % Update gradient and compute new Barzilai-Borwein scaling. %--------------------------------------------------------------- if (~lnErr) g = - A'*r; s = x - xOld; y = g - gOld; sts = s'*s; sty = s'*y; if sty <= 0, gStep = stepMax; else gStep = min( stepMax, max(stepMin, sts/sty) ); end else gStep = min( stepMax, gStep ); end %------------------------------------------------------------------ % Update function history. %------------------------------------------------------------------ if f > sigma^2 / 2 % Don't update if superoptimal. lastFv(mod(iter,nPrevVals)+1) = f; if fBest > f fBest = f; end end end end function [fNew,xNew,rNew,err] = spgLineCurvy(x,g,fMax,A,b,tau) % Projected backtracking linesearch. % On entry, % g is the (possibly scaled) steepest descent direction. EXIT_CONVERGED = 0; EXIT_ITERATIONS = 1; EXIT_NODESCENT = 2; gamma = 1e-4; maxIts = 10; step = 1; sNorm = 0; scale = 1; % Safeguard scaling. Reduced if needed. nSafe = 0; % No. of safeguarding steps. iter = 0; n = length(x); while 1 % Evaluate trial point and function value. xNew = project(x - step*scale*g, tau); rNew = b - A*xNew; fNew = rNew'*rNew / 2; s = xNew - x; gts = scale * real(g' * s); % real suffices if gts >= 0 % can happen in poorly conditioned problem err = EXIT_NODESCENT; break end if fNew < fMax + gamma*step*gts % check convergence err = EXIT_CONVERGED; break elseif iter >= maxIts % check iteration limit err = EXIT_ITERATIONS; break end % New linesearch iteration. iter = iter + 1; step = step / 2; % If same point after projection, drastically damp next search. sNormOld = sNorm; sNorm = norm(s) / sqrt(n); if abs(sNorm - sNormOld) <= 1e-6 * sNorm gNorm = norm(g) / sqrt(n); scale = sNorm / gNorm / (2^nSafe); nSafe = nSafe + 1; end end end function [fNew,xNew,rNew,err] = spgLine(f,x,d,gtd,fMax,A,b) % Nonmonotone linesearch. EXIT_CONVERGED = 0; EXIT_ITERATIONS = 1; maxIts = 10; step = 1; iter = 0; gamma = 1e-4; gtd = -abs(gtd); % 03 Aug 07: If gtd is complex, % then should be looking at -abs(gtd). while 1 % Evaluate trial point and function value. xNew = x + step*d; rNew = b - A*xNew; fNew = rNew'*rNew / 2; % Check exit conditions. if fNew < fMax + gamma*step*gtd % Sufficient descent condition. err = EXIT_CONVERGED; break elseif iter >= maxIts % Too many linesearch iterations. err = EXIT_ITERATIONS; break end % New linesearch iteration. iter = iter + 1; % Safeguarded quadratic interpolation. if step <= 0.1 step = step / 2; else tmp = (-gtd*step^2) / (2*(fNew-f-step*gtd)); if tmp < 0.1 || tmp > 0.9*step || isnan(tmp) tmp = step / 2; end step = tmp; end end end function x = project(b,tau) % Get sign of b and set to absolute values s = sign(b); b = abs(b); % Initialization n = length(b); b_norm = norm(b,1); % Check for quick exit. if (tau >= b_norm), x = b; return; end x = zeros(n,1); % Initialize x here. if (tau < eps), return; end % Preprocessing (b is assumed to be >= 0) [b,idx] = sort(b,'descend'); % Descending. csb = -tau; alphaPrev = 0; for j= 1:n csb = csb + b(j); alpha = csb / j; % We are done as soon as the constraint can be satisfied % without exceeding the current minimum value of b if alpha >= b(j) break; end alphaPrev = alpha; end % Set the solution by applying soft-thresholding with % the previous value of alpha x(idx) = max(0,b - alphaPrev); % Restore signs in x x = x.*s; end
github
CU-UQ/BASE_PC-master
omp.m
.m
BASE_PC-master/base_pc_v1/solver/solvers/omp.m
3,079
utf_8
31d5408348df72fe1ebd17f5e038d011
% orthogonal matching pursuit % ----- % x = omp(A,b,tol) % ----- % Input % ----- % A = lhs matrix % b = rhs vector % tol = regularization parameter that may be cross-validated % ------ % Output % ------ % x = coefficient vector % x = omp(A, b, tol) % A,x, b = from Ax=b % tol = For stopping OMP and matrix operations. % This code modifies SolveOMP.m as part of SparseLAB https://sparselab.stanford.edu/ having the following copyrights % ----------------------------------------------------- % Copyright (c) 2006. Victoria Stodden and David Donoho % Copyright (c) 2006. Yaakov Tsaig % Part of SparseLab Version:100 % Created Tuesday March 28, 2006 function x = omp(A,b,tol) % Initialize eps = 1e-12; % Effective zero is needed due to some numerical instabilities tol = max(tol,eps); % if tol is too low, increase numRows = size(A,1); numCols = size(A,2); w = zeros(numCols,1); % weights make correlations most comparable for k = 1:numCols w(k) = 1/norm(A(:,k)); A(:,k) = A(:,k)*w(k); end x = zeros(numCols,1); actSet = []; % active set L = []; % For Cholesky decomposition nb = norm(b); if(nb <= eps) % RHS is numerically zero return end b = b/nb; % Normalize rhs (will renormalize solution later) r = b; % Residual to rhs. corrA = A'*b; % Correlation with RHS converged = false; % Main Loop iCols=0; while(~converged) iCols=iCols+1; % Size of ActiveSet corrSense = A'*r; corrSense(actSet) = zeros(size(actSet,2),1); [C, i] = max(abs(corrSense)); if C < eps x = w.*x*nb; return end [L, actSet, flag] = updateChol(L, A, actSet, i); if flag % Gramian has numerical instability x = zeros(numCols,1); x(actSet) = A(:,actSet)\b; % May not be ok? x = w.*x*nb; return end % Calculate New Residual x = zeros(numCols,1); x(actSet) = qcs(L,corrA(actSet)); % Compute new residual r = b - A(:,actSet) * x(actSet); % Check Convergence if(iCols==numRows-1||norm(r)<tol) converged=true; end end x = w.*x*nb; end % L = Upper Triangular Cholesky matrix % LL^T = A^TA. Restricted to columns in active Set % LL^Tx = A^TAx = z. function z = qcs(L, z) o.LT = true; ot.LT = true; ot.TRANSA = true; [w,~] = linsolve(L,z,o); [z,~] = linsolve(L,w,ot); end % L = existing Lower Triangular Cholesky matrix % index = index to be added function [L, activeSet, flag] = updateChol(L, A, activeSet, index) % Updates Cholesky factorization flag = 0; o.LT = true; nCols = size(activeSet,2); if(nCols==0) L = norm(A(:,index)); else [p,~] = linsolve(L,A(:,activeSet)'*A(:,index),o); q = 1-sum(p.^2); if q <= 0 % Can occur due to numerical issues flag = 1; return end L = [L zeros(nCols,1); p' sqrt(q)]; end activeSet = [activeSet index]; end