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
|
CohenBerkeleyLab/WRF_Utils-master
|
test_wrf_bl_height.m
|
.m
|
WRF_Utils-master/One-off Scripts/test_wrf_bl_height.m
| 3,712 |
utf_8
|
371c8d38efec5ce36408596fe62b02c5
|
function [ fraction_good, fraction_ok, fraction_undefined, indices_good, indices_ok, indices_bad, indices_undefined ] = test_wrf_bl_height( z, no2, is_z_pres, pblh )
%TEST_WRF_BL_HEIGHT Plots tests of ways to find the chemical BL height from WRF profiles
% Detailed explanation goes here
E = JLLErrors;
if ndims(z) ~= 3 || ndims(no2) ~= 3
E.badinput('Both input matrices must be 3D')
elseif any(size(z) ~= size(no2)) && size(z,3) ~= size(no2,3)+1
E.badinput('Both input matrices must have the same size, or z must have at most one more element in the third dimension')
end
if ~exist('is_z_pres','var')
is_z_pres = false;
end
if ~exist('pblh','var')
use_wrf_blh = false;
else
use_wrf_blh = true;
end
if size(z,3) == size(no2,3)+1
z = z(:,:,1:end-1);
end
% This function will randomly pick profiles from the matrix provided,
% calculate the boundary layer height, and plot both the profile and the
% height. It will then ask if the height is accurate and keep track of what
% percent (and which ones) are good or bad. This will continue until the
% user says to quit.
n = 0;
n_good = 0;
n_ok = 0;
n_undefined = 0;
indices_good = {};
indices_ok = {};
indices_bad = {};
indices_undefined = {};
while true
n = n+1;
i = randi(size(z,1));
j = randi(size(z,2));
z_slice = squeeze(z(i,j,:));
no2_slice = squeeze(no2(i,j,:));
f=figure;
line(no2_slice, z_slice, 'linewidth', 2, 'color', 'k', 'linestyle', '-');
if is_z_pres
set(gca,'ydir','reverse');
end
method = 'exp2';
while true
if ~use_wrf_blh
blh = find_bdy_layer_height(no2_slice, z_slice, method, 'altispres', is_z_pres);
l=line([min(no2_slice(:)), max(no2_slice(:))], [blh blh], 'linewidth', 2, 'color', 'b', 'linestyle', '--');
d = (no2_slice(1) - median(no2_slice))/no2_slice(1) * 100;
title(sprintf('%.2f',d));
else
l = line([min(no2_slice(:)), max(no2_slice(:))], [pblh(i,j)+z_slice(1), pblh(i,j)+z_slice(1)]);
end
s = ask_question;
switch s
case 'y'
n_good = n_good + 1;
indices_good = cat(1,indices_good, {[i,j],method});
break
case 'n'
indices_bad = cat(1, indices_bad, {[i,j],method});
break
case 'o'
n_ok = n_ok + 1;
indices_ok = cat(1,indices_ok, {[i,j],method});
break
case 'e'
if ~use_wrf_blh && ~strcmp(method,'exp')
delete(l);
if strcmp(method, 'exp2')
method = 'exp1.5';
elseif strcmp(method, 'exp1.5')
method = 'exp';
end
else
n_undefined = n_undefined + 1;
indices_undefined = cat(1, indices_undefined, {[i,j],method});
break
end
case 'q'
n = n-1; % we never categorized this last profile.
break
end
end
close(f);
if strcmp(s,'q')
break
end
end
fraction_good = n_good / n;
fraction_ok = n_ok / n;
fraction_undefined = n_undefined / n;
end
function s = ask_question
fprintf('Is the BL height for this profile accurate?\n')
quest = ' Enter ''y'' for yes, ''n'' for no, ''o'' for okay, ''e'' if no BL height shown, or ''q'', to quit: ';
while true
s = lower(input(quest, 's'));
s = s(1);
if ~ismember(s,'ynoeq')
fprintf(' * Please enter y, n, o, e, or q! *\n')
else
break
end
end
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_autoencoder_with_classerror.m
|
.m
|
Encoder-Based-Lifelong-learning-master/Autoencoder/cnn_autoencoder_with_classerror.m
| 6,861 |
utf_8
|
6e6a912f8633c3a7a031dd3fb869d0b2
|
function [net, opts, imdb, info] = cnn_autoencoder_with_classerror(varargin)
%CNN_AUTOENCODER_WITH_CLASSERROR contructs an autoencoder to be trained in order to minimize:
% - the reconstruction loss (as is classicly the case for autoencoders)
% - the task loss (e.g. classification loss) when the task layers are given the output ofthe autoencoder
%For more details, see A. Rannen Triki, R. Aljundi, M. B. Blaschko, and T. Tuytelaars, Encoder Based Lifelong
%Learning. ICCV 2017 - Section 3.
%
% Authors: Rahaf Aljundi & Amal Rannen Triki
%
% See the COPYING file.
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
%
% Copyright (C) 2014-15 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', 'matlab', 'vl_setupnn.m')) ;
opts = getAutoencoderOpts;
opts = vl_argparse(opts, varargin) ;
net = get_onelayer_autoencoder(opts);
net = add_task_layers(net,opts);
if exist(opts.imdbPath, 'file')
imdb=load(opts.imdbPath);
if(isfield(imdb,'imdb'))
imdb=imdb.imdb;
end
inds=find(imdb.images.set==2);
if ~isempty(inds)
opts.val = inds;
end;
end
opts.compute_stats=false;
[net, info] = cnn_train_adadelta(net, imdb, getBatchFn(opts), opts);
end
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
end
% -------------------------------------------------------------------------
function net = get_onelayer_autoencoder(opts)
% -------------------------------------------------------------------------
%Constructs an autoencoder with one hidden layer, with sigmoid activation, and a reconstruction loss
%multiplied by a parameter alpha that controls the compromise between the reconstruction loss and the
%task loss
if (~isempty(opts.initial_encoder))
load(opts.initial_encoder);
net = vl_simplenn_move(net, 'cpu') ;
else
net.layers = {} ;
% Layer 1
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', 'code', '1'), ...
'weights', {{init_weight(opts, 1, 1, opts.input_size, opts.code_size, 'single'), ...
ones( opts.code_size, 1, 'single')*opts.initBias}}, ...
'stride', [1 1], ...
'pad', [0 0 0 0], ...
'dilate', 1, ...
'learningRate', [1 1], ...
'weightDecay', [1 0] ,'precious',1 ) ;
%Sigmoid activation
net.layers{end+1} = struct('name', 'encoder_1_sigmoid', ...
'type', 'sigmoid' );
% Layer 2
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', 'data_hat', '3'), ...
'weights', {{init_weight(opts, 1, 1, opts.code_size, opts.input_size, 'single'), ...
ones(opts.input_size, 1, 'single')*opts.initBias}}, ...
'stride', [1 1], ...
'pad', [0 0 0 0], ...
'dilate', 1, ...
'learningRate', [1 1], ...
'weightDecay', [1 0] , 'precious',1 ) ;
%Loss
net.layers{end+1} = struct('type', 'intermediate_euclideanloss','alpha',opts.alpha);
end
end
% -------------------------------------------------------------------------
function net = add_task_layers(net,opts)
% -------------------------------------------------------------------------
%Adds the task layers (e.g. fully connected layers for a classification ConvNet) to the autoencoder
%WARNING: orgNet.layers{end}.type should be set to the loss related to your task loss (e.g. softmaxlss).
%Make sure that this loss is interpretable by vl_simplenn.m
orgNet = load(opts.orgNetPath);
if(isfield(orgNet,'net'))
orgNet=orgNet.net;
end
orgNet.layers{end}.type='softmaxloss';
orgNet = vl_simplenn_tidy(orgNet) ;
orgNet.layers(1:opts.output_layer_id-1) =[];
for i=1:length(orgNet.layers)
if isfield(orgNet.layers{i}, 'learningRate')
orgNet.layers{i}.learningRate = zeros(size(orgNet.layers{i}.learningRate));
end
end
net.layers(end+1:end+length(orgNet.layers)) = orgNet.layers;
end
% -------------------------------------------------------------------------
function opts=getAutoencoderOpts()
% -------------------------------------------------------------------------
%Initializes the options for the autoencoder training
%Make sure to change the paths to your data and models if needed
opts.nesterovUpdate = false;
opts.expDir = fullfile(vl_rootnn, 'data', 'autoencoder_with_classerror') ;
opts.dataDir = fullfile(vl_rootnn, 'data', 'dataset') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.orgNetPath= fullfile(opts.expDir, 'model-task-1.mat');
opts.dataLinks = 1; %1 if imdb.images.data contains images paths, 0 otherwise
opts.code_size=100;
opts.input_size= 9216;
opts.batchSize= 128;
opts.initial_encoder=[];
opts.errorType = 'euclideanloss';
opts.errorFunction = 'euclideanloss' ;
opts.continue = true;
opts.learningRate = 1e-2;
opts.numEpochs = 100;
opts.imagenet_mean='imagenet_mean';
opts.imagenet_std='imagenet_std';
opts.compute_stats=false;
opts.alpha=1e-6;
opts.output_layer_id= 16;
opts.useGpu = true;
opts.val = [];
opts.weightDecay = 5e-4;
opts.scale = 1 ;
opts.initBias = 0 ;
opts.weightInitMethod = 'xavierimproved' ;
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.numFetchThreads = 12 ;
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts)
% -------------------------------------------------------------------------
fn = @(x,y) getBatch(x,y,opts) ;
end
% -------------------------------------------------------------------------
function varargout = getBatch(imdb, batch, opts)
% -------------------------------------------------------------------------
if opts.dataLinks
im_links=imdb.images.data(batch);
input = [];
for i=1:length(im_links)
im = load(im_links{i});
input = cat(4, input, im.input);
end;
else
input = imdb.images.data(:,:,:,batch);
end;
labels = imdb.images.labels(batch);
varargout = {input, labels} ;
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_train_adadelta.m
|
.m
|
Encoder-Based-Lifelong-learning-master/Autoencoder/cnn_train_adadelta.m
| 22,540 |
utf_8
|
02f3c27590616a1beeaa11e720632314
|
function [net, stats] = cnn_train_adadelta(net, imdb, getBatch, varargin)
%CNN_TRAIN_ADADELTA An example of custom implementation of adaptive
%gradient for training CNNs, needed with matconvnet_b23 or older.
%From the version matconvnet_b24 on, the solver adadelta can be used
%instead.
%CNN_TRAIN_ADADELTA() is an example learner implementing adaptive stochastic
% gradient descent with ADADELTA method to train a CNN. It can be used
% with different datasets and tasks by providing a suitable
% getBatch function.
%
% 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).
%
% Authors: Rahaf Aljundi (RA)
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
% 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).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [1] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
%==========legacy code===============
opts.compute_stats=false;
opts.imagenet_mean='imagenet_mean';
opts.imagenet_std='imagenet_std';
opts.delta = 1e-8;
opts.errorType='';
opts.weightInitMethod = 'gaussian' ;
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts.scale = 1 ;
opts.initBias = 0 ;
opts.initial_encoder='';
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'euclideanloss' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts.imdbPath=[];
opts.net_path='';
opts.input_size='';
opts.code_size='';
opts.output_layer_id='';
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.numFetchThreads = 12 ;
opts.useGpu=1;
%==================================
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==3) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
%==========================AdaDelta================================
%Written by RA
for l=1:numel(net.layers)
if ~strcmp(net.layers{l}.type, 'conv'), continue ; end
J = numel(net.layers{l}.weights) ;
for j=1:J
net.layers{l}.Gf{j} = zeros(size(net.layers{l}.weights{j}), 'single');
net.layers{l}.Df{j} = zeros(size(net.layers{l}.weights{j}), 'single');
end
end
%==========================AdaDelta=================================
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
case 'euclideanloss'
opts.errorFunction = @error_euclidean ;
if isempty(opts.errorLabels), opts.errorLabels = {'euc_err'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
%HERE
xx_temp= tmp(1,:)';
xx_temp=gather(xx_temp);
values(end+1,:) = xx_temp ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
function err = error_euclidean(params, labels, res)
predictions = gather(res(end-1).x) ;
err = euclideanloss((predictions), labels);
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
for i = 1:numel(net.layers)
for j = 1:numel(net.layers{i}.weights)
state.momentum{i}{j} = 0 ;
end
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move(net, 'gpu') ;
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[im, labels] = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
res = vl_simplenn_LwF_encoder(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats = extractStats(net, params, error / num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
% collect diagnostic statistics
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ;
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ;
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gather(state.momentum{i}{j}) ;
end
end
end
net = vl_simplenn_move(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for l=numel(net.layers):-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
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, ...
parDer) ;
else
%====================ADADELTA==========================
%Written by RA
%Implements ADADELTA (see Matthew D. Zeiler, ADADELTA: AN
%ADAPTIVE LEARNING RATE METHOD, arXiv:1212.5701.
%g_f is the current gradient
% net.layers{l}.Gf{j} contains the update rule (Delta in the
% paper)
%params.momentum and params.delta are the method
%hyperparameters (correpond respectively to rho and epsilon in the paper)
if ~strcmp(net.layers{l}.type, 'conv'), continue ; end
thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;
g_f = res(l).dzdw{j};
net.layers{l}.Gf{j} =params.momentum.*net.layers{l}.Gf{j}+ (1-params.momentum).*(g_f .^ 2);
% Compute update
dCurr= -(sqrt( net.layers{l}.Df{j} + params.delta)./sqrt( net.layers{l}.Gf{j} + params.delta)).*g_f;
% Update accumulated updates (deltas)
net.layers{l}.Df{j} =params.momentum.*net.layers{l}.Df{j}+(1-params.momentum).*( dCurr .^ 2);
net.layers{l}.weights{j}= net.layers{l}.weights{j}+ dCurr;
%====================ADADELTA==========================
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power);
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
dt=whos('state');
MB=dt.bytes*9.53674e-7
dt=whos('net');
MB=dt.bytes*9.53674e-7
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename) ;
clearMex() ;
if numGpus == 1
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
add_new_task.m
|
.m
|
Encoder-Based-Lifelong-learning-master/LwF_with_encoder/Model_preparation/add_new_task.m
| 6,061 |
utf_8
|
aef5b1c13f46b5114cf9430da4776951
|
function [new_net, aug_imdb] = add_new_task(varargin)
%ADD_NEW_TASK modifies a model and to prepare it for training on a new task
%and modifies its corresponding data by:
% -adding the two first layers of the autoencoder of the model
% -augmenting the data if needed
% -add the task specific layers to the model and train them for few
% epochs for a better initialization.
%The last network layer is a custom layer, that contains 2 branches:
% - 1 for the autoencoder
% - 1 for the task operator (see paper for definition)
% The task operator is also divided into a commun part and a task specific
% part. The task specific part is the last layer, that is also a custom
% layer divided into a branch per task, in the same order the tasks are fed
% to the model.
%
%For more details about the model, see A. Rannen Triki, R. Aljundi, M. B. Blaschko,
%and T. Tuytelaars, Encoder Based Lifelong Learning. ICCV 2017
%
% Author: Rahaf Aljundi
%
% See the COPYING file.
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
%
% Copyright (C) 2014-15 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).
opts=getDefaultOpts();
[opts, ~] = vl_argparse(opts, varargin) ;
org_imdb=load(opts.imdb_path);
org_net=load(opts.orgin_net);
if(isfield(org_net,'net'))
org_net=org_net.net;
end
%Prepare autoencoder
autoencoder_net = load(opts.autoencoder_path);
if isfield(autoencoder_net,'net')
autoencoder_net=autoencoder_net.net;
end;
new_net=org_net;
new_enc_net.layers=[];
new_enc_net.layers{1}=struct('type','en_reshape');
new_enc_net.layers(end+1:end+2)=autoencoder_net.layers(1:2);
new_enc_net.layers{end+1}=struct('type','intermediate_euclideanloss');
new_enc_net.layers{end}.alpha=opts.alpha;
new_enc_net.layers{1}.gr_weight=1;
autoencoder_net=new_enc_net;
for i=1:numel(autoencoder_net.layers)
if(isfield(autoencoder_net.layers{i},'Gf'))
autoencoder_net.layers{i}=rmfield(autoencoder_net.layers{i},'Gf');
end
if(isfield(autoencoder_net.layers{i},'Df'))
autoencoder_net.layers{i}=rmfield(autoencoder_net.layers{i},'Df');
end
autoencoder_net.layers{i}.learningRate=[0 0];
end
%Add autoencoder to the model
new_net.layers{end}.tasks{end+1}=new_net.layers{end}.tasks{end};
new_net.layers{end}.tasks{end-1}=autoencoder_net;
%Record the initial codes and last task targets for the new data
if(~exist(opts.output_imdb_path,'file'))
mkdir(opts.aug_output_path)
encoder_opts.output_layer_id=opts.split_layer;
% if augmentation is needed
if(opts.extract_images)
org_imdb=load(opts.imdb_path);
[aug_imdb]=augment_data(org_imdb,org_net,opts.aug_output_path,autoencoder_net,encoder_opts);
[imdb] = record_task_aug(aug_imdb,new_net,opts);
save(opts.output_imdb_path,'imdb');
% if the data is already augmented
else
aug_imdb=load(opts.old_aug_imdb_path);
if(isfield(aug_imdb,'imdb'))
aug_imdb=aug_imdb.imdb;
end
[imdb] = record_task_aug(aug_imdb,new_net,opts);
save(opts.output_imdb_path,'imdb');
end
end
%finetune only the new task specific layer while freezing all other
fine_tune_opts.expDir=opts.freezeDir;
fine_tune_opts.imdbPath=opts.imdb_path;
fine_tune_opts.dataDir='';
fine_tune_opts.modelPath=opts.last_task_net_path;
fine_tune_opts.train.learningRate=opts.train.learningRate;
fine_tune_opts.train.batchSize=opts.train.batchSize;
fine_tune_opts.freeze_layer=22;
fine_tune_opts.add_dropout=0;
cnn_fine_tune_freeze(fine_tune_opts);
freezed_net=load(fullfile(opts.freezeDir,strcat('net-epoch-',num2str(findLastCheckpoint(opts.freezeDir)),'.mat')));
if isfield(freezed_net, 'net')
freezed_net=freezed_net.net;
end;
%Add the knowledge distillation (old tasks) and cross entropy(new task)
%losses
new_net.layers{end}.tasks{end}.layers{end}.tasks{end}.layers{end}=struct('type','softmaxlossdiff');
new_net.layers{end}.tasks{end}.layers{end}.tasks{end+1}.layers{1}=freezed_net.layers{end-1:end};
new_net.layers{end}.tasks{end}.layers{end}.tasks{end}.layers{1}.dilate=1;
new_net.layers{end}.tasks{end}.layers{end}.tasks{end}.layers{end+1} = struct('type', 'softmaxloss') ;%
net=new_net;
save(opts.outputnet_path,'net');
end
% -------------------------------------------------------------------------
function opts=getDefaultOpts()
% -------------------------------------------------------------------------
%Initializes the options for the autoencoder training
%Make sure to change the paths to your data and models if needed
opts.split_layer=16;
opts.expDir = fullfile(vl_rootnn, 'data', 'LwF_with_encoder') ;
opts.orgNetPath= fullfile(opts.expDir, 'model-task-1.mat');
opts.imdb_path=fullfile(opts.expDir, 'imdb.mat');
opts.outputnet_path=fullfile(opts.expDir, 'model-task-2-initial.mat');
opts.output_imdb_path=fullfile(opts.expDir, 'imdb-2.mat');
opts.train.learningRate = [0.0004*ones(1, 54) 0.1*0.0004*ones(1, 18)] ;
opts.freezeDir=fullfile(opts.expDir, 'task-2-finetune');
opts.train.batchSize=15;
opts.aug_output_path=fullfile(vl_rootnn, 'data', 'aug-dataset-2') ;
opts.old_aug_imdb_path=fullfile(opts.expDir, 'aug-imdb-2.mat');
opts.autoencoder_dir = fullfile(vl_rootnn, 'data', 'autoencoder_with_classerror');
opts.autoencoder_path=fullfile(opts.autoencoder_dir, strcat('net-epoch-',num2str(findLastCheckpoint(opts.autoencoder_dir)),'.mat')) ;
opts.scale = 1 ;
opts.extract_images=true;
opts.alpha=1e-1;
opts.last_task_net_path='';%the last network after lwf
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
% Finds the network of the last epoch in the directory modelDir
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_fine_tune_freeze.m
|
.m
|
Encoder-Based-Lifelong-learning-master/LwF_with_encoder/Model_preparation/cnn_fine_tune_freeze.m
| 9,697 |
utf_8
|
2a13c512208940104d831be1ca2ed4fa
|
function [net, info] = cnn_fine_tune_freeze(varargin)
%CNN_FINE_TUNE_FREEZE finetune the last layers of the network for
%the new task before adding it to the global model
%See add_new_task for details
%
% Author: Rahaf Aljundi
%
% See the COPYING file.
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
%
% Copyright (C) 2014-15 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', 'matlab', 'vl_setupnn.m')) ;
opts.train.gpus=[1];
opts.train.learningRate=0.01*ones(1,100);
opts.train.batchSize=256;
opts.dataDir = fullfile(vl_rootnn, 'data','ILSVRC2012') ;
opts.modelType = 'alexnet' ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
opts.batchNormalization = true ;
opts.weightInitMethod = 'gaussian' ;
opts.imdbPath = fullfile(opts.dataDir,'imdb');
opts.batchSize=256;
opts.modelPath='data/models/imagenet-caffe-alex.mat';
opts.compute_stats=false;
opts.freeze_layer=15;
opts.add_dropout=true;
opts.useGpu=false;
opts.weightInitMethod = 'gaussian';
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.modelType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
sfx = [sfx '-' opts.networkType] ;
opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.useValidation=true;
opts.numFetchThreads = 12 ;
opts.lite = false ;
opts.imdbPath = fullfile(opts.dataDir, opts.imdbPath);
opts.numAugments=3;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
imdb = load(opts.imdbPath) ;
if(isfield(imdb,'imdb'))
imdb=imdb.imdb;
end
mkdir(opts.expDir);
%--------------------------------------------------------------------------
% create a validation set
%--------------------------------------------------------------------------
if(opts.useValidation)
sets=unique(imdb.images.set);
if(numel(sets)==2)
test_set=find(imdb.images.set~=1);
imdb.images.set(test_set)=3;
training_inds=find(imdb.images.set==1);
training_size=numel(training_inds);
%create validation inds
val_inds= randi(training_size,floor(training_size/10),1);
imdb.images.set(training_inds(val_inds))=2;
end
else
test_set=find(imdb.images.set~=1);
imdb.images.set(test_set)=2;
end
%==========================================================================
if(opts.compute_stats)
% Compute image statistics (mean, RGB covariances, etc.)
imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;
if exist(imageStatsPath)
load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
else
train = find(imdb.images.set == 1) ;
images = fullfile( imdb.images.data(train(1:100:end))) ;
[averageImage, rgbMean, rgbCovariance] = getImageStats(images, ...
'imageSize', [256 256], ...
'numThreads', opts.numFetchThreads, ...
'gpus', opts.train.gpus) ;
save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
end
[v,d] = eig(rgbCovariance) ;
rgbDeviation = v*sqrt(d) ;
clear v d ;
end
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
net = load(opts.modelPath );
if(isfield(net,'net'))
net=net.net;
end
% Meta parameters
if(opts.compute_stats)
net.meta.normalization.averageImage=averageImage;
end
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * zeros(3)) ;
net.meta.augmentation.jitterAspect = [2/3, 3/2] ;
net.meta.trainOpts.learningRate =opts.train.learningRate ;
net.meta.trainOpts.numEpochs = numel(opts.train.learningRate) ;
net.meta.trainOpts.batchSize = opts.train.batchSize ;
net.meta.trainOpts.weightDecay = 0.0005 ;
%---------------------------------------------------------------------------
% put drop out layers
%---------------------------------------------------------------------------
aux_net=net;
opts.scale = 1 ;
if (opts.add_dropout)
aux_net.layers = net.layers(1:end-4);
%add dropout
aux_net = add_dropout(aux_net, 'drop_out6');
%get number of classes from the dataset
%move fc7 and relu
aux_net.layers{end+1}= net.layers{end-3};
aux_net.layers{end+1}= net.layers{end-2};
%add dropout
aux_net = add_dropout(aux_net, 'drop_out7');
else
aux_net.layers = net.layers(1:end-2);
end
%add task specific layer
aux_net.layers{end+1} = struct('type', 'conv', ...
'weights', {{init_weight(opts,1,1,4096,numel(imdb.meta.classes), 'single'), zeros(1,numel(imdb.meta.classes),'single')}}, ...
'learningRate', [1 1], ...
'stride', [1 1], ...
'pad', [0 0 0 0]) ;
aux_net.layers{end+1} = struct('type', 'softmaxloss') ;%
%FREEZE OLD LAYERS
for i=1:opts.freeze_layer-1
if strcmp(aux_net.layers{1,i}.type,'conv')
aux_net.layers{1,i}.learningRate=[0 0];
end
end
net=aux_net;
net = vl_simplenn_tidy(net) ;
% -------------------------------------------------------------------------
% Learn
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainFn = @cnn_train ;
case 'dagnn', trainFn = @cnn_train_dag ;
end
[net, info] = trainFn(net, imdb, getBatchFn(opts, net.meta), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train) ;
% -------------------------------------------------------------------------
% Deploy
% -------------------------------------------------------------------------
net = cnn_imagenet_deploy(net) ;
modelPath = fullfile(opts.expDir, 'net-deployed.mat');
switch opts.networkType
case 'simplenn'
save(modelPath, '-struct', 'net') ;
case 'dagnn'
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
function net = add_dropout(net, id)
% --------------------------------------------------------------------
net.layers{end+1} = struct('type', 'dropout', ...
'name', sprintf('dropout%s', id), ...
'rate', 0.5) ;
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', meta.normalization.cropSize, ...
'subtractAverage', mu) ;
% Copy the parameters for data augmentation
bopts.train = bopts.test ;
for f = fieldnames(meta.augmentation)'
f = char(f) ;
bopts.train.(f) = meta.augmentation.(f) ;
end
bopts.numAugments=opts.numAugments;
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(batch) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
%handelling the augmentation
data=[];
for i=1:opts.numAugments
curr_data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if(~isempty(data))
data=cat(4,data,curr_data);
else
data=curr_data;
end
end
rep_inds=get_aug_inds(opts,batch);
data=data(:,:,:,rep_inds);
if nargout > 0
labels = imdb.images.labels(batch) ;
a=repmat(labels,size(data,4)/size(batch,2), 1);
labels=a(:);
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_imagenet_deploy.m
|
.m
|
Encoder-Based-Lifelong-learning-master/LwF_with_encoder/Model_training/cnn_imagenet_deploy.m
| 6,585 |
utf_8
|
2f3e6d216fa697ff9adfce33e75d44d8
|
function net = cnn_imagenet_deploy(net)
%CNN_IMAGENET_DEPLOY Deploy a CNN
isDag = isa(net, 'dagnn.DagNN') ;
if isDag
dagRemoveLayersOfType(net, 'dagnn.Loss') ;
dagRemoveLayersOfType(net, 'dagnn.DropOut') ;
else
net = simpleRemoveLayersOfType(net, 'softmaxloss') ;
net = simpleRemoveLayersOfType(net, 'dropout') ;
end
if isDag
net.addLayer('prob', dagnn.SoftMax(), 'prediction', 'prob', {}) ;
else
net.layers{end+1} = struct('name', 'prob', 'type', 'softmax') ;
end
if isDag
dagMergeBatchNorm(net) ;
dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ;
else
net = simpleMergeBatchNorm(net) ;
net = simpleRemoveLayersOfType(net, 'bnorm') ;
end
if ~isDag
net = simpleRemoveMomentum(net) ;
end
% Switch to use MatConvNet default memory limit for CuDNN (512 MB)
if ~isDag
for l = simpleFindLayersOfType(net, 'conv')
net.layers{l}.opts = removeCuDNNMemoryLimit(net.layers{l}.opts) ;
end
else
for name = dagFindLayersOfType(net, 'dagnn.Conv')
l = net.getLayerIndex(char(name)) ;
net.layers(l).block.opts = removeCuDNNMemoryLimit(net.layers(l).block.opts) ;
end
end
% -------------------------------------------------------------------------
function opts = removeCuDNNMemoryLimit(opts)
% -------------------------------------------------------------------------
remove = false(1, numel(opts)) ;
for i = 1:numel(opts)
if isstr(opts{i}) && strcmp(lower(opts{i}), 'CudnnWorkspaceLimit')
remove([i i+1]) = true ;
end
end
opts = opts(~remove) ;
% -------------------------------------------------------------------------
function net = simpleRemoveMomentum(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if isfield(net.layers{l}, 'momentum')
net.layers{l} = rmfield(net.layers{l}, 'momentum') ;
end
end
% -------------------------------------------------------------------------
function layers = simpleFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = find(cellfun(@(x)strcmp(x.type, type), net.layers)) ;
% -------------------------------------------------------------------------
function net = simpleRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = simpleFindLayersOfType(net, type) ;
net.layers(layers) = [] ;
% -------------------------------------------------------------------------
function layers = dagFindLayersWithOutput(net, outVarName)
% -------------------------------------------------------------------------
layers = {} ;
for l = 1:numel(net.layers)
if any(strcmp(net.layers(l).outputs, outVarName))
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function dagRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, type) ;
for i = 1:numel(names)
layer = net.layers(net.getLayerIndex(names{i})) ;
net.removeLayer(names{i}) ;
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
% -------------------------------------------------------------------------
function dagMergeBatchNorm(net)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, 'dagnn.BatchNorm') ;
for name = names
name = char(name) ;
layer = net.layers(net.getLayerIndex(name)) ;
% merge into previous conv layer
playerName = dagFindLayersWithOutput(net, layer.inputs{1}) ;
playerName = playerName{1} ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
if ~isa(player.block, 'dagnn.Conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
% if the convolution layer does not have a bias,
% recreate it to have one
if ~player.block.hasBias
block = player.block ;
block.hasBias = true ;
net.renameLayer(playerName, 'tmp') ;
net.addLayer(playerName, ...
block, ...
player.inputs, ...
player.outputs, ...
{player.params{1}, sprintf('%s_b',playerName)}) ;
net.removeLayer('tmp') ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
biases = net.getParamIndex(player.params{2}) ;
net.params(biases).value = zeros(block.size(4), 1, 'single') ;
end
filters = net.getParamIndex(player.params{1}) ;
biases = net.getParamIndex(player.params{2}) ;
multipliers = net.getParamIndex(layer.params{1}) ;
offsets = net.getParamIndex(layer.params{2}) ;
moments = net.getParamIndex(layer.params{3}) ;
[filtersValue, biasesValue] = mergeBatchNorm(...
net.params(filters).value, ...
net.params(biases).value, ...
net.params(multipliers).value, ...
net.params(offsets).value, ...
net.params(moments).value) ;
net.params(filters).value = filtersValue ;
net.params(biases).value = biasesValue ;
end
% -------------------------------------------------------------------------
function net = simpleMergeBatchNorm(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if strcmp(net.layers{l}.type, 'bnorm')
if ~strcmp(net.layers{l-1}.type, 'conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
[filters, biases] = mergeBatchNorm(...
net.layers{l-1}.weights{1}, ...
net.layers{l-1}.weights{2}, ...
net.layers{l}.weights{1}, ...
net.layers{l}.weights{2}, ...
net.layers{l}.weights{3}) ;
net.layers{l-1}.weights = {filters, biases} ;
end
end
% -------------------------------------------------------------------------
function [filters, biases] = mergeBatchNorm(filters, biases, multipliers, offsets, moments)
% -------------------------------------------------------------------------
% wk / sqrt(sigmak^2 + eps)
% bk - wk muk / sqrt(sigmak^2 + eps)
a = multipliers(:) ./ moments(:,2) ;
b = offsets(:) - moments(:,1) .* a ;
biases(:) = biases(:) + b(:) ;
sz = size(filters) ;
numFilters = sz(4) ;
filters = reshape(bsxfun(@times, reshape(filters, [], numFilters), a'), sz) ;
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_train_lwf_with_encoder.m
|
.m
|
Encoder-Based-Lifelong-learning-master/LwF_with_encoder/Model_training/cnn_train_lwf_with_encoder.m
| 27,825 |
utf_8
|
7af728d200b656511a5aa7bda59654c3
|
function [net, stats] = cnn_train_lwf_with_encoder(net, imdb, getBatch, varargin)
%CNN_TRAIN_LWF_WITH_ENCODER is an example learner implementing stochastic
% gradient descent with momentum to train a CNN with the Encoder Based
% Lifelong Learning method after preparing the model(See functions under
% Model_prepapration).
% It can be used with different datasets and tasks by providing a suitable
% getBatch function.
%
% 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).
%
%The last network layer is a custom layer, that contains 2 branches:
% - 1 for the autoencoder
% - 1 for the task operator (see paper for definition)
% The task operator is also divided into a commun part and a task specific
% part. The task specific part is the last layer, that is also a custom
% layer divided into a branch per task, in the same order the tasks are fed
% to the model.
%
%For more details about the model, see A. Rannen Triki, R. Aljundi, M. B. Blaschko,
%and T. Tuytelaars, Encoder Based Lifelong Learning. ICCV 2017
%
% Author: Rahaf Aljundi
%
% See the COPYING file.
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
%
% Copyright (C) 2014-15 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).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.encoder_fork_indx=16;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
if(strcmp(net.layers{i}.type,'custom'))
net.layers{i}=initilize_custom(net.layers{i});
else
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
end
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
%legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions=gather(res(end).aux{end}.layers{end}.aux{end}.layers{end-1}.x);
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
for i = 1:numel(net.layers)
if(strcmp(net.layers{i}.type,'custom'))
state.momentum{i}=initilize_momentum(net.layers{i});
end
if isfield(net.layers{i},'weights')
for j = 1:numel(net.layers{i}.weights)
state.momentum{i}{j} = 0 ;
end
end
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move_lwf(net, 'gpu') ;
for i = 1:numel(state.momentum)
if(isstruct(state.momentum{i}))
state.momentum{i}=move_momentum(state.momentum{i},@gpuArray);
else
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;
end
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[im, labels,tasks_recs,tasks_targets] = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
for ts=1:numel(tasks_recs)
tasks_recs{ts}=gpuArray(tasks_recs{ts});
end
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
net.layers{end}.tasks_class = tasks_recs ;
net.layers{end}.tasks_targets = tasks_targets;
net.layers{end}.mode=evalMode;
res = vl_simplenn(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats = extractStats(net, params, error / num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
for ts=1:numel(net.layers{end}.tasks)-1
fprintf(' [%f/ task number %d error]', (res(end).aux{end}.layers{end}.aux{ts}.layers{end}.x/ numel(batch)), ts);
end
fprintf('\n') ;
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ;
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ;
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
for i = 1:numel(state.momentum)
if(isstruct(state.momentum{i}))
state.momentum{i}=move_momentum(state.momentum{i},@gather);
else
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gather(state.momentum{i}{j}) ;
end
end
end
end
net = vl_simplenn_move_lwf(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
%===========================LWF-Auto:start============================
%take care of the last fully connected layers
fc_for_layer=net.layers{end}.tasks{end}.layers{end};
fc_res=res(end-1).aux{end}.layers{end-1};
this_state=state.momentum{end}.tasks{end}.layers{end};
for t=1:numel(fc_res.aux)
%only one fully connected layer
for j=numel(fc_res.aux{t}.layers{1}.dzdw):-1:1% has to be dealt with
thisDecay = params.weightDecay *fc_for_layer.tasks{t}.layers{1}.weightDecay(j) ;
thisLR = params.learningRate *fc_for_layer.tasks{t}.layers{1}.learningRate(j) ;
this_state.tasks{t}.layers{1}{j}=params.momentum * this_state.tasks{t}.layers{1}{j} ...
- thisDecay * fc_for_layer.tasks{t}.layers{1}.weights{j} ...
- (1 / batchSize) * fc_res.aux{t}.layers{1}.dzdw{j} ;
fc_for_layer.tasks{t}.layers{1}.weights{j} = fc_for_layer.tasks{t}.layers{1}.weights{j} + thisLR *this_state.tasks{t}.layers{1}{j};
end
end
state.momentum{end}.tasks{end}.layers{end}=this_state;
net.layers{end}.tasks{end}.layers{end}=fc_for_layer;
%first accumulate the gradients from the last multi task layer
for t=numel(net.layers{end}.tasks):-1:1
%Here I can add the AUtoencoder and the LWF
%freeze the autoencoder
%just the first layer is convolutional
for t_layer=numel(net.layers{end}.tasks{t}.layers):-1:1
if(isfield(res(end-1).aux{t}.layers{t_layer},'dzdw'))%for the soft max layers
for j=numel(res(end-1).aux{t}.layers{t_layer}.dzdw):-1:1% has to be dealt with
thisDecay = params.weightDecay * net.layers{end}.tasks{t}.layers{t_layer}.weightDecay(j) ;
thisLR = params.learningRate * net.layers{end}.tasks{t}.layers{t_layer}.learningRate(j) ;
this_batch_size=size(res(end-1).aux{t}.layers{t_layer}.dzdx,4);
if(thisLR>0)
state.momentum{end}.tasks{t}.layers{t_layer}{j}=params.momentum * state.momentum{end}.tasks{t}.layers{t_layer}{j} ...
- thisDecay * net.layers{end}.tasks{t}.layers{t_layer}.weights{j} ...
- (1 / this_batch_size) * res(end-1).aux{t}.layers{t_layer}.dzdw{j} ;
net.layers{end}.tasks{t}.layers{t_layer}.weights{j} = net.layers{end}.tasks{t}.layers{t_layer}.weights{j} + thisLR *state.momentum{end}.tasks{t}.layers{t_layer}{j} ;
end
end
end
end
end
for l=numel(net.layers)-1:-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
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, ...
parDer) ;
else
% Standard gradient training.
thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;
thisLR = params.learningRate * net.layers{l}.learningRate(j) ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.layers{l}.weights{j}) ;
% Update momentum.
state.momentum{l}{j} = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
else
delta = state.momentum{l}{j} ;
end
% Update parameters.
net.layers{l}.weights{j} = vl_taccum(...
1, net.layers{l}.weights{j}, ...
thisLR, delta) ;
end
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power) ;
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename) ;
clearMex() ;
if numGpus == 1
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
% -------------------------------------------------------------------------
function layer=initilize_custom(layer)
% -------------------------------------------------------------------------
%Initializes custom layer (= branches that contain encoders and task layers
%of previous task, and the task layer of current task)
for t=1: numel(layer.tasks)
%each task has at least two layers: one conv and one
%softmaxloss or softmaxlossdiff
tasks_layers= layer.tasks{t}.layers;
for t_layer=1:numel(tasks_layers)
if isfield(tasks_layers{t_layer}, 'weights')
J = numel(tasks_layers{t_layer}.weights) ;
if ~isfield(tasks_layers{t_layer}, 'learningRate')
tasks_layers{t_layer}.learningRate = ones(1, J, 'single') ;
end
if ~isfield(tasks_layers{t_layer}, 'weightDecay')
tasks_layers{t_layer}.weightDecay = ones(1, J, 'single') ;
end
end
if(strcmp(tasks_layers{t_layer}.type,'custom'))
tasks_layers{t_layer}=initilize_custom(tasks_layers{t_layer});
end
end
layer.tasks{t}.layers=tasks_layers;
clear tasks_layers;
end
% -------------------------------------------------------------------------
function state=move_momentum(state,fn)
% -------------------------------------------------------------------------
%Reccursive call of move_momentum to deal with all the branches of the
%model
for t= 1:numel(state.tasks)
for i = 1:numel(state.tasks{t}.layers)
if(isstruct(state.tasks{t}.layers{i}))
state.tasks{t}.layers{i}=move_momentum( state.tasks{t}.layers{i},fn);
else
for j = 1:numel(state.tasks{t}.layers{i})
state.tasks{t}.layers{i}{j} = fn(state.tasks{t}.layers{i}{j} ) ;
end
end
end
end
% -------------------------------------------------------------------------
function momentum=initilize_momentum(layer)
% -------------------------------------------------------------------------
%Initializes the momentum for the custom layer (= branches that contain
%encoders and task layers of previous task, and the task layer of current
%task)
for t=1: numel(layer.tasks)
tasks_layers= layer.tasks{t}.layers;
for t_layer=1:numel(tasks_layers)
if(strcmp(tasks_layers{t_layer}.type,'custom'))
temp.tasks{t}.layers{t_layer}= initilize_momentum(tasks_layers{t_layer});
end
if isfield(tasks_layers{t_layer},'weights')
J = numel(tasks_layers{t_layer}.weights) ;
for j=1:J
temp.tasks{t}.layers{t_layer}{j} = 0 ;
end
end
end
end
momentum=temp;
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_lwf_with_encoder.m
|
.m
|
Encoder-Based-Lifelong-learning-master/LwF_with_encoder/Model_training/cnn_lwf_with_encoder.m
| 5,108 |
utf_8
|
6eb118d24d7e1561f820b348dd98a741
|
function [net, info] = cnn_lwf_with_encoder(varargin)
%CNN_LWF_WITH_ENCODER Demonstrates training a CNN with the Encoder Based
%Lifelong Learning method after preparing the model(See functions under
%Model_prepapration).
%
%For more details about the model, see A. Rannen Triki, R. Aljundi, M. B. Blaschko,
%and T. Tuytelaars, Encoder Based Lifelong Learning. ICCV 2017
%
% Author: Rahaf Aljundi
%
% See the COPYING file.
%
% Adapted from MatConvNet of VLFeat library. Their copyright info:
%
% Copyright (C) 2014-15 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..','matlab', 'vl_setupnn.m')) ;
opts.train.gpus=[1];
opts.train.learningRate=1e-4*ones(1,100);
opts.train.batchSize=100;
opts.expDir = fullfile(vl_rootnn, 'data', 'LwF_with_encoder') ;
opts.dataDir = fullfile(vl_rootnn, 'data', 'dataset-2') ;
opts.modelType = 'alexnet' ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
opts.batchNormalization = true ;
opts.weightInitMethod = 'gaussian' ;
opts.imdbPath = fullfile(opts.expDir, 'aug-imdb-2.mat');
opts.modelPath=fullfile(opts.expDir, 'model-task-2-initial.mat');
opts.temperature=2;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.modelType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
sfx = [sfx '-' opts.networkType] ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.useValidation=false;
opts.numFetchThreads = 12 ;
opts.lite = false ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
imdb = load(opts.imdbPath) ;
if(isfield(imdb,'imdb'))
imdb=imdb.imdb;
end
mkdir(opts.expDir);
%--------------------------------------------------------------------------
% create a validation set
%--------------------------------------------------------------------------
if(opts.useValidation)
sets=unique(imdb.images.set);
if(numel(sets)==2)
test_set=find(imdb.images.set~=1);
imdb.images.set(test_set)=3;
training_inds=find(imdb.images.set==1);
training_size=numel(training_inds);
%create validation inds
val_inds= randi(training_size,floor(training_size/10),1);
imdb.images.set(training_inds(val_inds))=2;
end
else
test_set=find(imdb.images.set~=1);
imdb.images.set(test_set)=2;
end
%The model already has the previous task information and parameters but
%make sure not to use the deployed model as a previous task model
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
net = load(opts.modelPath );
if(isfield(net,'net'))
net=net.net;
end
% Meta parameters
net.meta.trainOpts.learningRate =opts.train.learningRate ;
net.meta.trainOpts.numEpochs = numel(opts.train.learningRate) ;
net.meta.trainOpts.batchSize = opts.train.batchSize ;
net.meta.trainOpts.weightDecay = 0.0005 ;
% -------------------------------------------------------------------------
% Learn
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainFn = @cnn_train_lwf_auto_fc_shared ;
case 'dagnn', error('This function does not support DagNN yet. Please use simplenn');
end
[net, info] = trainFn(net, imdb, @getBatch, ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train) ;
% --------------------------------------------------------------------
function [img, labels,tasks_recs,tlabels] = getBatch(imdb, batch)
% --------------------------------------------------------------------
%To extract batches from datasets that contain recorded codes and soft
%targets for previous tasks
%no augmentation is applied now, data augmented in preparation phase
ims = imdb.images.data(1,batch) ;
labels = imdb.images.labels(1,batch) ;
%here we have to add the codes and soft targets from each task
img=[];
%this is to be applied to already augmented data, that we store in an imdb
%file with image links
for i=1:numel(ims)
load(ims{i});
img= cat(4,img,im);
clear im;
end
for t=1:numel(imdb.images.recs)
if(~iscell(imdb.images.recs{t}))
tasks_recs{t}=imdb.images.recs{t}(:,:,:,batch) ;
else
rec_links=imdb.images.recs{t}(batch) ;
for i=1:numel(rec_links)
load(rec_links{i});
tasks_recs{t}= cat(4,tasks_recs{t},rec);
clear rec;
end
end
end
for t=1:numel(imdb.images.tlabels)
tlabels_all=imdb.images.tlabels{t};
tlabels{t}=tlabels_all(batch,:)';
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_train.m
|
.m
|
Encoder-Based-Lifelong-learning-master/Experiments/cnn_train.m
| 19,907 |
utf_8
|
67356030c67680633023886d99dd8251
|
function [net, new_images stats] = cnn_train(net, imdb, getBatch, varargin)
%CNN_TRAIN An example implementation of SGD for training CNNs
% CNN_TRAIN() is an example learner implementing stochastic
% gradient descent with momentum to train a CNN. It can be used
% with different datasets and tasks by providing a suitable
% getBatch function.
%
% 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).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.data.expDir= fullfile(opts.expDir, 'features');
opts.output_layer_id = 16;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
net.layers{opts.output_layer_id-1}.precious = 1;% do not remove pool5
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
new_images = [];
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
[net, ~, state] = processEpoch(net, state, params, 'train') ;
[net, new_images, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net,new_images, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
for i = 1:numel(net.layers)
for j = 1:numel(net.layers{i}.weights)
state.momentum{i}{j} = 0 ;
end
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move(net, 'gpu') ;
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
aug_num=0;
start = tic ;
new_images = params.imdb.images;
new_images.data =[];
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[im, labels] = params.getBatch(params.imdb, batch) ;
aug_num=aug_num+numel(labels);
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
res = vl_simplenn_LwF_encoder(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
%saving part
%=======================================================
input=res(params.output_layer_id);
all_input=reshape(input.x,1,1,size(input.x,1)*size(input.x,2)*size(input.x,3),[]);
%save
for ele=1:numel(batch)
input=all_input(:,:,:,ele);
cur_index=batch(ele);
save(strcat(params.data.expDir,num2str(cur_index),'.mat'),'input');
new_images.data{cur_index}=strcat(params.data.expDir,num2str(cur_index),'.mat');
end
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
%To get the right approximate
stats = extractStats(net, params, error / aug_num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
% collect diagnostic statistics
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ;
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ;
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gather(state.momentum{i}{j}) ;
end
end
end
net = vl_simplenn_move(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for l=numel(net.layers):-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
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, ...
parDer) ;
else
% Standard gradient training.
thisDecay =double( params.weightDecay * net.layers{l}.weightDecay(j)) ;
thisLR =double( params.learningRate * net.layers{l}.learningRate(j) );
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.layers{l}.weights{j}) ;
% Update momentum.
state.momentum{l}{j} = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
else
delta = state.momentum{l}{j} ;
end
% Update parameters.
net.layers{l}.weights{j} = vl_taccum(...
1, net.layers{l}.weights{j}, ...
thisLR, delta) ;
end
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename) ;
clearMex() ;
if numGpus == 1
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
cnn_imagenet_evaluate.m
|
.m
|
Encoder-Based-Lifelong-learning-master/Experiments/cnn_imagenet_evaluate.m
| 5,272 |
utf_8
|
f1b153a158026e131ba92ebe7bd8bc85
|
function [net,new_images,info] = cnn_imagenet_evaluate(varargin)
% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile('data', 'ILSVRC2012') ;
opts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;
opts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.networkType = [] ;
opts.lite = false ;
opts.numFetchThreads = 12 ;
opts.train.batchSize = 128 ;
opts.train.numEpochs = 1 ;
opts.train.gpus = [] ;
opts.train.output_layer_id=16;
opts.train.expDir = opts.expDir ;
opts.train.data.expDir = fullfile(opts.dataDir, 'Features');
opts.train.prefetch = true ;
opts = vl_argparse(opts, varargin) ;
display(opts);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
mkdir(opts.expDir) ;
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = load(opts.modelPath) ;
if isfield(net, 'net')
net = net.net ;
end
if(~isfield(net,'meta'))
error('The model does not contain meta information, may be needed for training');
end
% Cannot use isa('dagnn.DagNN') because it is not an object yet
isDag = isfield(net, 'params') ;
if isDag
opts.networkType = 'dagnn' ;
net = dagnn.DagNN.loadobj(net) ;
trainfn = @cnn_train_dag ;
% Drop existing loss layers
drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;
for n = {net.layers(drop).name}
net.removeLayer(n) ;
end
% Extract raw predictions from softmax
sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;
predVar = 'prediction' ;
for n = {net.layers(sftmx).name}
% check if output
l = net.getLayerIndex(n) ;
v = net.getVarIndex(net.layers(l).outputs{1}) ;
if net.vars(v).fanout == 0
% remove this layer and update prediction variable
predVar = net.layers(l).inputs{1} ;
net.removeLayer(n) ;
end
end
% Add custom objective and loss layers on top of raw predictions
net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...
{predVar,'label'}, 'objective') ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{predVar,'label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{predVar,'label'}, 'top5err') ;
% Make sure that the input is called 'input'
v = net.getVarIndex('data') ;
if ~isnan(v)
net.renameVar('data', 'input') ;
end
% Swtich to test mode
net.mode = 'test' ;
else
opts.networkType = 'simplenn' ;
net = vl_simplenn_tidy(net) ;
trainfn = @cnn_train ;
net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss
end
% Synchronize label indexes used in IMDB with the ones used in NET
imdb = cnn_imagenet_sync_labels(imdb, net);
% Run evaluation
[net,new_images, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...
opts.train, ...
'train', NaN, ...
'val', find(imdb.images.set~=4)) ;
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if isfield(meta.normalization, 'keepAspect')
keepAspect = meta.normalization.keepAspect ;
else
keepAspect = true ;
end
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', max(meta.normalization.imageSize(1:2)) / 256, ...
'subtractAverage', mu, ...
'keepAspect', keepAspect) ;
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
rahafaljundi/Encoder-Based-Lifelong-learning-master
|
findLastCheckpoint.m
|
.m
|
Encoder-Based-Lifelong-learning-master/Experiments/findLastCheckpoint.m
| 463 |
utf_8
|
706404565378f9d06708c02acc71764e
|
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
% Finds the network of the last epoch in the directory modelDir
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
end
|
github
|
Eden-Kramer-Lab/COMPASS-master
|
acf.m
|
.m
|
COMPASS-master/COMPASS_StateSpaceToolbox/acf.m
| 2,458 |
utf_8
|
236f4d8adcb8a89ee0851080b4ee4309
|
function ta = acf(y,p)
% ACF - Compute Autocorrelations Through p Lags
% >> myacf = acf(y,p)
%
% Inputs:
% y - series to compute acf for, nx1 column vector
% p - total number of lags, 1x1 integer
%
% Output:
% myacf - px1 vector containing autocorrelations
% (First lag computed is lag 1. Lag 0 not computed)
%
%
% A bar graph of the autocorrelations is also produced, with
% rejection region bands for testing individual autocorrelations = 0.
%
% Note that lag 0 autocorelation is not computed,
% and is not shown on this graph.
%
% Example:
% >> acf(randn(100,1), 10)
%
% --------------------------
% USER INPUT CHECKS
% --------------------------
[n1, n2] = size(y) ;
if n2 ~=1
error('Input series y must be an nx1 column vector')
end
[a1, a2] = size(p) ;
if ~((a1==1 & a2==1) & (p<n1))
error('Input number of lags p must be a 1x1 scalar, and must be less than length of series y')
end
% -------------
% BEGIN CODE
% -------------
ta = zeros(p,1) ;
global N
N = max(size(y)) ;
global ybar
ybar = mean(y);
% Collect ACFs at each lag i
for i = 1:p
ta(i) = acf_k(y,i) ;
end
% Plot ACF
% Plot rejection region lines for test of individual autocorrelations
% H_0: rho(tau) = 0 at alpha=.05
bar(ta)
line([0 p+.5], (1.96)*(1/sqrt(N))*ones(1,2))
line([0 p+.5], (-1.96)*(1/sqrt(N))*ones(1,2))
% Some figure properties
line_hi = (1.96)*(1/sqrt(N))+.05;
line_lo = -(1.96)*(1/sqrt(N))-.05;
bar_hi = max(ta)+.05 ;
bar_lo = -max(ta)-.05 ;
if (abs(line_hi) > abs(bar_hi)) % if rejection lines might not appear on graph
axis([0 p+.60 line_lo line_hi])
else
axis([0 p+.60 bar_lo bar_hi])
end
title({' ','Sample Autocorrelations',' '})
xlabel('Lag Length')
set(gca,'YTick',[-1:.20:1])
% set number of lag labels shown
if (p<28 & p>4)
set(gca,'XTick',floor(linspace(1,p,4)))
elseif (p>=28)
set(gca,'XTick',floor(linspace(1,p,8)))
end
set(gca,'TickLength',[0 0])
% ---------------
% SUB FUNCTION
% ---------------
function ta2 = acf_k(y,k)
% ACF_K - Autocorrelation at Lag k
% acf(y,k)
%
% Inputs:
% y - series to compute acf for
% k - which lag to compute acf
%
global ybar
global N
cross_sum = zeros(N-k,1) ;
% Numerator, unscaled covariance
for i = (k+1):N
cross_sum(i) = (y(i)-ybar)*(y(i-k)-ybar) ;
end
% Denominator, unscaled variance
yvar = (y-ybar)'*(y-ybar) ;
ta2 = sum(cross_sum) / yvar ;
|
github
|
Eden-Kramer-Lab/COMPASS-master
|
fminsearchbnd.m
|
.m
|
COMPASS-master/COMPASS_StateSpaceToolbox/fminsearchbnd.m
| 8,139 |
utf_8
|
1316d7f9d69771e92ecc70425e0f9853
|
function [x,fval,exitflag,output] = fminsearchbnd(fun,x0,LB,UB,options,varargin)
% FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation
% usage: x=FMINSEARCHBND(fun,x0)
% usage: x=FMINSEARCHBND(fun,x0,LB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...)
% usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...)
%
% arguments:
% fun, x0, options - see the help for FMINSEARCH
%
% LB - lower bound vector or array, must be the same size as x0
%
% If no lower bounds exist for one of the variables, then
% supply -inf for that variable.
%
% If no lower bounds at all, then LB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% UB - upper bound vector or array, must be the same size as x0
%
% If no upper bounds exist for one of the variables, then
% supply +inf for that variable.
%
% If no upper bounds at all, then UB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% Notes:
%
% If options is supplied, then TolX will apply to the transformed
% variables. All other FMINSEARCH parameters should be unaffected.
%
% Variables which are constrained by both a lower and an upper
% bound will use a sin transformation. Those constrained by
% only a lower or an upper bound will use a quadratic
% transformation, and unconstrained variables will be left alone.
%
% Variables may be fixed by setting their respective bounds equal.
% In this case, the problem will be reduced in size for FMINSEARCH.
%
% The bounds are inclusive inequalities, which admit the
% boundary values themselves, but will not permit ANY function
% evaluations outside the bounds. These constraints are strictly
% followed.
%
% If your problem has an EXCLUSIVE (strict) constraint which will
% not admit evaluation at the bound itself, then you must provide
% a slightly offset bound. An example of this is a function which
% contains the log of one of its parameters. If you constrain the
% variable to have a lower bound of zero, then FMINSEARCHBND may
% try to evaluate the function exactly at zero.
%
%
% Example usage:
% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
%
% fminsearch(rosen,[3 3]) % unconstrained
% ans =
% 1.0000 1.0000
%
% fminsearchbnd(rosen,[3 3],[2 2],[]) % constrained
% ans =
% 2.0000 4.0000
%
% See test_main.m for other examples of use.
%
%
% See also: fminsearch, fminspleas
%
%
% Author: John D'Errico
% E-mail: [email protected]
% Release: 4
% Release date: 7/23/06
% size checks
xsize = size(x0);
x0 = x0(:);
n=length(x0);
if (nargin<3) || isempty(LB)
LB = repmat(-inf,n,1);
else
LB = LB(:);
end
if (nargin<4) || isempty(UB)
UB = repmat(inf,n,1);
else
UB = UB(:);
end
if (n~=length(LB)) || (n~=length(UB))
error 'x0 is incompatible in size with either LB or UB.'
end
% set default options if necessary
if (nargin<5) || isempty(options)
options = optimset('fminsearch');
end
% stuff into a struct to pass around
params.args = varargin;
params.LB = LB;
params.UB = UB;
params.fun = fun;
params.n = n;
% note that the number of parameters may actually vary if
% a user has chosen to fix one or more parameters
params.xsize = xsize;
params.OutputFcn = [];
% 0 --> unconstrained variable
% 1 --> lower bound only
% 2 --> upper bound only
% 3 --> dual finite bounds
% 4 --> fixed variable
params.BoundClass = zeros(n,1);
for i=1:n
k = isfinite(LB(i)) + 2*isfinite(UB(i));
params.BoundClass(i) = k;
if (k==3) && (LB(i)==UB(i))
params.BoundClass(i) = 4;
end
end
% transform starting values into their unconstrained
% surrogates. Check for infeasible starting guesses.
x0u = x0;
k=1;
for i = 1:n
switch params.BoundClass(i)
case 1
% lower bound only
if x0(i)<=LB(i)
% infeasible starting value. Use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(x0(i) - LB(i));
end
% increment k
k=k+1;
case 2
% upper bound only
if x0(i)>=UB(i)
% infeasible starting value. use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(UB(i) - x0(i));
end
% increment k
k=k+1;
case 3
% lower and upper bounds
if x0(i)<=LB(i)
% infeasible starting value
x0u(k) = -pi/2;
elseif x0(i)>=UB(i)
% infeasible starting value
x0u(k) = pi/2;
else
x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1;
% shift by 2*pi to avoid problems at zero in fminsearch
% otherwise, the initial simplex is vanishingly small
x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k))));
end
% increment k
k=k+1;
case 0
% unconstrained variable. x0u(i) is set.
x0u(k) = x0(i);
% increment k
k=k+1;
case 4
% fixed variable. drop it before fminsearch sees it.
% k is not incremented for this variable.
end
end
% if any of the unknowns were fixed, then we need to shorten
% x0u now.
if k<=n
x0u(k:n) = [];
end
% were all the variables fixed?
if isempty(x0u)
% All variables were fixed. quit immediately, setting the
% appropriate parameters, then return.
% undo the variable transformations into the original space
x = xtransform(x0u,params);
% final reshape
x = reshape(x,xsize);
% stuff fval with the final value
fval = feval(params.fun,x,params.args{:});
% fminsearchbnd was not called
exitflag = 0;
output.iterations = 0;
output.funcCount = 1;
output.algorithm = 'fminsearch';
output.message = 'All variables were held fixed by the applied bounds';
% return with no call at all to fminsearch
return
end
% Check for an outputfcn. If there is any, then substitute my
% own wrapper function.
if ~isempty(options.OutputFcn)
params.OutputFcn = options.OutputFcn;
options.OutputFcn = @outfun_wrapper;
end
% now we can call fminsearch, but with our own
% intra-objective function.
[xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params);
% undo the variable transformations into the original space
x = xtransform(xu,params);
% final reshape to make sure the result has the proper shape
x = reshape(x,xsize);
% Use a nested function as the OutputFcn wrapper
function stop = outfun_wrapper(x,varargin);
% we need to transform x first
xtrans = xtransform(x,params);
% then call the user supplied OutputFcn
stop = params.OutputFcn(xtrans,varargin{1:(end-1)});
end
end % mainline end
% ======================================
% ========= begin subfunctions =========
% ======================================
function fval = intrafun(x,params)
% transform variables, then call original function
% transform
xtrans = xtransform(x,params);
% and call fun
fval = feval(params.fun,reshape(xtrans,params.xsize),params.args{:});
end % sub function intrafun end
% ======================================
function xtrans = xtransform(x,params)
% converts unconstrained variables into their original domains
xtrans = zeros(params.xsize);
% k allows some variables to be fixed, thus dropped from the
% optimization.
k=1;
for i = 1:params.n
switch params.BoundClass(i)
case 1
% lower bound only
xtrans(i) = params.LB(i) + x(k).^2;
k=k+1;
case 2
% upper bound only
xtrans(i) = params.UB(i) - x(k).^2;
k=k+1;
case 3
% lower and upper bounds
xtrans(i) = (sin(x(k))+1)/2;
xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i);
% just in case of any floating point problems
xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i)));
k=k+1;
case 4
% fixed variable, bounds are equal, set it at either bound
xtrans(i) = params.LB(i);
case 0
% unconstrained variable.
xtrans(i) = x(k);
k=k+1;
end
end
end % sub function xtransform end
|
github
|
Eden-Kramer-Lab/COMPASS-master
|
fminsearchcon.m
|
.m
|
COMPASS-master/COMPASS_StateSpaceToolbox/fminsearchcon.m
| 11,330 |
utf_8
|
c52011ee59580c69f3872d1b59630088
|
function [x,fval,exitflag,output]=fminsearchcon(fun,x0,LB,UB,A,b,nonlcon,options,varargin)
% FMINSEARCHCON: Extension of FMINSEARCHBND with general inequality constraints
% usage: x=FMINSEARCHCON(fun,x0)
% usage: x=FMINSEARCHCON(fun,x0,LB)
% usage: x=FMINSEARCHCON(fun,x0,LB,UB)
% usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b)
% usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon)
% usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon,options)
% usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon,options,p1,p2,...)
% usage: [x,fval,exitflag,output]=FMINSEARCHCON(fun,x0,...)
%
% arguments:
% fun, x0, options - see the help for FMINSEARCH
%
% x0 MUST be a feasible point for the linear and nonlinear
% inequality constraints. If it is not inside the bounds
% then it will be moved to the nearest bound. If x0 is
% infeasible for the general constraints, then an error will
% be returned.
%
% LB - lower bound vector or array, must be the same size as x0
%
% If no lower bounds exist for one of the variables, then
% supply -inf for that variable.
%
% If no lower bounds at all, then LB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% UB - upper bound vector or array, must be the same size as x0
%
% If no upper bounds exist for one of the variables, then
% supply +inf for that variable.
%
% If no upper bounds at all, then UB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% A,b - (OPTIONAL) Linear inequality constraint array and right
% hand side vector. (Note: these constraints were chosen to
% be consistent with those of fmincon.)
%
% A*x <= b
%
% nonlcon - (OPTIONAL) general nonlinear inequality constraints
% NONLCON must return a set of general inequality constraints.
% These will be enforced such that nonlcon is always <= 0.
%
% nonlcon(x) <= 0
%
%
% Notes:
%
% If options is supplied, then TolX will apply to the transformed
% variables. All other FMINSEARCH parameters should be unaffected.
%
% Variables which are constrained by both a lower and an upper
% bound will use a sin transformation. Those constrained by
% only a lower or an upper bound will use a quadratic
% transformation, and unconstrained variables will be left alone.
%
% Variables may be fixed by setting their respective bounds equal.
% In this case, the problem will be reduced in size for FMINSEARCH.
%
% The bounds are inclusive inequalities, which admit the
% boundary values themselves, but will not permit ANY function
% evaluations outside the bounds. These constraints are strictly
% followed.
%
% If your problem has an EXCLUSIVE (strict) constraint which will
% not admit evaluation at the bound itself, then you must provide
% a slightly offset bound. An example of this is a function which
% contains the log of one of its parameters. If you constrain the
% variable to have a lower bound of zero, then FMINSEARCHCON may
% try to evaluate the function exactly at zero.
%
% Inequality constraints are enforced with an implicit penalty
% function approach. But the constraints are tested before
% any function evaluations are ever done, so the actual objective
% function is NEVER evaluated outside of the feasible region.
%
%
% Example usage:
% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
%
% Fully unconstrained problem
% fminsearchcon(rosen,[3 3])
% ans =
% 1.0000 1.0000
%
% lower bound constrained
% fminsearchcon(rosen,[3 3],[2 2],[])
% ans =
% 2.0000 4.0000
%
% x(2) fixed at 3
% fminsearchcon(rosen,[3 3],[-inf 3],[inf,3])
% ans =
% 1.7314 3.0000
%
% simple linear inequality: x(1) + x(2) <= 1
% fminsearchcon(rosen,[0 0],[],[],[1 1],.5)
%
% ans =
% 0.6187 0.3813
%
% general nonlinear inequality: sqrt(x(1)^2 + x(2)^2) <= 1
% fminsearchcon(rosen,[0 0],[],[],[],[],@(x) norm(x)-1)
% ans =
% 0.78633 0.61778
%
% Of course, any combination of the above constraints is
% also possible.
%
% See test_main.m for other examples of use.
%
%
% See also: fminsearch, fminspleas, fminsearchbnd
%
%
% Author: John D'Errico
% E-mail: [email protected]
% Release: 1.0
% Release date: 12/16/06
% size checks
xsize = size(x0);
x0 = x0(:);
n=length(x0);
if (nargin<3) || isempty(LB)
LB = repmat(-inf,n,1);
else
LB = LB(:);
end
if (nargin<4) || isempty(UB)
UB = repmat(inf,n,1);
else
UB = UB(:);
end
if (n~=length(LB)) || (n~=length(UB))
error 'x0 is incompatible in size with either LB or UB.'
end
% defaults for A,b
if (nargin<5) || isempty(A)
A = [];
end
if (nargin<6) || isempty(b)
b = [];
end
nA = [];
nb = [];
if (isempty(A)&&~isempty(b)) || (isempty(b)&&~isempty(A))
error 'Sizes of A and b are incompatible'
elseif ~isempty(A)
nA = size(A);
b = b(:);
nb = size(b,1);
if nA(1)~=nb
error 'Sizes of A and b are incompatible'
end
if nA(2)~=n
error 'A is incompatible in size with x0'
end
end
% defaults for nonlcon
if (nargin<7) || isempty(nonlcon)
nonlcon = [];
end
% test for feasibility of the initial value
% against any general inequality constraints
if ~isempty(A)
if any(A*x0>b)
error 'Infeasible starting values (linear inequalities failed).'
end
end
if ~isempty(nonlcon)
if any(feval(nonlcon,(reshape(x0,xsize)),varargin{:})>0)
error 'Infeasible starting values (nonlinear inequalities failed).'
end
end
% set default options if necessary
if (nargin<8) || isempty(options)
options = optimset('fminsearch');
end
% stuff into a struct to pass around
params.args = varargin;
params.LB = LB;
params.UB = UB;
params.fun = fun;
params.n = n;
params.xsize = xsize;
params.OutputFcn = [];
params.A = A;
params.b = b;
params.nonlcon = nonlcon;
% 0 --> unconstrained variable
% 1 --> lower bound only
% 2 --> upper bound only
% 3 --> dual finite bounds
% 4 --> fixed variable
params.BoundClass = zeros(n,1);
for i=1:n
k = isfinite(LB(i)) + 2*isfinite(UB(i));
params.BoundClass(i) = k;
if (k==3) && (LB(i)==UB(i))
params.BoundClass(i) = 4;
end
end
% transform starting values into their unconstrained
% surrogates. Check for infeasible starting guesses.
x0u = x0;
k=1;
for i = 1:n
switch params.BoundClass(i)
case 1
% lower bound only
if x0(i)<=LB(i)
% infeasible starting value. Use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(x0(i) - LB(i));
end
% increment k
k=k+1;
case 2
% upper bound only
if x0(i)>=UB(i)
% infeasible starting value. use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(UB(i) - x0(i));
end
% increment k
k=k+1;
case 3
% lower and upper bounds
if x0(i)<=LB(i)
% infeasible starting value
x0u(k) = -pi/2;
elseif x0(i)>=UB(i)
% infeasible starting value
x0u(k) = pi/2;
else
x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1;
% shift by 2*pi to avoid problems at zero in fminsearch
% otherwise, the initial simplex is vanishingly small
x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k))));
end
% increment k
k=k+1;
case 0
% unconstrained variable. x0u(i) is set.
x0u(k) = x0(i);
% increment k
k=k+1;
case 4
% fixed variable. drop it before fminsearch sees it.
% k is not incremented for this variable.
end
end
% if any of the unknowns were fixed, then we need to shorten
% x0u now.
if k<=n
x0u(k:n) = [];
end
% were all the variables fixed?
if isempty(x0u)
% All variables were fixed. quit immediately, setting the
% appropriate parameters, then return.
% undo the variable transformations into the original space
x = xtransform(x0u,params);
% final reshape
x = reshape(x,xsize);
% stuff fval with the final value
fval = feval(params.fun,x,params.args{:});
% fminsearchbnd was not called
exitflag = 0;
output.iterations = 0;
output.funcCount = 1;
output.algorithm = 'fminsearch';
output.message = 'All variables were held fixed by the applied bounds';
% return with no call at all to fminsearch
return
end
% Check for an outputfcn. If there is any, then substitute my
% own wrapper function.
if ~isempty(options.OutputFcn)
params.OutputFcn = options.OutputFcn;
options.OutputFcn = @outfun_wrapper;
end
% now we can call fminsearch, but with our own
% intra-objective function.
[xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params);
% undo the variable transformations into the original space
x = xtransform(xu,params);
% final reshape
x = reshape(x,xsize);
% Use a nested function as the OutputFcn wrapper
function stop = outfun_wrapper(x,varargin);
% we need to transform x first
xtrans = xtransform(x,params);
% then call the user supplied OutputFcn
stop = params.OutputFcn(xtrans,varargin{1:(end-1)});
end
end % mainline end
% ======================================
% ========= begin subfunctions =========
% ======================================
function fval = intrafun(x,params)
% transform variables, test constraints, then call original function
% transform
xtrans = xtransform(x,params);
% test constraints before the function call
% First, do the linear inequality constraints, if any
if ~isempty(params.A)
% Required: A*xtrans <= b
if any(params.A*xtrans(:) > params.b)
% linear inequality constraints failed. Just return inf.
fval = inf;
return
end
end
% resize xtrans to be the correct size for the nonlcon
% and objective function calls
xtrans = reshape(xtrans,params.xsize);
% Next, do the nonlinear inequality constraints
if ~isempty(params.nonlcon)
% Required: nonlcon(xtrans) <= 0
cons = feval(params.nonlcon,xtrans,params.args{:});
if any(cons(:) > 0)
% nonlinear inequality constraints failed. Just return inf.
fval = inf;
return
end
end
% we survived the general inequality constraints. Only now
% do we evaluate the objective function.
% append any additional parameters to the argument list
fval = feval(params.fun,xtrans,params.args{:});
end % sub function intrafun end
% ======================================
function xtrans = xtransform(x,params)
% converts unconstrained variables into their original domains
xtrans = zeros(1,params.n);
% k allows some variables to be fixed, thus dropped from the
% optimization.
k=1;
for i = 1:params.n
switch params.BoundClass(i)
case 1
% lower bound only
xtrans(i) = params.LB(i) + x(k).^2;
k=k+1;
case 2
% upper bound only
xtrans(i) = params.UB(i) - x(k).^2;
k=k+1;
case 3
% lower and upper bounds
xtrans(i) = (sin(x(k))+1)/2;
xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i);
% just in case of any floating point problems
xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i)));
k=k+1;
case 4
% fixed variable, bounds are equal, set it at either bound
xtrans(i) = params.LB(i);
case 0
% unconstrained variable.
xtrans(i) = x(k);
k=k+1;
end
end
end % sub function xtransform end
|
github
|
cs4243-ay1718-group12/lucas-kanade-tracker-master
|
LK_Track_Pyramid_Iterative.m
|
.m
|
lucas-kanade-tracker-master/deprecated/LK_Track_Pyramid_Iterative.m
| 2,670 |
utf_8
|
891f603e5d49bda89930ac20a026c2ba
|
function [U, V] = LK_Track_Pyramid_Iterative(raw_img1, raw_img2, X, Y)
% Constants
win_rad = 5;
accuracy_threshold = .01;
max_iterations = 20;
max_levels = Maximum_Pyramid_Level(raw_img1, 128);
num_points = size(X,1);
% Get images for each pyramid levels
img1_pyramidized = generate_pyramid(raw_img1, max_levels);
img2_pyramidized = generate_pyramid(raw_img2, max_levels);
U = X/2^max_levels;
V = Y/2^max_levels;
for level = max_levels:-1:1
% Get image for this level
img1 = img1_pyramidized{level};
img2 = img2_pyramidized{level};
[num_rows, num_cols] = size(img1);
h = fspecial('sobel');
img1x = imfilter(img1,h','replicate');
img1y = imfilter(img1,h,'replicate');
for point = 1 : num_points
xt = U(point)*2;
yt = V(point)*2;
[iX, iY, oX, oY, is_out_of_bound] = generate_window(xt, yt, win_rad, num_rows, num_cols);
if is_out_of_bound
continue;
end
Ix = interp2(iX,iY,img1x(iY,iX),oX,oY);
Iy = interp2(iX,iY,img1y(iY,iX),oX,oY);
I1 = interp2(iX,iY,img1(iY,iX),oX,oY);
for i = 1 : max_iterations
[iX, iY, oX, oY, is_out_of_bound] = generate_window(xt, yt, win_rad, num_rows, num_cols);
if is_out_of_bound, break; end
It = interp2(iX,iY,img2(iY,iX),oX,oY) - I1;
vel = [Ix(:),Iy(:)]\It(:);
xt = xt+vel(1);
yt = yt+vel(2);
if max(abs(vel)) < accuracy_threshold
break;
end
end
U(point) = xt;
V(point) = yt;
end
end
end
function [cols_range, rows_range, oX, oY, is_out_of_bound] = generate_window(x, y, win_rad, num_rows, num_cols)
% Get window size
left_bound = x - win_rad;
right_bound = x + win_rad;
top_bound = y - win_rad;
bottom_bound = y + win_rad;
% x and y can be non-integers because U=X/2^level AND V=Y/2^level
fl = floor(left_bound);
cr = ceil(right_bound);
ft = floor(top_bound);
cb = ceil(bottom_bound);
% Get the range of cols and rows in the window
cols_range = fl:cr;
rows_range = ft:cb;
% Get ... considering using our own method for meshgrid
[oX,oY] = meshgrid(left_bound:right_bound,top_bound:bottom_bound);
% Check if the window is outside the image
if (fl < 1 || ft < 1 || cr > num_cols || cb > num_rows)
is_out_of_bound = true;
else
is_out_of_bound = false;
end
end
|
github
|
bentong95923/music_notation_printer-master
|
acf.m
|
.m
|
music_notation_printer-master/code/autocorrelation/sample_code/acf.m
| 2,353 |
utf_8
|
a06fdab5c89736f28e9ce08df507dfa2
|
function ta = acf(y,p)
% ACF - Compute Autocorrelations Through p Lags
% >> myacf = acf(y,p)
%
% Inputs:
% y - series to compute acf for, nx1 column vector
% p - total number of lags, 1x1 integer
%
% Output:
% myacf - px1 vector containing autocorrelations
% (First lag computed is lag 1. Lag 0 not computed)
%
%
% A bar graph of the autocorrelations is also produced, with
% rejection region bands for testing individual autocorrelations = 0.
%
% Note that lag 0 autocorelation is not computed,
% and is not shown on this graph.
%
% Example:
% >> acf(randn(100,1), 10)
%
% --------------------------
% USER INPUT CHECKS
% --------------------------
[n1, n2] = size(y) ;
if n2 ~=1
error('Input series y must be an nx1 column vector')
end
[a1, a2] = size(p) ;
if ~((a1==1 & a2==1) & (p<n1))
error('Input number of lags p must be a 1x1 scalar, and must be less than length of series y')
end
% -------------
% BEGIN CODE
% -------------
ta = zeros(p,1) ;
global N
N = max(size(y)) ;
disp(N);
global ybar
ybar = mean(y);
% Collect ACFs at each lag i
for i = 1:p
ta(i) = acf_k(y,i) ;
end
% Plot ACF
% Plot rejection region lines for test of individual autocorrelations
% H_0: rho(tau) = 0 at alpha=.05
bar(ta)
line([0 p+.5], (1.96)*(1/sqrt(N))*ones(1,2))
line([0 p+.5], (-1.96)*(1/sqrt(N))*ones(1,2))
% Some figure properties
line_hi = (1.96)*(1/sqrt(N))+.05;
line_lo = -(1.96)*(1/sqrt(N))-.05;
bar_hi = max(ta)+.05 ;
bar_lo = -max(ta)-.05 ;
if (abs(line_hi) > abs(bar_hi)) % if rejection lines might not appear on graph
axis([0 p+.60 line_lo line_hi])
else
axis([0 p+.60 bar_lo bar_hi])
end
title({' ','Sample Autocorrelations',' '})
xlabel('Lag Length')
set(gca,'YTick',[-1:.20:1])
% set number of lag labels shown
if (p<28 & p>4)
set(gca,'XTick',floor(linspace(1,p,4)))
elseif (p>=28)
set(gca,'XTick',floor(linspace(1,p,8)))
end
set(gca,'TickLength',[0 0])
% ---------------
% SUB FUNCTION
% ---------------
function ta2 = acf_k(y,k)
% ACF_K - Autocorrelation at Lag k
% acf(y,k)
%
% Inputs:
% y - series to compute acf for
% k - which lag to compute acf
%
global ybar
global N
cross_sum = zeros(N-k,1) ;
% Numerator, unscaled covariance
for i = (k+1):N
cross_sum(i) = (y(i)-ybar)*(y(i-k)-ybar) ;
end
% Denominator, unscaled variance
yvar = (y-ybar)'*(y-ybar) ;
ta2 = sum(cross_sum) / yvar ;
|
github
|
pvarin/DynamicVAE-master
|
jdqr.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/jdqr.m
| 73,068 |
utf_8
|
b45810ddb5b2767c9289909175d1dc04
|
function varargout=jdqr(varargin)
%JDQR computes a partial Schur decomposition of a square matrix or operator.
% Lambda = JDQR(A) returns the absolute largest eigenvalues in a K vector
% Lambda. Here K=min(5,N) (unless K has been specified), where N=size(A,1).
% JDQR(A) (without output argument) displays the K eigenvalues.
%
% [X,Lambda] = JDQR(A) returns the eigenvectors in the N by K matrix X and
% the eigenvalues in the K by K diagonal matrix Lambda. Lambda contains the
% Jordan structure if there are multiple eigenvalues.
%
% [X,Lambda,HISTORY] = JDQR(A) returns also the convergence history
% (that is, norms of the subsequential residuals).
%
% [X,Lambda,Q,S] = JDQR(A) returns also a partial Schur decomposition:
% S is an K by K upper triangular matrix and Q is an N by K orthonormal matrix
% such that A*Q = Q*S. The diagonal elements of S are eigenvalues of A.
%
% [X,Lambda,Q,S,HISTORY] = JDQR(A) returns also the convergence history.
%
% [X,Lambda,HISTORY] = JDQR('Afun')
% [X,Lambda,HISTORY] = JDQR('Afun',N)
% The first input argument is either a square matrix (which can be
% full or sparse, symmetric or nonsymmetric, real or complex), or a
% string containing the name of an M-file which applies a linear
% operator to a given column vector. In the latter case, the M-file must
% return the the order N of the problem with N = Afun([],'dimension') or
% N must be specified in the list of input arguments.
% For example, EIGS('fft',...) is much faster than EIGS(F,...)
% where F is the explicit FFT matrix.
%
% The remaining input arguments are optional and can be given in
% practically any order:
% ... = JDQR(A,K,SIGMA,OPTIONS)
% ... = JDQR('Afun',K,SIGMA,OPTIONS)
% where
%
% K An integer, the number of eigenvalues desired.
% SIGMA A scalar shift or a two letter string.
% OPTIONS A structure containing additional parameters.
%
% With one output argument, S is a vector containing K eigenvalues.
% With two output arguments, S is a K-by-K upper triangular matrix
% and Q is a matrix with K columns so that A*Q = Q*S and Q'*Q=I.
% With three output arguments, HISTORY contains the convergence history.
%
% If K is not specified, then K = MIN(N,5) eigenvalues are computed.
%
% If SIGMA is not specified, then the K-th eigenvalues largest in magnitude
% are computed. If SIGMA is zero, then the K-th eigenvalues smallest in
% magnitude are computed. If SIGMA is a real or complex scalar then the
% K-th eigenvalues nearest SIGMA are computed. If SIGMA is one of the
% following strings, then it specifies the desired eigenvalues.
%
% SIGMA Location wanted eigenvalues
%
% 'LM' Largest Magnitude (the default)
% 'SM' Smallest Magnitude (same as sigma = 0)
% 'LR' Largest Real part
% 'SR' Smallest Real part
% 'BE' Both Ends. Computes k/2 eigenvalues
% from each end of the spectrum (one more
% from the high end if k is odd.)
%
%
% The OPTIONS structure specifies certain parameters in the algorithm.
%
% Field name Parameter Default
%
% OPTIONS.Tol Convergence tolerance: 1e-8
% norm(A*Q-Q*S,1) <= tol * norm(A,1)
% OPTIONS.jmin minimum dimension search subspace k+5
% OPTIONS.jmax maximum dimension search subspace jmin+5
% OPTIONS.MaxIt Maximum number of iterations. 100
% OPTIONS.v0 Starting space ones+0.1*rand
% OPTIONS.Schur Gives schur decomposition 'no'
% also in case of 2 or 3 output
% arguments (X=Q, Lambda=R).
%
% OPTIONS.TestSpace For using harmonic Ritz values 'Standard'
% If 'TestSpace'='Harmonic' then
% sigma=0 is the default value for SIGMA
%
% OPTIONS.Disp Shows size of intermediate residuals 1
% and displays the appr. eigenvalues.
%
% OPTIONS.LSolver Linear solver 'GMRES'
% OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,..
% OPTIONS.LS_MaxIt Maximum number it. linear solver 5
% OPTIONS.LS_ell ell for BiCGstab(ell) 4
%
% OPTIONS.Precond Preconditioner LU=[[],[]].
%
% For instance
%
% OPTIONS=STRUCT('Tol',1.0e-10,'LSolver','BiCGstab','LS_ell',2,'Precond',M);
%
% changes the convergence tolerance to 1.0e-10, takes BiCGstab(2) as linear
% solver and the preconditioner defined in M.m if M is the string 'M',
% or M = L*U if M is an n by 2*n matrix: M = [L,U].
%
% The preconditoner can be specified in the OPTIONS structure,
% but also in the argument list:
% ... = JDQR(A,K,SIGMA,M,OPTIONS)
% ... = JDQR(A,K,SIGMA,L,U,OPTIONS)
% ... = JDQR('Afun',K,SIGMA,'M',OPTIONS)
% ... = JDQR('Afun',K,SIGMA,'L','U',OPTIONS)
% as an N by N matrix M (then M is the preconditioner), or an N by 2*N
% matrix M (then L*U is the preconditioner, where M = [L,U]),
% or as N by N matrices L and U (then L*U is the preconditioner),
% or as one or two strings containing the name of M-files ('M', or
% 'L' and 'U') which apply a linear operator to a given column vector.
%
% JDQR (without input arguments) lists the options and the defaults.
% Gerard Sleijpen.
% Copyright (c) 98
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
global Qschur Rschur PinvQ Pinv_u Pu nm_operations
if nargin==0, possibilities, return, end
%%% Read/set parameters
[n,nselect,sigma,SCHUR,...
jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV0,t_tol,...
lsolver,LSpar] = ReadOptions(varargin{1:nargin});
LSpar0=LSpar; JDV=0; tol0=tol; LOCK0=~ischar(sigma);
if nargout>3, SCHUR=0; end
tau=0; if INTERIOR>=1 & LOCK0, tau=sigma(1); end
n_tar=size(sigma,1); nt=1; FIG=gcf;
%%% Initiate global variables
Qschur = zeros(n,0); Rschur = [];
PinvQ = zeros(n,0); Pinv_u = zeros(n,1); Pu = [];
nm_operations = 0; history = [];
%%% Return if eigenvalueproblem is trivial
if n<2
if n==1, Qschur=1; Rschur=MV(1); end
if nargout == 0, eigenvalue=Rschur, else
[varargout{1:nargout}]=output(history,Qschur,Rschur); end,
return, end
String = ['\r#it=%i #MV=%i dim(V)=%i |r_%i|=%6.1e '];
StrinP = '--- Checking for conjugate pair ---\n';
time = clock;
%%% Initialize V, W:
%%% V,W orthonormal, A*V=W*R+Qschur*E, R upper triangular
[V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol);
j=size(V,2); k=size(Rschur,1);
nit=0; nlit=0; SOLVED=0;
switch INTERIOR
case 0
%%% The JD loop (Standard)
%%% V orthogonal, V orthogonal to Qschur
%%% V*V=eye(j), Qschur'*V=0,
%%% W=A*V, M=V'*W
%%%
W=W*R; if tau ~=0; W=W+tau*V; end, M=M'*R; temptarget=sigma(nt,:);
while (k<nselect) & (nit < maxit)
%%% Compute approximate eigenpair and residual
[UR,S]=SortSchur(M,temptarget,j==jmax,jmin);
y=UR(:,1); theta=S(1,1); u=V*y; w=W*y;
r=w-theta*u; [r,s]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1;
if LOCK0 & nr<t_tol, temptarget=[theta;sigma(nt,:)]; end
% defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr);
% DispResult('defekt',defekt,3)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
history=[history;nr,nit,nm_operations]; %%%
if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%%
if SHOW == 2, LOCK = LOCK0 & nr<t_tol; %%%
if MovieTheta(n,nit,diag(S),jmin,sigma(nt,:),LOCK,j==jmax) %%%
break, end, end, end %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check for convergence
if nr<tol
%%% Expand the partial Schur form
Qschur=[Qschur,u];
%% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1;
Rschur=[Rschur,s;zeros(1,k),theta]; k=k+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SHOW, ShowLambda(theta,k), end %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if k>=nselect, break, end, r_KNOWN=0;
%%% Expand preconditioned Schur matrix PinvQ
SOLVED=UpdateMinv(u,SOLVED);
if j==1,
[V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol);
k=size(Rschur,1); if k>=nselect, break, end
W=W*R; if tau ~=0; W=W+tau*V; end; M=M'*R; j=size(V,2);
else,
J=[2:j]; j=j-1; UR=UR(:,J);
M=S(J,J); V=V*UR; W=W*UR;
end
if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));
if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end
end
if EXPAND, temptarget=conj(theta); if SHOW, fprintf(StrinP), end
else, nlit=0; nt=min(nt+1,n_tar); temptarget=sigma(nt,:); end
end % nr<tol
%%% Check for shrinking the search subspace
if j>=jmax
j=jmin; J=[1:j]; UR=UR(:,J);
M=S(J,J); V=V*UR; W=W*UR;
end % if j>=jmax
if r_KNOWN
%%% Solve correction equation
v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;
nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;
end % if r_KNOWN
if EXPAND
%%% Expand the subspaces of the interaction matrix
v=RepGS([Qschur,V],v);
if size(v,2)>0
w=MV(v);
M=[M,V'*w;v'*W,v'*w];
V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;
else
tol=2*tol;
end
end % if EXPAND
end % while (nit<maxit)
case 1
%%% The JD loop (Harmonic Ritz values)
%%% Both V and W orthonormal and orthogonal w.r.t. Qschur
%%% V*V=eye(j), Qschur'*V=0, W'*W=eye(j), Qschur'*W=0
%%% (A*V-tau*V)=W*R+Qschur*E, E=Qschur'*(A*V-tau*V), M=W'*V
%%%
temptarget=0; FIXT=1; lsolver0=lsolver;
while (k<nselect) & (nit<maxit)
%%% Compute approximate eigenpair and residual
[UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin);
y=UR(:,1); theta=T(1,1)'*S(1,1);
u=V*y; w=W*(R*y); r=w-theta*u; nr=norm(r); r_KNOWN=1;
if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau;
% defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr);
% DispResult('defect',defekt,3)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
history=[history;nr,nit,nm_operations]; %%%
if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%%
if SHOW == 2, Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%%
if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%%
break, end, end, end %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check for convergence
if nr<tol
%%% Expand the partial Schur form
Qschur=[Qschur,u];
%% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1;
Rschur=[Rschur,E*y;zeros(1,k),theta]; k=k+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SHOW, ShowLambda(theta,k), end %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if k>=nselect, break, end, r_KNOWN=0; JDV=0;
%%% Expand preconditioned Schur matrix PinvQ
SOLVED=UpdateMinv(u,SOLVED);
if j==1,
[V,W,R,E,M]=...
SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol);
k=size(Rschur,1); if k>=nselect, break, end, j=size(V,2);
else
J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J);
R=S(J,J); M=T(J,J); V=V*UR; W=W*UL;
[r,a]=RepGS(u,r,0); E=[E*UR;(T(1,1)'-a/S(1,1))*S(1,J)];
s=(S(1,J)/S(1,1))/R; W=W+r*s; M=M+s'*(r'*V);
if (nr*norm(s))^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end
end
if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));
if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end
end
if EXPAND, if SHOW, fprintf(StrinP), end
temptarget=[conj(theta)-tau;0];
else, nlit=0; temptarget=0;
if nt<n_tar
nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau;
[W,R]=qr(W*R+tau0*V,0); M=W'*V;
end
end
end
%%% Check for shrinking the search subspace
if j>=jmax
j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J);
R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; E=E*UR;
end % if j>=jmax
if r_KNOWN
%%% Solve correction equation
if JDV, disp('Stagnation'),
LSpar(end-1)=(LSpar(end-1)+15)*2;
% lsolver='bicgstab'; LSpar=[1.e-2,300,4];
else
LSpar=LSpar0; JDV=0; lsolver=lsolver0;
end
if nr>0.001 & FIXT, theta=tau; else, FIXT=0; end
v=Solve_pce(theta,u,r,lsolver,LSpar,nlit);
nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; SOLVED=1; JDV=0;
end
if EXPAND
%%% Expand the subspaces of the interaction matrix
[v,zeta]=RepGS([Qschur,V],v);
if JDV0 & abs(zeta(end,1))/norm(zeta)<0.06, JDV=JDV+1; end
if size(v,2)>0
w=MV(v); if tau ~=0, w=w-tau*v; end
[w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w);
R=[[R;zeros(1,j)],y]; M=[M,W'*v;w'*V,w'*v]; E=[E,e];
V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;
else
tol=2*tol;
end
end
end % while (nit<maxit)
case 1.1
%%% The JD loop (Harmonic Ritz values)
%%% V W AV.
%%% Both V and W orthonormal and orthogonal w.r.t. Qschur, AV=A*V-tau*V
%%% V*V=eye(j), W'*W=eye(j), Qschur'*V=0, Qschur'*W=0,
%%% (I-Qschur*Qschur')*AV=W*R, M=W'*V; R=W'*AV;
%%%
AV=W*R; temptarget=0;
while (k<nselect) & (nit<maxit)
%%% Compute approximate eigenpair and residual
[UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin);
y=UR(:,1); u=V*y; w=AV*y; theta=u'*w;
r=w-theta*u; [r,y]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1;
if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau;
% defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr);
% DispResult('defect',defekt,3)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
history=[history;nr,nit,nm_operations]; %%%
if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%%
if SHOW == 2,Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%%
if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%%
break, end, end, end %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check for convergence
if nr<tol
%%% Expand the partial Schur form
Qschur=[Qschur,u];
%% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1;
Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SHOW, ShowLambda(theta,k), end %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if k>=nselect, break, end, r_KNOWN=0;
%%% Expand preconditioned Schur matrix PinvQ
SOLVED=UpdateMinv(u,SOLVED);
if j==1
[V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol);
k=size(Rschur,1); if k>=nselect, break, end
AV=W*R; j=size(V,2);
else
J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J);
AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL;
end
if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));
if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end
end
if EXPAND,if SHOW, fprintf(StrinP), end
temptarget=[conj(theta)-tau;0];
else, nlit=0; temptarget=0;
if nt<n_tar
nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau;
AV=AV+tau0*V; [W,R]=qr(W*R+tau0*V,0); M=W'*V;
end
end
end
%%% Check for shrinking the search subspace
if j>=jmax
j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J);
AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL;
end % if j>=jmax
if r_KNOWN
%%% Solve correction equation
v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;
nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;
end
if EXPAND
%%% Expand the subspaces of the interaction matrix
v=RepGS([Qschur,V],v);
if size(v,2)>0
w=MV(v); if tau ~=0, w=w-tau*v;end
AV=[AV,w]; R=[R,W'*w];
w=RepGS([Qschur,W],w);
R=[R;w'*AV]; M=[M,W'*v;w'*V,w'*v];
V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0;
else
tol=2*tol;
end
end
end % while (nit<maxit)
case 1.2
%%% The JD loop (Harmonic Ritz values)
%%% W orthonormal, V and W orthogonal to Qschur,
%%% W'*W=eye(j), Qschur'*V=0, Qschur'*W=0
%%% W=(A*V-tau*V)-Qschur*E, E=Qschur'*(A*V-tau*V),
%%% M=W'*V
V=V/R; M=M/R; temptarget='LM'; E=E/R;
while (k<nselect) & (nit<maxit)
%%% Compute approximate eigenpair and residual
[UR,S]=SortSchur(M,temptarget,j==jmax,jmin);
y=UR(:,1); u=V*y; nrm=norm(u); y=y/nrm; u=u/nrm;
theta=S(1,1)'/(nrm*nrm); w=W*y; r=w-theta*u; nr=norm(r); r_KNOWN=1;
if nr<t_tol, temptarget=[S(1,1);inf]; end, theta=theta+tau;
% defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr);
% DispResult('defect',defekt,3)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
history=[history;nr,nit,nm_operations]; %%%
if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%%
if SHOW == 2, Lambda=1./diag(S)+tau; Lambda(1)=theta; %%%
if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%%
break, end, end, end %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check for convergence
if nr<tol
%%% Expand the partial Schur form
Qschur=[Qschur,u];
%% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1;
y=E*y; Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SHOW, ShowLambda(theta,k), end %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if k>=nselect, break, end, r_KNOWN=0;
%%% Expand preconditioned Schur matrix PinvQ
SOLVED=UpdateMinv(u,SOLVED);
if j==1
[V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol);
k=size(Rschur,1); if k>=nselect, break, end
V=V/R; j=size(V,2); M=M/R; E=E/R;
else
J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J);
V=V*UR; W=W*UR; [r,a]=RepGS(u,r,0);
s=u'*V; V=V-u*s; W=W-r*s; M=M-s'*(r'*V)-(W'*u)*s;
E=[E*UR-y*s;(tau-theta-a)*s];
if (nr*norm(s))^2>eps, [W,R]=qr(W,0); V=V/R; M=(R'\M)/R; E=E/R; end
end
if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u)));
if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end
end
if EXPAND, if SHOW, fprintf(StrinP), end
temptarget=[1/(conj(theta)-tau);inf];
else, nlit=0; temptarget='LM';
if nt<n_tar
nt=nt+1; tau0=tau; tau=sigma(nt,1);
[W,R]=qr(W+(tau0-tau)*V,0); V=V/R; M=W'*V; E=E/R;
end
end
end
%%% Check for shrinking the search subspace
if j>=jmax
j=jmin; J=[1:j]; UR=UR(:,J);
M=S(J,J); V=V*UR; W=W*UR; E=E*UR;
end % if j>=jmax
if r_KNOWN
%%% Solve correction equation
v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1;
nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1;
end
if EXPAND
%%% Expand the subspaces of the interaction matrix
v=RepGS(Qschur,v,0);
if size(v,2)>0
w=MV(v); if tau ~=0, w=w-tau*v; end
[w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w);
nrw=y(j+1,1); y=y(1:j,:);
v=v-V*y; v=v/nrw; e=e-E*y; e=e/nrw;
M=[M,W'*v;w'*V,w'*v];
V=[V,v]; W=[W,w]; j=j+1; E=[E,e];
if 1/cond(M)<10*tol
[V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E);
k=size(Rschur,1); if k>=nselect, break, end
V=V/R; M=M/R; j=size(V,2);temptarget='LM'; E=E/R;
end
EXPAND=0; tol=tol0;
else
tol=2*tol;
end
end
end % while (nit<maxit)
end % case
time_needed=etime(clock,time);
Refine([Qschur,V],1);% 2-SCHUR);
CheckSortSchur(sigma);
Lambda=[]; X=zeros(n,0);
if ~SCHUR & k>0, [z,Lambda]=Jordan(Rschur); X=Qschur*z; end
%-------------- display results ----------------------------
if SHOW == 2, MovieTheta, figure(FIG), end
if SHOW & size(history,1)>0
switch INTERIOR
case 0
testspace='V, V orthonormal';
case 1
testspace='A*V-sigma*V, V and W orthonormal';
case 1.1
testspace='A*V-sigma*V, V and W orthonormal, AV';
case 1.2
testspace='A*V-sigma*V, W orthogonal';
otherwise
testspace='Experimental';
end
StringT=sprintf('The test subspace W is computed as W = %s.',testspace);
StringX=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',...
jmin,jmax,tol);
StringY=sprintf('Correction equation solved with %s.',lsolver);
date=fix(clock);
String=sprintf('\n%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6));
StringL='log_{10} || r_{#it} ||_2';
for pl=1:SHOW
subplot(SHOW,1,pl), t=history(:,pl+1);
plot(t,log10(history(:,1)),'*-',t,log10(tol)+0*t,':')
legend(StringL), title(StringT)
StringL='log_{10} || r_{#MV} ||_2'; StringT=StringX;
end
if SHOW==2, xlabel([StringY,String])
else, xlabel([StringX,String]), ylabel(StringY), end
drawnow
end
if SHOW
str1=num2str(abs(k-nselect)); str='s';
if k>nselect,
if k==nselect+1, str1='one'; str=''; end
fprintf('\n\nDetected %s additional eigenpair%s.',str1,str)
end
if k<nselect,
if k==0, str1='any'; str=''; elseif k==nselect-1, str1='one'; str=''; end
fprintf('\n\nFailed detection of %s eigenpair%s.',str1,str)
end
if k>0, ShowLambda(diag(Rschur)); else, fprintf('\n'); end
Str='time_needed'; DispResult(Str,eval(Str))
if (k>0)
if ~SCHUR
Str='norm(MV(X)-X*Lambda)'; DispResult(Str,eval(Str))
end
Str='norm(MV(Qschur)-Qschur*Rschur)'; DispResult(Str,eval(Str))
I=eye(k); Str='norm(Qschur''*Qschur-I)'; DispResult(Str,eval(Str))
end
fprintf('\n\n')
end
if nargout == 0, if ~SHOW, eigenvalues=diag(Rschur), end, return, end
[varargout{1:nargout}]=output(history,X,Lambda);
return
%===========================================================================
%======= PREPROCESSING =====================================================
%===========================================================================
%======= INITIALIZE SUBSPACE ===============================================
function [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E);
%[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol);
% Output: V(:,1:SIZE(VV,2))=ORTH(VV),
% V'*V=W'*W=EYE(JMIN), M=W'*V;
% such that A*V-tau*V=W*R+Qschur*E,
% with R upper triangular, and E=Qschur'*(A*V-tau*V).
%
%[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol,AV,EE);
% Input such that
% A*VV-tau*VV=AV+Qschur*EE, EE=Qschur'*(A*VV-tau*VV);
%
% Output: V(:,1:SIZE(VV,2))=ORTH(VV),
% V'*V=W'*W=EYE(JMIN), M=W'*V;
% such that A*V-tau*V=W*R+Qschur*E,
% with R upper triangular, and E=Qschur'*(A*V-tau*V).
global Qschur Rschur
[n,j]=size(V); k=size(Qschur,2);
if j>1,
[V,R]=qr(V,0);
if nargin <6,
W=MV(V); R=eye(j); if tau~=0, W=W-tau*V; end
if k>0, E=Qschur'*W; W=W-Qschur*E; else, E=zeros(0,j); end
end
[V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,R);
l=size(Qschur,2); j=size(V,2);
if l>=nselect, if size(V,2)==0; R=1; M=1; return, end, end
if l>k, UpdateMinv(Qschur(:,k+1:l),0); end, k=l;
end
if j==0, nr=0;
while nr==0
V = ones(n,1)+0.1*rand(n,1); V=RepGS(Qschur,V); nr=norm(V);
end, j=1;
end
if j==1
[V,H,E]=Arnoldi(V,tau,jmin,nselect,tol);
l=size(Qschur,2); j=max(size(H,2),1);
if l>=nselect, W=V; R=eye(j); M=R; return, end
if l>k, UpdateMinv(Qschur(:,k+1:l),0); end
[Q,R]=qr(full(H),0);
W=V*Q; V(:,j+1)=[]; M=Q(1:j,:)';
%% W=V*Q; V=V(:,1:j)/R; E=E/R; R=eye(j); M=Q(1:j,:)'/R;
%% W=V*H; V(:,j+1)=[];R=R'*R; M=H(1:j,:)';
end
return
%%%======== ARNOLDI (for initializing spaces) ===============================
function [V,H,E]=Arnoldi(v,tau,jmin,nselect,tol)
%
%[V,AV,H,nMV,tau]=ARNOLDI(A,V0,TAU,JMIN,NSELECT,TOL)
% ARNOLDI computes the Arnoldi factorization of dimenison JMIN+1:
% (A-tau)*V(:,1:JMIN)=V*H where V is n by JMIN+1 orthonormal with
% first column a multiple of V0, and H is JMIN+1 by JMIN Hessenberg.
%
% If an eigenvalue if H(1:j,1:j) is an eigenvalue of A
% within the required tolerance TOL then the Schurform
% A*Qschur=Qschur*Rschur is expanded and the Arnoldi factorization
% (A-tau)*V(:,1:j)=V(:,1:j+1)*H(1:j+1,1:j) is deflated.
% Returns if size(Qschur,2) = NSELECT or size(V,2) = JMIN+1
% (A-tau)*V(:,1:JMIN)=V*H+Qschur*E, Qschur'*V=0
% Coded November 5, 1998, G. Sleijpen
global Qschur Rschur
k=size(Qschur,2); [n,j]=size(v);
if ischar(tau), tau=0; end
H=zeros(1,0); V=zeros(n,0); E=[];
j=0; nr=norm(v);
while j<jmin & k<nselect & j+k<n
if nr>=tol
v=v/nr; V=[V,v]; j=j+1;
Av=MV(v);
end
if j==0
H=zeros(1,0); j=1;
nr=0; while nr==0, v=RepGS(Qschur,rand(n,1)); nr=norm(v); end
v=v/nr; V=v; Av=MV(v);
end
if tau~=0; Av=Av-tau*v; end, [v,e] = RepGS(Qschur,Av,0);
if k==0, E=zeros(0,j); else, E = [E,e(1:k,1)]; end
[v,y] = RepGS(V,v,0); H = [H,y(1:j,1)];
nr = norm(v); H = [H;zeros(1,j-1),nr];
[Q,U,H1] = DeflateHess(full(H),tol);
j=size(U,2); l=size(Q,2);
if l>0 %--- expand Schur form ------
Qschur=[Qschur,V*Q];
Rschur=[Rschur,E*Q; zeros(l,k),H1(1:l,1:l)+tau*eye(l)]; k=k+l;
E=[E*U;H1(1:l,l+1:l+j)];
if j>0, V=V*U; H=H1(l+1:l+j+1,l+1:l+j);
else, V=zeros(n,0); H=zeros(1,0); end
end
end % while
if nr>=tol
v=v/nr; V=[V,v];
end
return
%----------------------------------------------------------------------
function [Q,U,H]=DeflateHess(H,tol)
% H_in*[Q,U]=[Q,U]*H_out such that H_out(K,K) upper triangular
% where K=1:SIZE(Q,2) and ABS(Q(end,2)*H_in(j+1,j))<TOL, j=SIZE(H,2),
[j1,j]=size(H);
if j1==j, [Q,H]=schur(H); U=zeros(j,0); return, end
nr=H(j+1,j);
U=eye(j); i=1; J=i:j;
for l=1:j
[X,Lambda]=eig(H(J,J));
I=find(abs(X(size(X,1),:)*nr)<tol);
if isempty(I), break, end
q=X(:,I(1)); q=q/norm(q);
q(1,1)=q(1,1)+sign(q(1,1)); q=q/norm(q);
H(:,J)=H(:,J)-(2*H(:,J)*q)*q';
H(J,:)=H(J,:)-2*q*(q'*H(J,:));
U(:,J)=U(:,J)-(2*U(:,J)*q)*q';
i=i+1; J=i:j;
end
[Q,HH]=RestoreHess(H(i:j+1,J));
H(:,J)=H(:,J)*Q; H(J,:)=Q'*H(J,:);
U(:,J)=U(:,J)*Q;
Q=U(:,1:i-1); U=U(:,i:j);
return
%----------------------------------------------------------------------
function [Q,M]=RestoreHess(M)
[j1,j2]=size(M); Q=eye(j2);
for j=j1:-1:2
J=1:j-1;
q=M(j,J)'; q=q/norm(q);
q(j-1,1)=q(j-1,1)+sign(q(j-1,1));
q=q/norm(q);
M(:,J)=M(:,J)-2*(M(:,J)*q)*q';
M(J,:)=M(J,:)-2*q*q'*M(J,:);
Q(:,J)=Q(:,J)-2*Q(:,J)*q*q';
end
return
%%%=========== END ARNOLDI ============================================
function [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,Rv);
% V,W orthonormal, A*V-tau*V=W*R+Qschur'*E
global Qschur Rschur
k=size(Rschur,1); j=size(V,2);
[W,R]=qr(W,0); E=E/Rv; R=R/Rv; M=W'*V;
%%% not accurate enough M=Rw'\(M/Rv);
if k>=nselect, return, end
CHECK=1; l=k;
[S,T,Z,Q]=qz(R,M); Z=Z';
while CHECK
I=SortEigPairVar(S,T,2); [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1));
s=abs(S(1,1)); t=min(abs(T(1,1)),1); CHECK=(s*sqrt(1-t*t)<tol);
if CHECK
V=V*Q; W=W*Z; E=E*Q;
u=V(:,1); [r,a]=RepGS(u,(W(:,1)-T(1,1)'*u)*S(1,1),0);
Qschur=[Qschur,u]; t=(T(1,1)'-a/S(1,1))*S(1,:);
Rschur=[Rschur,E(:,1);zeros(1,k),tau+t(1,1)]; k=k+1;
J=[2:j]; j=j-1;
V=V(:,J); W=W(:,J); E=[E(:,J);t(1,J)]; s=S(1,J)/S(1,1);
R=S(J,J); M=T(J,J); Q=eye(j); Z=eye(j);
s=s/R; nrs=norm(r)*norm(s);
if nrs>=tol,
W=W+r*s; M=M+s'*(r'*V);
if nrs^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end
end
S=R; T=M;
CHECK=(k<nselect & j>0);
end
end
return
%===========================================================================
%======= POSTPROCESSING ====================================================
%===========================================================================
function Refine(V,gamma);
if gamma==0, return, end
global Qschur Rschur
J=1:size(Rschur,1);
if gamma==1,
[V,R]=qr(V(:,J),0); W=MV(V); M=V'*W;
[U,Rschur]=schur(M);
[U,Rschur]=rsf2csf(U,Rschur); Qschur=V*U;
return
elseif gamma==2
[V,R]=qr(V,0); W=MV(V); M=V'*W;
[U,S]=schur(M); [U,S]=rsf2csf(U,S);
R=R*U; F=R'*R-S'*S;
[X,Lambda]=Jordan(S);
% Xinv=inv(X); D=sqrt(diag(Xinv*Xinv')); X=X*diag(D);
[d,I]=sort(abs(diag(X'*F*X)));
[U,S]=SwapSchur(U,S,I(J));
Qschur=V*U(:,J); Rschur=S(J,J);
end
return
%===========================================================================
function CheckSortSchur(sigma)
global Qschur Rschur
k=size(Rschur,1); if k==0, return, end
I=SortEig(diag(Rschur),sigma);
if ~min((1:k)'==I)
[U,Rschur]=SwapSchur(eye(k),Rschur,I);
Qschur=Qschur*U;
end
return
%%%=========== COMPUTE SORTED JORDAN FORM ==================================
function [X,Jordan]=Jordan(S)
% [X,J]=JORDAN(S)
% For S k by k upper triangular matrix with ordered diagonal elements,
% JORDAN computes the Jordan decomposition.
% X is a k by k matrix of vectors spanning invariant spaces.
% If J(i,i)=J(i+1,i+1) then X(:,i)'*X(:,i+1)=0.
% J is a k by k matrix, J is Jordan such that S*X=X*J.
% diag(J)=diag(S) are the eigenvalues
% coded by Gerard Sleijpen, Januari 14, 1998
k=size(S,1); X=zeros(k);
if k==0, Jordan=[]; return, end
%%% accepted separation between eigenvalues:
delta=2*sqrt(eps)*norm(S,inf); delta=max(delta,10*eps);
T=eye(k); s=diag(S); Jordan=diag(s);
for i=1:k
I=[1:i]; e=zeros(i,1); e(i,1)=1;
C=S(I,I)-s(i,1)*T(I,I); C(i,i)=1;
j=i-1; q=[]; jj=0;
while j>0
if abs(C(j,j))<delta, jj=jj+1; j=j-1; else, j=0; end
end
q=X(I,i-jj:i-1);
C=[C,T(I,I)*q;q',zeros(jj)];
q=C\[e;zeros(jj,1)]; nrm=norm(q(I,1));
Jordan(i-jj:i-1,i)=-q(i+1:i+jj,1)/nrm;
X(I,i)=q(I,1)/nrm;
end
return
%========== OUTPUT =========================================================
function varargout=output(history,X,Lambda)
global Qschur Rschur
if nargout == 1, varargout{1}=diag(Rschur); return, end
if nargout > 2, varargout{nargout}=history; end
if nargout > 3, varargout{3} = Qschur; varargout{4} = Rschur; end
if nargout < 4 & size(X,2)<2
varargout{1}=Qschur; varargout{2}=Rschur; return
else
varargout{1}=X; varargout{2}=Lambda;
end
return
%===========================================================================
%===== UPDATE PRECONDITIONED SCHUR VECTORS =================================
%===========================================================================
function solved=UpdateMinv(u,solved)
global Qschur PinvQ Pinv_u Pu L_precond
if ~isempty(L_precond)
if ~solved, Pinv_u=SolvePrecond(u); end
Pu=[[Pu;u'*PinvQ],Qschur'*Pinv_u];
PinvQ=[PinvQ,Pinv_u];
solved=0;
end
return
%===========================================================================
%===== SOLVE CORRECTION EQUATION ===========================================
%===========================================================================
function t=Solve_pce(theta,u,r,lsolver,par,nit)
global Qschur PinvQ Pinv_u Pu L_precond
switch lsolver
case 'exact'
t = exact(theta,[Qschur,u],r);
case 'iluexact'
t = iluexact(theta,[Qschur,u],r);
case {'gmres','bicgstab','olsen'}
if isempty(L_precond) %%% no preconditioning
t = feval(lsolver,theta,...
[Qschur,u],[Qschur,u],1,r,spar(par,nit));
else %%% solve left preconditioned system
%%% compute vectors and matrices for skew projection
Pinv_u=SolvePrecond(u);
mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u];
%%% precondion and project r
r=SolvePrecond(r);
r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r);
%%% solve preconditioned system
t = feval(lsolver,theta,...
[Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit));
end
case {'cg','minres','symmlq'}
if isempty(L_precond) %%% no preconditioning
t = feval(lsolver,theta,...
[Qschur,u],[Qschur,u],1,r,spar(par,nit));
else %%% solve two-sided expl. precond. system
%%% compute vectors and matrices for skew projection
Pinv_u=SolvePrecond(u,'L');
mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u];
%%% precondion and project r
r=SolvePrecond(r,'L');
r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r);
%%% solve preconditioned system
t = feval(lsolver,theta,...
[Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit));
%%% "unprecondition" solution
t=SkewProj([PinvQ,Pinv_u],[Qschur,u],mu,t);
t=SolvePrecond(t,'U');
end
end
return
%=======================================================================
%======= LINEAR SOLVERS ================================================
%=======================================================================
function x = exact(theta,Q,r)
global A_operator
[n,k]=size(Q); [n,l]=size(r);
if ischar(A_operator)
[x,xtol]=bicgstab(theta,Q,Q,1,r,[5.0e-14/norm(r),200,4]);
return
end
x = [A_operator-theta*speye(n,n),Q;Q',zeros(k,k)]\[r;zeros(k,l)];
x = x(1:n,1:l);
return
%----------------------------------------------------------------------
function x = iluexact(theta,Q,r)
global L_precond U_precond
[n,k]=size(Q); [n,l]=size(r);
y = L_precond\[r,Q];
x = [U_precond,y(:,l+1:k+1);Q',zeros(k,k)]\[y(:,1:l);zeros(k,l)];
x = x(1:n,1:l);
return
%----------------------------------------------------------------------
function r = olsen(theta,Q,Z,M,r,par)
return
%
%======= Iterative methods =============================================
%
function x = bicgstab(theta,Q,Z,M,r,par)
% BiCGstab(ell)
% [x,rnrm] = bicgstab(theta,Q,Z,M,r,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=r
% where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)).
%
% This function is specialized for use in JDQZ.
% integer nmv: number of matrix multiplications
% rnrm: relative residual norm
%
% par=[tol,mxmv,ell] where
% integer m: max number of iteration steps
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: ETNA
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization --
%
tol=par(1); max_it=par(2); l=par(3); n=size(r,1);
rnrm=1; nmv=0;
if max_it==0 | tol>=1, x=r; return, end
rnrm=norm(r); snrm=rnrm; tol=tol*rnrm;
sigma=1; omega=1;
x=zeros(n,1); u=zeros(n,1); tr=r;
% hist=rnrm;
% -- Iteration loop
while (rnrm > tol) & (nmv <= max_it)
sigma=-omega*sigma;
for j = 1:l,
rho=tr'*r(:,j); bet=rho/sigma;
u=r-bet*u;
%%%%%% u(:,j+1)=Atilde*u(:,j)
u(:,j+1)=mvp(theta,Q,Z,M,u(:,j));
sigma=tr'*u(:,j+1); alp=rho/sigma;
x=x+alp*u(:,1);
r=r-alp*u(:,2:j+1);
%%%%%% r(:,j+1)=Atilde*r(:,j)
r(:,j+1)=mvp(theta,Q,Z,M,r(:,j));
end
gamma=r(:,2:l+1)\r(:,1); omega=gamma(l,1);
x=x+r*[gamma;0]; u=u*[1;-gamma]; r=r*[1;-gamma];
rnrm = norm(r); nmv = nmv+2*l;
% hist=[hist,rnrm];
end
% figure(3),
% plot([0:length(hist)-1]*2*l,log10(hist/snrm),'-*'),
% drawnow,
rnrm = rnrm/snrm;
return
%----------------------------------------------------------------------
function v = gmres(theta,Q,Z,M,v,par)
% GMRES
% [x,rnrm] = gmres(theta,Q,Z,M,b,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=b
% where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)).
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: Saad
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization
tol=par(1); n = size(v,1); max_it=min(par(2),n);
rnrm = 1; nmv=0;
if max_it==0 | tol>=1, return, end
H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)];
rnrm = norm(v); v = v/rnrm; V = [v];
tol = tol * rnrm; snrm = rnrm;
y = [ rnrm ; zeros(max_it,1) ];
j=0; % hist=rnrm;
while (nmv < max_it) & (rnrm > tol),
j=j+1; nmv=nmv+1;
v=mvp(theta,Q,Z,M,v);
% [v, H(1:j+1,j)] = RepGS(V,v);
[v,h] = RepGS(V,v); H(1:size(h,1),j)=h;
V = [V, v];
for i = 1:j-1,
a = Rot(:,i);
H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j);
end
J=[j, j+1];
a=H(J,j);
if a(2) ~= 0
cs = norm(a);
a = a/cs; Rot(:,j) = a;
H(J,j) = [cs; 0];
y(J) = [a'; -a(2) a(1)]*y(J);
end
rnrm = abs(y(j+1));
% hist=[hist,rnrm];
end
% figure(3)
% plot([0:length(hist)-1],log10(hist/snrm),'-*')
% drawnow, pause
J=[1:j];
v = V(:,J)*(H(J,J)\y(J));
rnrm = rnrm/snrm;
return
%======================================================================
%========== BASIC OPERATIONS ==========================================
%======================================================================
function v=MV(v)
global A_operator nm_operations
if ischar(A_operator)
v = feval(A_operator,v);
else
v = A_operator*v;
end
nm_operations = nm_operations+1;
return
%----------------------------------------------------------------------
function v=mvp(theta,Q,Z,M,v)
% v=Atilde*v
v = MV(v) - theta*v;
v = SolvePrecond(v);
v = SkewProj(Q,Z,M,v);
return
%----------------------------------------------------------------------
function u=SolvePrecond(u,flag);
global L_precond U_precond
if isempty(L_precond), return, end
if nargin<2
if ischar(L_precond)
if ischar(U_precond)
u=feval(L_precond,u,U_precond);
elseif isempty(U_precond)
u=feval(L_precond,u);
else
u=feval(L_precond,u,'L'); u=feval(L_precond,u,'U');
end
else
u=U_precond\(L_precond\u);
end
else
switch flag
case 'U'
if ischar(L_precond), u=feval(L_precond,u,'U'); else, u=U_precond\u; end
case 'L'
if ischar(L_precond), u=feval(L_precond,u,'L'); else, u=L_precond\u; end
end
end
return
%----------------------------------------------------------------------
function r=SkewProj(Q,Z,M,r);
if ~isempty(Q),
r=r-Z*(M\(Q'*r));
end
return
%----------------------------------------------------------------------
function ppar=spar(par,nit)
% Changes par=[tol(:),max_it,ell] to
% ppap=[TOL,max_it,ell] where
% if lenght(tol)==1
% TOL=tol
% else
% red=tol(end)/told(end-1); tole=tol(end);
% tol=[tol,red*tole,red^2*tole,red^3*tole,...]
% TOL=tol(nit);
% end
k=size(par,2)-2;
ppar=par(1,k:k+2);
if k>1
if nit>k
ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k));
else
ppar(1,1)=par(1,max(nit,1));
end
end
ppar(1,1)=max(ppar(1,1),1.0e-8);
return
%
%======= Iterative methods for symmetric systems =======================
%
function x = cg(theta,Q,Z,M,r,par)
% CG
% [x,rnrm] = cg(theta,Q,Z,M,b,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=b
% where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)).
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: Hestenes and Stiefel
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization
tol=par(1); max_it=par(2); n = size(r,1);
rnrm = 1; nmv=0;
b=r;
if max_it ==0 | tol>=1, x=r; return, end
x= zeros(n,1); u=zeros(n,1);
rho = norm(r); snrm = rho; rho = rho*rho;
tol = tol*tol*rho;
sigma=1;
while ( rho > tol & nmv < max_it )
beta=rho/sigma;
u=r-beta*u;
y=smvp(theta,Q,Z,M,u); nmv=nmv+1;
sigma=y'*r; alpha=rho/sigma;
x=x+alpha*u;
r=r-alpha*y; sigma=-rho; rho=r'*r;
end % while
rnrm=sqrt(rho)/snrm;
return
%----------------------------------------------------------------------
function x = minres(theta,Q,Z,M,r,par)
% MINRES
% [x,rnrm] = minres(theta,Q,Z,M,b,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=b
% where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)).
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: Paige and Saunders
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization
tol=par(1); max_it=par(2); n = size(r,1);
rnrm = 1; nmv=0;
if max_it ==0 | tol>=1, x=r; return, end
x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho;
beta = 0; v_old = zeros(n,1);
beta_t = 0; c = -1; s = 0;
w = zeros(n,1); www = v;
tol=tol*rho;
while ( nmv < max_it & abs(rho) > tol )
wv =smvp(theta,Q,Z,M,v)-beta*v_old; nmv=nmv+1;
alpha = v'*wv; wv = wv-alpha*v;
beta = norm(wv); v_old = v; v = wv/beta;
l1 = s*alpha - c*beta_t; l2 = s*beta;
alpha_t = -s*beta_t - c*alpha; beta_t = c*beta;
l0 = sqrt(alpha_t*alpha_t+beta*beta);
c = alpha_t/l0; s = beta/l0;
ww = www - l1*w; www = v - l2*w; w = ww/l0;
x = x + (rho*c)*w; rho = s*rho;
end % while
rnrm=abs(rho)/snrm;
return
%----------------------------------------------------------------------
function x = symmlq(theta,Q,Z,M,r,par)
% SYMMLQ
% [x,rnrm] = symmlq(theta,Q,Z,M,b,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=b
% where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)).
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: Paige and Saunders
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization
tol=par(1); max_it=par(2); n = size(r,1);
rnrm = 1; nmv=0;
if max_it ==0 | tol>=1, x=r; return, end
x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho;
beta = 0; beta_t = 0; c = -1; s = 0;
v_old = zeros(n,1); w = v; gtt = rho; g = 0;
tol=tol*rho;
while ( nmv < max_it & rho > tol )
wv = smvp(theta,Q,Z,M,v) - beta*v_old; nmv=nmv+1;
alpha = v'*wv; wv = wv - alpha*v;
beta = norm(wv); v_old = v; v = wv/beta;
l1 = s*alpha - c*beta_t; l2 = s*beta;
alpha_t = -s*beta_t - c*alpha; beta_t = c*beta;
l0 = sqrt(alpha_t*alpha_t+beta*beta);
c = alpha_t/l0; s = beta/l0;
gt = gtt - l1*g; gtt = -l2*g; g = gt/l0;
rho = sqrt(gt*gt+gtt*gtt);
x = x + (g*c)*w + (g*s)*v;
w = s*w - c*v;
end % while
rnrm=rho/snrm;
return
%----------------------------------------------------------------------
function v=smvp(theta,Q,Z,M,v)
% v=Atilde*v
v = SkewProj(Z,Q,M,v);
v = SolvePrecond(v,'U');
v = MV(v) - theta*v;
v = SolvePrecond(v,'L');
v = SkewProj(Q,Z,M,v);
return
%=======================================================================
%========== Orthogonalisation ==========================================
%=======================================================================
function [v,y]=RepGS(V,v,gamma)
% [v,y]=REP_GS(V,w)
% If V orthonormal then [V,v] orthonormal and w=[V,v]*y;
% If size(V,2)=size(V,1) then w=V*y;
%
% The orthonormalisation uses repeated Gram-Schmidt
% with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion.
%
% [v,y]=REP_GS(V,w,GAMMA)
% GAMMA=1 (default) same as [v,y]=REP_GS(V,w)
% GAMMA=0, V'*v=zeros(size(V,2)) and w = V*y+v (v is not normalized).
% coded by Gerard Sleijpen, August 28, 1998
if nargin < 3, gamma=1; end
[n,d]=size(V);
if size(v,2)==0, y=zeros(d,0); return, end
nr_o=norm(v); nr=eps*nr_o; y=zeros(d,1);
if d==0
if gamma, v=v/nr_o; y=nr_o; else, y=zeros(0,1); end, return
end
y=V'*v; v=v-V*y; nr_n=norm(v); ort=0;
while (nr_n<0.5*nr_o & nr_n > nr)
s=V'*v; v=v-V*s; y=y+s;
nr_o=nr_n; nr_n=norm(v); ort=ort+1;
end
if nr_n <= nr, if ort>2, disp(' dependence! '), end
if gamma % and size allows, expand with a random vector
if d<n, v=RepGS(V,rand(n,1)); y=[y;0]; else, v=zeros(n,0); end
else, v=0*v; end
elseif gamma, v=v/nr_n; y=[y;nr_n]; end
return
%=======================================================================
%============== Sorts Schur form =======================================
%=======================================================================
function [Q,S]=SortSchur(A,sigma,gamma,kk)
%[Q,S]=SortSchur(A,sigma)
% A*Q=Q*S with diag(S) in order prescribed by sigma.
% If sigma is a scalar then with increasing distance from sigma.
% If sigma is string then according to string
% ('LM' with decreasing modulus, etc)
%
%[Q,S]=SortSchur(A,sigma,gamma,kk)
% if gamma==0, sorts only for the leading element
% else, sorts for the kk leading elements
l=size(A,1);
if l<2, Q=1;S=A; return,
elseif nargin==2, kk=l-1;
elseif gamma, kk=min(kk,l-1);
else, kk=1; sigma=sigma(1,:); end
%%%------ compute schur form -------------
[Q,S]=schur(A); %% A*Q=Q*S, Q'*Q=eye(size(A));
%%% transform real schur form to complex schur form
if norm(tril(S,-1),1)>0, [Q,S]=rsf2csf(Q,S); end
%%%------ find order eigenvalues ---------------
I = SortEig(diag(S),sigma);
%%%------ reorder schur form ----------------
[Q,S] = SwapSchur(Q,S,I(1:kk));
return
%----------------------------------------------------------------------
function I=SortEig(t,sigma);
%I=SortEig(T,SIGMA) sorts the indices of T.
%
% T is a vector of scalars,
% SIGMA is a string or a vector of scalars.
% I is a permutation of (1:LENGTH(T))' such that:
% if SIGMA is a vector of scalars then
% for K=1,2,...,LENGTH(T) with KK = MIN(K,SIZE(SIGMA,1))
% ABS( T(I(K))-SIGMA(KK) ) <= ABS( T(I(J))-SIGMA(KK) )
% SIGMA(kk)=INF: ABS( T(I(K)) ) >= ABS( T(I(J)) )
% for all J >= K
if ischar(sigma)
switch sigma
case 'LM'
[s,I]=sort(-abs(t));
case 'SM'
[s,I]=sort(abs(t));
case 'LR';
[s,I]=sort(-real(t));
case 'SR';
[s,I]=sort(real(t));
case 'BE';
[s,I]=sort(real(t)); I=twistdim(I,1);
end
else
[s,I]=sort(abs(t-sigma(1,1)));
ll=min(size(sigma,1),size(t,1)-1);
for j=2:ll
if sigma(j,1)==inf
[s,J]=sort(abs(t(I(j:end)))); J=flipdim(J,1);
else
[s,J]=sort(abs(t(I(j:end))-sigma(j,1)));
end
I=[I(1:j-1);I(J+j-1)];
end
end
return
%----------------------------------------------------------------------
function t=twistdim(t,k)
d=size(t,k); J=1:d; J0=zeros(1,2*d);
J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J);
if k==1, t=t(I,:); else, t=t(:,I); end
return
%----------------------------------------------------------------------
function [Q,S]=SwapSchur(Q,S,I)
% [Q,S]=SwapSchur(QQ,SS,P)
% QQ and SS are square matrices of size K by K
% P is the first part of a permutation of (1:K)'.
%
% If M = QQ*SS*QQ' and QQ'*QQ = EYE(K), SS upper triangular
% then M*Q = Q*S with Q'*Q = EYE(K), S upper triangular
% and D(1:LENGTH(P))=DD(P) where D=diag(S), DD=diag(SS)
%
% Computations uses Givens rotations.
kk=min(length(I),size(S,1)-1);
j=1; while (j<=kk & j==I(j)), j=j+1; end;
while j<=kk
i=I(j);
for k=i-1:-1:j
q = [S(k,k)-S(k+1,k+1),S(k,k+1)];
if q(1) ~= 0
q = q/norm(q);
G = [[q(2);-q(1)],q'];
J = [k,k+1];
Q(:,J) = Q(:,J)*G;
S(:,J) = S(:,J)*G;
S(J,:) = G'*S(J,:);
end
S(k+1,k) = 0;
end
I=I+(I<i);
j=j+1; while (j<=kk & j==I(j)), j=j+1; end
end
return
%----------------------------------------------------------------------
function [Q,Z,S,T]=SortQZ(A,B,sigma,gamma,kk)
%
% [Q,Z,S,T]=SORTQZ(A,B,SIGMA)
% A and B are K by K matrices, SIGMA is a complex scalar or string.
% SORTQZ computes the qz-decomposition of (A,B) with prescribed
% ordering: A*Q=Z*S, B*Q=Z*T;
% Q and Z are K by K unitary,
% S and T are K by K upper triangular.
% The ordering is as follows:
% (DAIG(S),DAIG(T)) are the eigenpairs of (A,B) ordered
% as prescribed by SIGMA.
%
% coded by Gerard Sleijpen, version Januari 12, 1998
l=size(A,1);
if l<2; Q=1; Z=1; S=A; T=B; return
elseif nargin==3, kk=l-1;
elseif gamma, kk=min(kk,l-1);
else, kk=1; sigma=sigma(1,:); end
%%%------ compute qz form ----------------
[S,T,Z,Q]=qz(A,B); Z=Z'; S=triu(S);
%%%------ sort eigenvalues ---------------
I=SortEigPair(diag(S),diag(T),sigma);
%%%------ sort qz form -------------------
[Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk));
return
%----------------------------------------------------------------------
function I=SortEigPair(s,t,sigma)
% I=SortEigPair(S,T,SIGMA)
% S is a complex K-vectors, T a positive real K-vector
% SIGMA is a string or a vector of pairs of complex scalars.
% SortEigPair gives the index set I that sorts the pairs (S,T).
%
% If SIGMA is a pair of scalars then the sorting is
% with increasing "chordal distance" w.r.t. SIGMA.
%
% The chordal distance D between a pair A and a pair B is defined as follows.
% Scale A by a scalar F such that NORM(F*A)=1 and F*A(2)>=0,
% scale B by a scalar G such that NORM(G*B)=1 and G*B(2)>=0,
% then D(A,B)=ABS((F*A)*RROT(G*B)) where RROT(alpha,beta)=(beta,-alpha)
% coded by Gerard Sleijpen, version Januari 14, 1998
n=sign(t); n=n+(n==0); t=abs(t./n); s=s./n;
if ischar(sigma)
switch sigma
case {'LM','SM'}
case {'LR','SR','BE'}
s=real(s);
end
[s,I]=sort((-t./sqrt(s.*conj(s)+t.*t)));
switch sigma
case {'LM','LR'}
I=flipdim(I,1);
case {'SM','SR'}
case 'BE'
I=twistdim(I,1);
end
else
n=sqrt(sigma.*conj(sigma)+1); ll=size(sigma,1);
tau=[ones(ll,1)./n,-sigma./n]; tau=tau.';
n=sqrt(s.*conj(s)+t.*t); s=[s./n,t./n];
[t,I]=sort(abs(s*tau(:,1)));
ll = min(ll,size(I,1)-1);
for j=2:ll
[t,J]=sort(abs(s(I(j:end),:)*tau(:,j)));
I=[I(1:j-1);I(J+j-1)];
end
end
return
%----------------------------------------------------------------------
function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I)
% [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P)
% QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular.
% P is the first part of a permutation of (1:K)'.
%
% Then Q and Z are K by K unitary, S and T are K by K upper triangular,
% such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have
% A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where
% LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT).
%
% Computation uses Givens rotations.
%
% coded by Gerard Sleijpen, version October 12, 1998
kk=min(length(I),size(S,1)-1);
j=1; while (j<=kk & j==I(j)), j=j+1; end
while j<=kk
i=I(j);
for k = i-1:-1:j,
%%% i>j, move ith eigenvalue to position j
J = [k,k+1];
q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J);
if q(1) ~= 0
q = q/norm(q);
G = [[q(2);-q(1)],q'];
Q(:,J) = Q(:,J)*G;
S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G;
end
if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end
if q(2) ~= 0
q=q/norm(q);
G = [q';q(2),-q(1)];
Z(:,J) = Z(:,J)*G';
S(J,:) = G*S(J,:); T(J,:) = G*T(J,:);
end
T(k+1,k) = 0;
S(k+1,k) = 0;
end
I=I+(I<i);
j=j+1; while (j<=kk & j==I(j)), j=j+1; end
end
return
%=======================================================================
%======= SET PARAMETERS ================================================
%=======================================================================
function [n,nselect,sigma,SCHUR,...
jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV,OLD,...
lsolver,par] = ReadOptions(varargin)
% Read options and set defaults
global A_operator L_precond U_precond
A_operator = varargin{1};
%%% determine dimension
if ischar(A_operator)
n=-1;
if exist(A_operator) ~=2
msg=sprintf(' Can not find the M-file ''%s.m'' ',A_operator);
errordlg(msg,'MATRIX'),n=-2;
end
if n==-1, eval('n=feval(A_operator,[],''dimension'');','n=-1;'), end
else
[n,n] = size(A_operator);
if any(size(A_operator) ~= n)
msg=sprintf(' The operator must be a square matrix or a string. ');
errordlg(msg,'MATRIX'),n=-3;
end
end
%%% defaults
SCHUR = 0;
jmin = -1;
jmax = -1;
p0 = 5; % jmin=nselect+p0
p1 = 5; % jmax=jmin+p1
tol = 1e-8;
maxit = 200;
V = zeros(0,0);
INTERIOR= 0;
SHOW = 0;
PAIRS = 0;
JDV = 0;
OLD = 1e-4;
lsolver = 'gmres';
ls_maxit= 200;
ls_tol = [1,0.7];
ell = 4;
par = [ls_tol,ls_maxit,ell];
options=[]; sigma=[]; varg=[]; L_precond = []; U_precond = [];
for j = 2:nargin
if isstruct(varargin{j})
options = varargin{j};
elseif ischar(varargin{j})
if length(varargin{j}) == 2 & isempty(sigma)
sigma = varargin{j};
elseif isempty(L_precond)
L_precond=varargin{j};
elseif isempty(U_precond)
U_precond=varargin{j};
end
elseif length(varargin{j}) == 1
varg = [varg,varargin{j}];
elseif min(size(varargin{j}))==1
sigma = varargin{j}; if size(sigma,1)==1, sigma=conj(sigma'); end
elseif isempty(L_precond)
L_precond=varargin{j};
elseif isempty(U_precond)
U_precond=varargin{j};
end
end
if ischar(sigma)
sigma0=sigma; sigma=upper(sigma);
switch sigma
case {'LM','LR','SR','BE','SM'}
otherwise
if exist(sigma0)==2 & isempty(L_precond)
ok=1; eval('v=feval(sigma,zeros(n,1));','ok=0')
if ok, L_precond=sigma0; sigma=[]; end
end
end
end
[s,I]=sort(varg); I=flipdim(I,2);
J=[]; j=0;
while j<length(varg)
j=j+1; jj=I(j); s=varg(jj);
if isreal(s) & (s == fix(s)) & (s > 0)
if n==-1
n=s; eval('v=feval(A_operator,zeros(n,0));','n=-1;')
if n>-1, J=[J,jj]; end
end
else
if isempty(sigma), sigma=s;
elseif ischar(sigma) & isempty(L_precond)
ok=1; eval('v=feval(sigma0,zeros(n,1));','ok=0')
if ok, L_precond=sigma0; sigma=s; end
end, J=[J,jj];
end
end
varg(J)=[];
if n==-1,
msg1=sprintf(' Cannot find the dimension of ''%s''. \n',A_operator);
msg2=sprintf(' Put the dimension n in the parameter list: \n like');
msg3=sprintf('\t\n\n\t jdqr(''%s'',n,..), \n\n',A_operator);
msg4=sprintf(' or let\n\n\t n = %s(',A_operator);
msg5=sprintf('[],''dimension'')\n\n give n.');
msg=[msg1,msg2,msg3,msg4,msg5];
errordlg(msg,'MATRIX')
end
nselect=[];
if n<2, return, end
if length(varg) == 1
nselect=min(n,varg);
elseif length(varg)>1
if isempty(sigma), sigma=varg(end); varg(end)=[]; end
nselect=min(n,min(varg));
end
fopts = []; if ~isempty(options), fopts=fields(options); end
if isempty(L_precond)
if strmatch('Precond',fopts)
L_precond = options.Precond;
elseif strmatch('L_Precond',fopts)
L_precond = options.L_Precond;
end
end
if isempty(U_precond) & strmatch('U_Precond',fopts)
U_precond = options.U_Precond;
end
if isempty(L_precond), ls_tol = [0.7,0.49]; end
if ~isempty(L_precond) & ischar(L_precond)
if exist(L_precond) ~=2
msg=sprintf(' Can not find the M-file ''%s.m'' ',L_precond); n=-1;
elseif ~isempty(U_precond) & ~ischar(U_precond) & n>0
msg=sprintf(' L and U should both be strings or matrices'); n=-1;
elseif strcmp(L_precond,U_precond)
eval('v=feval(L_precond,zeros(n,1),''L'');','n=-1;')
eval('v=feval(L_precond,zeros(n,1),''U'');','n=-1;')
if n<0
msg='L and U use the same M-file';
msg1=sprintf(' %s.m \n',L_precond);
msg2='Therefore L and U are called';
msg3=sprintf(' as\n\n\tw=%s(v,''L'')',L_precond);
msg4=sprintf(' \n\tw=%s(v,''U'')\n\n',L_precond);
msg5=sprintf('Check the dimensions and/or\n');
msg6=sprintf('put this "switch" in %s.m.',L_precond);
msg=[msg,msg1,msg2,msg3,msg4,msg5,msg6];
else
U_precond=0;
end
elseif ischar(A_operator) & strcmp(A_operator,L_precond)
U_precond='preconditioner';
eval('v=feval(L_precond,zeros(n,1),U_precond);','n=-1;')
if n<0
msg='Preconditioner and matrix use the same M-file';
msg1=sprintf(' %s. \n',L_precond);
msg2='Therefore the preconditioner is called';
msg3=sprintf(' as\n\n\tw=%s(v,''preconditioner'')\n\n',L_precond);
msg4='Put this "switch" in the M-file.';
msg=[msg,msg1,msg2,msg3,msg4];
end
else
eval('v=feval(L_precond,zeros(n,1));','n=-1')
if n<0
msg=sprintf('''%s'' should produce %i-vectors',L_precond,n);
end
end
end
Ud=1;
if ~isempty(L_precond) & ~ischar(L_precond) & n>0
if ~isempty(U_precond) & ischar(U_precond)
msg=sprintf(' L and U should both be strings or matrices'); n=-1;
elseif ~isempty(U_precond)
if ~min([n,n]==size(L_precond) & [n,n]==size(U_precond))
msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1;
end
elseif min([n,n]==size(L_precond))
U_precond=speye(n); Ud=0;
elseif min([n,2*n]==size(L_precond))
U_precond=L_precond(:,n+1:2*n); L_precond=L_precond(:,1:n);
else
msg=sprintf('The preconditioning matrix\n');
msg2=sprintf('should be %iX%i or %ix%i ([L,U]).\n',n,n,n,2*n);
msg=[msg,msg2]; n=-1;
end
end
if n<0, errordlg(msg,'PRECONDITIONER'), return, end
ls_tol0=ls_tol;
if strmatch('Tol',fopts), tol = options.Tol; end
if isempty(nselect), nselect=min(n,5); end
if strmatch('jmin',fopts), jmin=min(n,options.jmin); end
if strmatch('jmax',fopts)
jmax=min(n,options.jmax);
if jmin<0, jmin=max(1,jmax-p1); end
else
if jmin<0, jmin=min(n,nselect+p0); end
jmax=min(n,jmin+p1);
end
if strmatch('MaxIt',fopts), maxit = abs(options.MaxIt); end
if strmatch('v0',fopts);
V = options.v0;
[m,d]=size(V);
if m~=n | d==0
if m>n, V = V(1:n,:); end
nrV=norm(V); if nrV>0, V=V/nrV; end
d=max(d,1);
V = [V; ones(n-m,d) +0.1*rand(n-m,d)];
end
else
V = ones(n,1) +0.1*rand(n,1); d=1;
end
if strmatch('TestSpace',fopts), INTERIOR = boolean(options.TestSpace,...
[INTERIOR,0,1,1.1,1.2],strvcat('standard','harmonic'));
end
if isempty(sigma)
if INTERIOR, sigma=0; else, sigma = 'LM'; end
elseif ischar(sigma)
switch sigma
case {'LM','LR','SR','BE'}
case {'SM'}
sigma=0;
otherwise
if INTERIOR, sigma=0; else, sigma='LM'; end
end
end
if strmatch('Schur',fopts), SCHUR = boolean(options.Schur,SCHUR); end
if strmatch('Disp',fopts), SHOW = boolean(options.Disp,[SHOW,2]); end
if strmatch('Pairs',fopts), PAIRS = boolean(options.Pairs,PAIRS); end
if strmatch('AvoidStag',fopts),JDV = boolean(options.AvoidStag,JDV); end
if strmatch('Track',fopts)
OLD = boolean(options.Track,[OLD,0,OLD,inf],strvcat('no','yes')); end
OLD=max(abs(OLD),10*tol);
if strmatch('LSolver',fopts), lsolver = lower(options.LSolver); end
switch lsolver
case {'exact'}
L_precond=[];
if ischar(A_operator)
msg=sprintf('The operator must be a matrix for ''exact''.');
msg=[msg,sprintf('\nDo you want to solve the correction equation')];
msg=[msg,sprintf('\naccurately with an iterative solver (BiCGstab)?')];
button=questdlg(msg,'Solving exactly','Yes','No','Yes');
if strcmp(button,'No'), n=-1; return, end
end
case {'iluexact'}
if ischar(L_precond)
msg=sprintf('The preconditioner must be matrices for ''iluexact''.');
errordlg(msg,'Solving with ''iluexact''')
n=-1; return
end
case {'olsen'}
case {'cg','minres','symmlq'}
ls_tol=1.0e-12;
case 'gmres'
ls_maxit=5;
case 'bicgstab'
ls_tol=1.0e-10;
otherwise
error(['Unknown method ''' lsolver '''.']);
end
if strmatch('LS_MaxIt',fopts), ls_maxit=abs(options.LS_MaxIt); end
if strmatch('LS_Tol',fopts), ls_tol=abs(options.LS_Tol); end
if strmatch('LS_ell',fopts), ell=round(abs(options.LS_ell)); end
par=[ls_tol,ls_maxit,ell];
if SHOW
fprintf('\n'),fprintf('PROBLEM\n')
if ischar(A_operator)
fprintf(' A: ''%s''\n',A_operator);
elseif issparse(A_operator)
fprintf(' A: [%ix%i sparse]\n',n,n);
else
fprintf(' A: [%ix%i double]\n',n,n);
end
fprintf(' dimension: %i\n',n);
fprintf(' nselect: %i\n\n',nselect);
fprintf('TARGET\n')
if ischar(sigma)
fprintf(' sigma: ''%s''',sigma)
else
Str=ShowLambda(sigma);
fprintf(' sigma: %s',Str)
end
fprintf('\n\n')
fprintf('OPTIONS\n');
fprintf(' Schur: %i\n',SCHUR);
fprintf(' Tol: %g\n',tol);
fprintf(' Disp: %i\n',SHOW);
fprintf(' jmin: %i\n',jmin);
fprintf(' jmax: %i\n',jmax);
fprintf(' MaxIt: %i\n',maxit);
fprintf(' v0: [%ix%i double]\n',size(V));
fprintf(' TestSpace: %g\n',INTERIOR);
fprintf(' Pairs: %i\n',PAIRS);
fprintf(' AvoidStag: %i\n',JDV);
fprintf(' Track: %g\n',OLD);
fprintf(' LSolver: ''%s''\n',lsolver);
switch lsolver
case {'exact','iluexact','olsen'}
case {'cg','minres','symmlq','gmres','bicgstab'}
if length(ls_tol)>1
fprintf(' LS_Tol: ['); fprintf(' %g',ls_tol); fprintf(' ]\n');
else
fprintf(' LS_Tol: %g\n',ls_tol);
end
fprintf(' LS_MaxIt: %i\n',ls_maxit);
end
if strcmp(lsolver,'bicgstab')
fprintf(' LS_ell: %i\n',ell);
end
if isempty(L_precond)
fprintf(' Precond: []\n');
else
StrL='Precond'; StrU='U precond'; Us='double'; Ls=Us; ok=0;
if issparse(L_precond), Ls='sparse'; end
if ~isempty(U_precond) & Ud, StrL='L precond'; ok=1;
if issparse(U_precond), Us='sparse'; end
end
if ischar(L_precond)
fprintf('%13s: ''%s''\n',StrL,L_precond);
if ok
if U_precond~=0 & ~strcmp(U_precond,'preconditioner')
fprintf('%13s: ''%s''\n',StrU,U_precond);
else
fprintf('%13s: ''%s''\n',StrU,L_precond);
end
end
else
fprintf('%13s: [%ix%i %s]\n',StrL,n,n,Ls);
if ok & Ud, fprintf('%13s: [%ix%i %s]\n',StrU,n,n,Us); end
end
end
fprintf('\n')
string1='%13s: ''%s'''; string2='\n\t %s';
switch INTERIOR
case 0
fprintf(string1,'TestSpace','Standard, W = V ')
fprintf(string2,'V W: V orthogonal')
fprintf(string2,'W=A*V')
case 1
fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')
fprintf(string2,'V W: V and W orthogonal')
fprintf(string2,'AV-Q*E=W*R where AV=A*V-sigma*V and E=Q''*AV')
case 1.1
fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')
fprintf(string2,'V W AV: V and W orthogonal')
fprintf(string2,'AV=A*V-sigma*V, AV-Q*Q''*AV=W*R')
case 1.2
fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V')
fprintf(string2,'V W: W orthogonal')
fprintf(string2,'W=AV-Q*E where AV=A*V-sigma*V and E=Q''*AV')
otherwise
fprintf(string1,'TestSpace','Experimental')
end % switch INTERIOR
fprintf('\n\n')
end % if SHOW
if ischar(sigma) & INTERIOR >=1
msg1=sprintf('\n The choice sigma = ''%s'' does not match',sigma);
msg2=sprintf('\n the search for INTERIOR eigenvalues.');
msg3=sprintf('\n Specify a numerical value for sigma');
msg4=sprintf(',\n for instance, a value that is ');
switch sigma
case {'LM'}
% sigma='SM';
msg5=sprintf('absolute large.\n');
msg4=[msg4,msg5];
case {'LR'}
% sigma='SP'; % smallest positive real
msg5=sprintf('positive large.\n');
msg4=[msg4,msg5];
case {'SR'}
% sigma='LN'; % largest negative real
msg5=sprintf('negative and absolute large.\n');
msg4=[msg4,msg5];
case {'BE'}
% sigma='AS'; % alternating smallest pos., largest neg
msg4=sprintf('.\n');
end
msg=[msg1,msg2,msg3,msg4];
msg5=sprintf(' Do you want to continue with sigma=0?');
msg=[msg,msg5];
button=questdlg(msg,'Finding Interior Eigenvalues','Yes','No','Yes');
if strcmp(button,'Yes'), sigma=0, else, n=-1; end
end
return
%-------------------------------------------------------------------
function x = boolean(x,gamma,string)
%Y = BOOLEAN(X,GAMMA,STRING)
% GAMMA(1) is the default.
% If GAMMA is not specified, GAMMA = 0.
% STRING is a matrix of accepted strings.
% If STRING is not specified STRING = ['no ';'yes']
% STRING(I,:) and GAMMA(I) are accepted expressions for X
% If X=GAMMA(I) then Y=X. If X=STRING(I,:), then Y=GAMMA(I+1).
% For other values of X, Y=GAMMA(1);
if nargin < 2, gamma=0; end
if nargin < 3, string=strvcat('no','yes'); gamma=[gamma,0,1]; end
if ischar(x)
i=strmatch(lower(x),string,'exact');
if isempty(i),i=1; else, i=i+1; end, x=gamma(i);
elseif max((gamma-x)==0)
elseif gamma(end) == inf
else, x=gamma(1);
end
return
%-------------------------------------------------------------------
function possibilities
fprintf('\n')
fprintf('PROBLEM\n')
fprintf(' A: [ square matrix | string ]\n');
fprintf(' nselect: [ positive integer {5} ]\n\n');
fprintf('TARGET\n')
fprintf(' sigma: [ scalar | vector of scalars |\n');
fprintf(' ''LM'' | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n');
fprintf('OPTIONS\n');
fprintf(' Schur: [ yes | {no} ]\n');
fprintf(' Tol: [ positive scalar {1e-8} ]\n');
fprintf(' Disp: [ yes | {no} | 2 ]\n');
fprintf(' jmin: [ positive integer {nselect+5} ]\n');
fprintf(' jmax: [ positive integer {jmin+5} ]\n');
fprintf(' MaxIt: [ positive integer {200} ]\n');
fprintf(' v0: [ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n');
fprintf(' TestSpace: [ Standard | {Harmonic} ]\n');
fprintf(' Pairs: [ yes | {no} ]\n');
fprintf(' AvoidStag: [ yes | {no} ]\n');
fprintf(' Track: [ {yes} | no | non-negative scalar {1e-4} ]\n');
fprintf(' LSolver: [ {gmres} | bicgstab ]\n');
fprintf(' LS_Tol: [ row of positive scalars {[1,0.7]} ]\n');
fprintf(' LS_MaxIt: [ positive integer {5} ]\n');
fprintf(' LS_ell: [ positive integer {4} ]\n');
fprintf(' Precond: [ n by 2n matrix | string {identity} ]\n');
fprintf('\n')
return
%===========================================================================
%============= OUTPUT FUNCTIONS ============================================
%===========================================================================
function varargout=ShowLambda(lambda,kk)
for k=1:size(lambda,1);
if k>1, Str=[Str,sprintf('\n%15s','')]; else, Str=[]; end
rlambda=real(lambda(k,1)); ilambda=imag(lambda(k,1));
Str=[Str,sprintf(' %+11.4e',rlambda)];
if abs(ilambda)>100*eps*abs(rlambda)
if ilambda>0
Str=[Str,sprintf(' + %10.4ei',ilambda)];
else
Str=[Str,sprintf(' - %10.4ei',-ilambda)];
end
end
end
if nargout == 0
if nargin == 2
Str=[sprintf('\nlambda(%i) =',kk),Str];
else
Str=[sprintf('\nDetected eigenvalues:\n\n%15s',''),Str];
end
fprintf('%s\n',Str)
else
varargout{1}=Str;
end
return
%===========================================================================
function DispResult(s,nr,gamma)
if nargin<3, gamma=0; end
extra='';
if nr > 100*eps & gamma
extra=' norm > 100*eps !!! ';
end
if gamma<2 | nr>100*eps
fprintf('\n %35s: %0.5g\t%s',s,nr,extra)
end
return
%===========================================================================
function STATUS0=MovieTheta(n,nit,Lambda,jmin,tau,LOCKED,SHRINK)
% MovieTheta(n,nit,Lambda,jmin,tau,nr<t_tol,j==jmax);
global A_operator Rschur EigMATLAB CIRCLE MovieAxis M_STATUS
f=256;
if nargin==0,
if ~isempty(CIRCLE)
%figure(f), buttons(f,-2); hold off, refresh
end
return
end
if nit==0
EigMATLAB=[];
if ~ischar(A_operator) & n<201
EigMATLAB=eig(full(A_operator));
end
CIRCLE=0:0.005:1; CIRCLE=exp(CIRCLE*2*pi*sqrt(-1));
if ischar(tau)
switch tau
case {'LR','SR'}
if ~ischar(A_operator)
CIRCLE=norm(A_operator,'inf')*[sqrt(-1),-sqrt(-1)]+1;
end
end
end
Explanation(~isempty(EigMATLAB),f-1)
end
%if gcf~=f, figure(f), end
jmin=min(jmin,length(Lambda));
%plot(real(Lambda(1:jmin)),imag(Lambda(1:jmin)),'bo');
if nit>0, axis(MovieAxis), end, hold on
pls='bo'; if SHRINK, pls='mo'; end
%plot(real(Lambda(jmin+1:end)),imag(Lambda(jmin+1:end)),pls)
%plot(real(EigMATLAB),imag(EigMATLAB),'cp');
THETA=diag(Rschur); %plot(real(THETA),imag(THETA),'k*');
x=real(Lambda(1)); y=imag(Lambda(1));
%plot(x,y,'kd'), pls='ks';
if LOCKED, plot(x,y,'ks'), pls='ms'; end
if ischar(tau), tau=0; end
delta=Lambda([1,jmin])-tau;
if length(CIRCLE)~=2, delta=abs(delta);
% plot(real(tau),imag(tau),pls)
else, delta=real(delta); end
for i=1:1+SHRINK,
zeta=delta(i)*CIRCLE+tau;
% plot(real(zeta),imag(zeta),'r:'),
end
if nit==0
buttons(f,-1); hold off, zoom on
end
title('legend see figure(255)')
if SHRINK, STATUS0=buttons(f,2); if STATUS0, return, end, end
STATUS0=buttons(f,1); drawnow, hold off
return
%=============================================================
function Explanation(E,f)
%if gcf~=f, figure(f), end
HL=plot(0,0,'kh',0,0,'bo'); hold on
StrL=str2mat('Detected eigenvalues','Approximate eigenvalues');
if E
HL=[HL;plot(0,0,'cp')];
StrL=str2mat(StrL,'Exact eigenvenvalues');
end
HL=[HL;plot(0,0,'kd',0,0,'ks',0,0,'r:')];
% StrL=str2mat(StrL,'Tracked app. eig.','target',...
% 'inner/outer bounds for restart');
StrL=str2mat(StrL,'Selected approximate eigenvalue','target',...
'inner/outer bounds for restart');
legend(HL,StrL), hold on, drawnow, hold off
title('legend for figure(256)')
return
%=============================================================
function STATUS0=buttons(f,push)
% push=0: do nothing
% push>0: check status buttons,
% STATUS0=1 if break else STATUS0=0.
% push=-1: make buttons for pause and break
% push=-2: remove buttons
global M_STATUS MovieAxis
if push>0 % check status buttons
ud = get(f,'UserData');
if ud.pause ==1, M_STATUS=1; end
if ud.break ==1, STATUS0=1;
ud.pause=0; ud.break=0; set(f,'UserData',ud); return,
else, STATUS0=0; end
if push>1
ud.pause=0; set(f,'UserData',ud);
while M_STATUS
ud = get(f,'UserData'); pause(0.1)
if ud.pause, M_STATUS=0; end
if ud.break, M_STATUS=0; STATUS0=1; end
MovieAxis=axis;
end
ud.pause=0; ud.break=0; set(f,'UserData',ud);
end
elseif push==0, STATUS0=0; return
elseif push==-1 % make buttons
ud = [];
h = findobj(f,'Tag','pause');
if isempty(h)
ud.pause = 0;
pos = get(0,'DefaultUicontrolPosition');
pos(1) = pos(1) - 15;
pos(2) = pos(2) - 15;
str = 'ud=get(gcf,''UserData''); ud.pause=1; set(gcf,''UserData'',ud);';
uicontrol( ...
'Style','push', ...
'String','Pause', ...
'Position',pos, ...
'Callback',str, ...
'Tag','pause');
else
set(h,'Visible','on'); % make sure it's visible
if ishold
oud = get(f,'UserData');
ud.pause = oud.pause; % don't change old ud.pause status
else
ud.pause = 0;
end
end
h = findobj(f,'Tag','break');
if isempty(h)
ud.break = 0;
pos = get(0,'DefaultUicontrolPosition');
pos(1) = pos(1) + 50;
pos(2) = pos(2) - 15;
str = 'ud=get(gcf,''UserData''); ud.break=1; set(gcf,''UserData'',ud);';
uicontrol( ...
'Style','push', ...
'String','Break', ...
'Position',pos, ...
'Callback',str, ...
'Tag','break');
else
set(h,'Visible','on'); % make sure it's visible
if ishold
oud = get(f,'UserData');
ud.break = oud.break; % don't change old ud.break status
else
ud.break = 0;
end
end
set(f,'UserData',ud); M_STATUS=0;
STATUS0=0; hold off, zoom on
MA=axis; nl=MA/10;
MovieAxis = MA-max(nl([2,4])-nl([1,3]))*[1,-1,1,-1];
else % remove buttons
set(findobj(f,'Tag','pause'),'Visible','off');
set(findobj(f,'Tag','break'),'Visible','off');
STATUS0=0; return, refresh
end
return
|
github
|
pvarin/DynamicVAE-master
|
lmnn.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/lmnn.m
| 5,431 |
utf_8
|
622ccdd8948f805d0d4552822cca46de
|
function [M, L, Y, C] = lmnn(X, labels)
%LMNN Learns a metric using large-margin nearest neighbor metric learning
%
% [M, L, Y, C] = lmnn(X, labels)
%
% The function uses large-margin nearest neighbor (LMNN) metric learning to
% learn a metric on the data set specified by the NxD matrix X and the
% corresponding Nx1 vector labels. The metric is returned in M.
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
% Initialize some variables
[N, D] = size(X);
assert(length(labels) == N);
[lablist, ~, labels] = unique(labels);
K = length(lablist);
label_matrix = false(N, K);
label_matrix(sub2ind(size(label_matrix), (1:length(labels))', labels)) = true;
same_label = logical(double(label_matrix) * double(label_matrix'));
M = eye(D);
C = Inf; prev_C = Inf;
% Set learning parameters
min_iter = 50; % minimum number of iterations
max_iter = 1000; % maximum number of iterations
eta = .1; % learning rate
mu = .5; % weighting of pull and push terms
tol = 1e-3; % tolerance for convergence
best_C = Inf; % best error obtained so far
best_M = M; % best metric found so far
no_targets = 3; % number of target neighbors
% Select target neighbors
sum_X = sum(X .^ 2, 2);
DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (X * X')));
DD(~same_label) = Inf; DD(1:N + 1:end) = Inf;
[~, targets_ind] = sort(DD, 2, 'ascend');
targets_ind = targets_ind(:,1:no_targets);
targets = false(N, N);
targets(sub2ind([N N], vec(repmat((1:N)', [1 no_targets])), vec(targets_ind))) = true;
% Compute pulling term between target neigbhors to initialize gradient
slack = zeros(N, N, no_targets);
G = zeros(D, D);
for i=1:no_targets
G = G + (1 - mu) .* (X - X(targets_ind(:,i),:))' * (X - X(targets_ind(:,i),:));
end
% Perform main learning iterations
iter = 0;
while (prev_C - C > tol || iter < min_iter) && iter < max_iter
% Compute pairwise distances under current metric
XM = X * M;
sum_X = sum(XM .* X, 2);
DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (XM * X')));
% Compute value of slack variables
old_slack = slack;
for i=1:no_targets
slack(:,:,i) = ~same_label .* max(0, bsxfun(@minus, 1 + DD(sub2ind([N N], (1:N)', targets_ind(:,i))), DD));
end
% Compute value of cost function
prev_C = C;
C = (1 - mu) .* sum(DD(targets)) + ... % push terms between target neighbors
mu .* sum(slack(:)); % pull terms between impostors
% Maintain best solution found so far (subgradient method)
if C < best_C
best_C = C;
best_M = M;
end
% Perform gradient update
for i=1:no_targets
% Add terms for new violations
[r, c] = find(slack(:,:,i) > 0 & old_slack(:,:,i) == 0);
G = G + mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ...
(X(r,:) - X(targets_ind(r, i),:)) - ...
(X(r,:) - X(c,:))' * (X(r,:) - X(c,:)));
% Remove terms for resolved violations
[r, c] = find(slack(:,:,i) == 0 & old_slack(:,:,i) > 0);
G = G - mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ...
(X(r,:) - X(targets_ind(r, i),:)) - ...
(X(r,:) - X(c,:))' * (X(r,:) - X(c,:)));
end
M = M - (eta ./ N) .* G;
% Project metric back onto the PSD cone
[V, L] = eig(M);
V = real(V); L = real(L);
ind = find(diag(L) > 0);
if isempty(ind)
warning('Projection onto PSD cone failed. All eigenvalues were negative.'); break
end
M = V(:,ind) * L(ind, ind) * V(:,ind)';
if any(isinf(M(:)))
warning('Projection onto PSD cone failed. Metric contains Inf values.'); break
end
if any(isnan(M(:)))
warning('Projection onto PSD cone failed. Metric contains NaN values.'); break
end
% Update learning rate
if prev_C > C
eta = eta * 1.01;
else
eta = eta * .5;
end
% Print out progress
iter = iter + 1;
no_slack = sum(slack(:) > 0);
if rem(iter, 10) == 0
[~, sort_ind] = sort(DD, 2, 'ascend');
disp(['Iteration ' num2str(iter) ': error is ' num2str(C ./ N) ...
', nearest neighbor error is ' num2str(sum(labels(sort_ind(:,2)) ~= labels) ./ N) ...
', number of constraints: ' num2str(no_slack)]);
end
end
% Return best metric and error
M = best_M;
C = best_C;
% Compute mapped data
[L, S, ~] = svd(M);
L = bsxfun(@times, sqrt(diag(S)), L);
Y = X * L;
end
function x = vec(x)
x = x(:);
end
|
github
|
pvarin/DynamicVAE-master
|
d2p.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/d2p.m
| 3,487 |
utf_8
|
0c7024a8039ea16b937d283585883fc3
|
function [P, beta] = d2p(D, u, tol)
%D2P Identifies appropriate sigma's to get kk NNs up to some tolerance
%
% [P, beta] = d2p(D, kk, tol)
%
% Identifies the required precision (= 1 / variance^2) to obtain a Gaussian
% kernel with a certain uncertainty for every datapoint. The desired
% uncertainty can be specified through the perplexity u (default = 15). The
% desired perplexity is obtained up to some tolerance that can be specified
% by tol (default = 1e-4).
% The function returns the final Gaussian kernel in P, as well as the
% employed precisions per instance in beta.
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
if ~exist('u', 'var') || isempty(u)
u = 15;
end
if ~exist('tol', 'var') || isempty(tol)
tol = 1e-4;
end
% Initialize some variables
n = size(D, 1); % number of instances
P = zeros(n, n); % empty probability matrix
beta = ones(n, 1); % empty precision vector
logU = log(u); % log of perplexity (= entropy)
% Run over all datapoints
for i=1:n
if ~rem(i, 500)
disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']);
end
% Set minimum and maximum values for precision
betamin = -Inf;
betamax = Inf;
% Compute the Gaussian kernel and entropy for the current precision
[H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i));
% Evaluate whether the perplexity is within tolerance
Hdiff = H - logU;
tries = 0;
while abs(Hdiff) > tol && tries < 50
% If not, increase or decrease precision
if Hdiff > 0
betamin = beta(i);
if isinf(betamax)
beta(i) = beta(i) * 2;
else
beta(i) = (beta(i) + betamax) / 2;
end
else
betamax = beta(i);
if isinf(betamin)
beta(i) = beta(i) / 2;
else
beta(i) = (beta(i) + betamin) / 2;
end
end
% Recompute the values
[H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i));
Hdiff = H - logU;
tries = tries + 1;
end
% Set the final row of P
P(i, [1:i - 1, i + 1:end]) = thisP;
end
disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]);
disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]);
disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]);
end
% Function that computes the Gaussian kernel values given a vector of
% squared Euclidean distances, and the precision of the Gaussian kernel.
% The function also computes the perplexity of the distribution.
function [H, P] = Hbeta(D, beta)
P = exp(-D * beta);
sumP = sum(P);
H = log(sumP) + beta * sum(D .* P) / sumP;
% why not: H = exp(-sum(P(P > 1e-5) .* log(P(P > 1e-5)))); ???
P = P / sumP;
end
|
github
|
pvarin/DynamicVAE-master
|
cg_update.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/cg_update.m
| 3,715 |
utf_8
|
1556078ae7c31950ec738949384cf180
|
% Version 1.000
%
% Code provided by Ruslan Salakhutdinov and Geoff Hinton
%
% Permission is granted for anyone to copy, use, modify, or distribute this
% program and accompanying programs and documents for any purpose, provided
% this copyright notice is retained and prominently displayed, along with
% a note saying that the original programs are available from our
% web page.
% The programs and documents are distributed without any warranty, express or
% implied. As the programs were written for research purposes only, they have
% not been tested to the degree that would be advisable in any important
% application. All use of these programs is entirely at the user's own risk.
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
function [f, df] = cg_update(VV, Dim, XX)
l1 = Dim(1);
l2 = Dim(2);
l3 = Dim(3);
l4 = Dim(4);
l5 = Dim(5);
l6 = Dim(6);
l7 = Dim(7);
l8 = Dim(8);
l9 = Dim(9);
N = size(XX, 1);
% Extract weights back from VV
w1 = reshape(VV(1:(l1 + 1) * l2), l1 + 1, l2);
xxx = (l1 + 1) * l2;
w2 = reshape(VV(xxx + 1:xxx + (l2 + 1) * l3), l2 + 1, l3);
xxx = xxx + (l2 + 1) * l3;
w3 = reshape(VV(xxx + 1:xxx + (l3 + 1) * l4), l3 + 1, l4);
xxx = xxx + (l3 + 1) * l4;
w4 = reshape(VV(xxx + 1:xxx + (l4 + 1) * l5), l4 + 1, l5);
xxx = xxx + (l4 + 1) * l5;
w5 = reshape(VV(xxx + 1:xxx + (l5 + 1) * l6), l5 + 1, l6);
xxx = xxx + (l5 + 1) * l6;
w6 = reshape(VV(xxx + 1:xxx + (l6 + 1) * l7), l6 + 1, l7);
xxx = xxx + (l6 + 1) * l7;
w7 = reshape(VV(xxx + 1:xxx + (l7 + 1) * l8), l7 + 1, l8);
xxx = xxx + (l7 + 1) * l8;
w8 = reshape(VV(xxx + 1:xxx + (l8 + 1) * l9), l8 + 1, l9);
% Evaluate points
XX = [XX ones(N, 1)];
w1probs = 1 ./ (1 + exp(-XX * w1)); w1probs = [w1probs ones(N,1)];
w2probs = 1 ./ (1 + exp(-w1probs * w2)); w2probs = [w2probs ones(N,1)];
w3probs = 1 ./ (1 + exp(-w2probs * w3)); w3probs = [w3probs ones(N,1)];
w4probs = w3probs * w4; w4probs = [w4probs ones(N,1)];
w5probs = 1 ./ (1 + exp(-w4probs * w5)); w5probs = [w5probs ones(N,1)];
w6probs = 1 ./ (1 + exp(-w5probs * w6)); w6probs = [w6probs ones(N,1)];
w7probs = 1 ./ (1 + exp(-w6probs * w7)); w7probs = [w7probs ones(N,1)];
XXout = 1 ./ (1 + exp(-w7probs * w8));
% Compute gradients
f = (-1 / N) * sum(sum(XX(:,1:end - 1) .* log(XXout) + (1 - XX(:,1:end - 1)) .* log(1 - XXout)));
IO = (1 / N) * (XXout - XX(:,1:end - 1));
Ix8 = IO;
dw8 = w7probs'*Ix8;
Ix7 = (Ix8 * w8') .* w7probs .* (1 - w7probs);
Ix7 = Ix7(:,1:end - 1);
dw7 = w6probs' * Ix7;
Ix6 = (Ix7*w7') .* w6probs .* (1 - w6probs);
Ix6 = Ix6(:,1:end - 1);
dw6 = w5probs' * Ix6;
Ix5 = (Ix6 * w6') .* w5probs .* (1 - w5probs);
Ix5 = Ix5(:,1:end - 1);
dw5 = w4probs' * Ix5;
Ix4 = (Ix5 * w5');
Ix4 = Ix4(:,1:end - 1);
dw4 = w3probs' * Ix4;
Ix3 = (Ix4 * w4') .* w3probs .* (1 - w3probs);
Ix3 = Ix3(:,1:end - 1);
dw3 = w2probs' * Ix3;
Ix2 = (Ix3 * w3') .* w2probs .* (1 - w2probs);
Ix2 = Ix2(:,1:end - 1);
dw2 = w1probs' * Ix2;
Ix1 = (Ix2 * w2') .* w1probs .* (1 - w1probs);
Ix1 = Ix1(:,1:end - 1);
dw1 = XX' * Ix1;
% Return gradients
df = [dw1(:)' dw2(:)' dw3(:)' dw4(:)' dw5(:)' dw6(:)' dw7(:)' dw8(:)']';
|
github
|
pvarin/DynamicVAE-master
|
lmvu.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/lmvu.m
| 8,540 |
utf_8
|
c8003ed7ff0fd0e226776c42c72ad385
|
function [mappedX, mapping] = lmvu(X, no_dims, K, LL)
%LMVU Performs Landmark MVU on dataset X
%
% [mappedX, mapping] = lmvu(X, no_dims, k1, k2)
%
% The function performs Landmark MVU on the DxN dataset X. The value of k1
% represents the number of nearest neighbors that is employed in the MVU
% constraints. The value of k2 represents the number of nearest neighbors
% that is employed to compute the reconstruction weights (for embedding the
% non-landmark points).
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
if ~exist('K', 'var')
K = 3;
end
if ~exist('LL', 'var')
LL = 12;
end
% Save some data for out-of-sample extension
if ischar(K)
error('Adaptive neighborhood selection not supported for landmark MVU.');
end
mapping.k1 = K;
mapping.k2 = LL;
mapping.X = X;
% Initialize some variables
N = size(X, 2); % number of datapoints
B = ceil(0.02 * N); % number of landmark points
% Set some parameters parameters
pars.ep = eps;
pars.fastmode = 1;
pars.warmup = K * B / N;
pars.verify = 1;
pars.angles = 1;
pars.maxiter = 100;
pars.noise = 0;
pars.ignore = 0.1;
pars.penalty = 1;
pars.factor = 0.9999;
% Identify nearest neighbors
disp('Identifying nearest neighbors...');
KK = max(LL, K);
X = L2_distance(X, X); % memory-intensive: O(n^{2}) !!!
[foo, neighbors] = find_nn(X, KK);
neighbors = neighbors';
% Get inverse of reconstruction weight matrix
Pia = getPia(B, LL, X, neighbors);
% Generate SDP problem
disp('Generating SDP problem...');
neighbors = neighbors(1:K,:);
clear temp index sorted
nck = nchoosek(1:K + 1, 2);
AA = zeros(N * K, 2);
pos3 = 1;
for i=1:N
ne = neighbors(:,i);
nne = [ne; i];
pairs = nne(nck);
js = pairs(:,1);
ks = pairs(:,2);
AA(pos3:pos3 + length(js) - 1,:) = sort([js ks], 2);
pos3 = pos3 + length(js);
if i == B
AA = unique(AA, 'rows');
ForceC = size(AA, 1);
end
if pos3 > size(AA, 1) && i < N
AA = unique(AA, 'rows');
pos3 = size(AA, 1) + 1;
AA = [AA; zeros(round(N / (N - i) * pos3), 2)];
fprintf('.');
end
end
AA = unique(AA, 'rows');
AA = AA(2:end,:);
clear neighbors ne v2 v3 js ks
bb = zeros(1, size(AA, 1));
for i=1:size(AA, 1)
bb(i) = sum((X(:,AA(i, 1)) - X(:,AA(i, 2))) .^ 2);
end
disp(' ');
% Reduce the number of forced vectors
ii = (1:ForceC)';
jj = zeros(1, size(AA, 1));
jj(ii) = 1;
jj = find(jj == 0);
jj1 = jj(jj <= ForceC);
jj2 = jj(jj > ForceC);
jj2 = jj2(randperm(length(jj2)));
jj1 = jj1(randperm(length(jj1)));
corder = [ii; jj1'; jj2'];
AA = AA(corder,:);
bb = bb(corder);
ForceC = length(ii);
clear temp jj1 jj2 jj ii
Const = max(round(pars.warmup * size(AA, 1)), ForceC);
[A, b, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars);
Qt = sum(Pia, 1)' * sum(Pia, 1);
A = [Qt(:)'; A];
b = [0; b];
clear K;
solved = 0;
% Start SDP iterations
disp('Perform semi-definite programming...');
disp('CSDP OUTPUT =============================================================================');
while solved == 0
% Initialize some variables
c = -vec(Pia' * Pia);
flags.s = B;
flags.l = size(A, 1) - 1;
A = [[zeros(1,flags.l); speye(flags.l)] A];
% Set c (employ penalty)
c = [ones(ForceC, 1) .* max(max(c)); zeros(flags.l - ForceC, 1); c];
% Launch the CSDP solver
options.maxiter=pars.maxiter;
[x, d, z, info] = csdp(A, b, c, flags, options);
K = mat(x(flags.l + 1:flags.l + flags.s ^ 2));
% Check whether a solution is reached
solved = isempty(AA);
A = A(:,flags.l + 1:end);
xx = K(:);
if size(AA, 1)
Aold = size(A,1);
total = 0;
while size(A, 1) - Aold < Const && ~isempty(AA)
[newA, newb, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars);
jj = find(newA * xx - newb > pars.ignore * abs(newb));
if info == 2
jj = 1:size(newA, 1);
end
total = total + length(jj);
A(size(A,1) + 1:size(A,1) + length(jj),:) = newA(jj,:);
b(length(b) + 1:length(b) + length(jj)) = newb(jj);
end
if total == 0
solved = 1;
end
else
solved=1;
end
if solved == 1 && pars.maxiter < 100
pars.maxiter = 100;
end
end
disp('=========================================================================================');
% Perform eigendecomposition of kernel matrix to compute Y
disp('Perform eigendecomposition to obtain low-dimensional data representation...');
[V, D] = eig(K);
V = V * sqrt(D);
Y = (V(:,end:-1:1))';
mappedX = Y * Pia';
% Reorder data in original order
mappedX = mappedX(1:no_dims,:);
% Set some information for the out-of-sample extension
mapping.Y = Y;
mapping.D = X;
mapping.no_landmarks = B;
mapping.no_dims = no_dims;
% Function that computes LLE weight matrix
function Q = getPia(B, LL, X, neighbors)
% Initialize some variables
N = size(X,2);
% Compute reconstruction weights
disp('Computing reconstruction weights...');
tol = 1e-7;
Pia = sparse([], [], [], B, N);
for i=1:N
z = X(:,neighbors(:,i)) - repmat(X(:,i), 1, LL);
C = z' * z;
C = C + tol * trace(C) * eye(LL) / LL;
invC = inv(C);
Pia(neighbors(:,i),i) = sum(invC)' / sum(sum(invC));
end
% Fill sparse LLE weight matrix
M = speye(N) + sparse([], [], [], N, N, N * LL .^ 2);
for i=1:N
j = neighbors(:,i);
w = Pia(j, i);
M(i, j) = M(i, j) - w';
M(j, i) = M(j, i) - w;
M(j, j) = M(j, j) + w * w';
end
% Invert LLE weight matrix
disp('Invert reconstruction weight matrix...');
Q = -M(B + 1:end, B + 1:end) \ M(B + 1:end, 1:B);
Q = [eye(B); Q];
% Functions that constructs the constraints for the SDP
function [A, b, AAomit, bbomit] = getConstraints(AA, Pia, bb, B, Const, pars)
% Initialize some variables
pos2 = 0;
perm = 1:size(AA,1);
if size(AA, 1) > Const
AAomit = AA(perm(Const + 1:end),:);
bbomit = bb(perm(Const + 1:end));
AA = AA(perm(1:Const),:);
bb = bb(perm(1:Const));
else
AAomit = [];
bbomit = [];
end
% Allocate some memory
persistent reqmem;
if isempty(reqmem)
A2 = zeros(size(AA, 1) * B, 3);
else
A2 = zeros(reqmem, 3);
end
% Set the constraints
pos = 0;
for j=1:size(AA, 1)
% Evaluate for current row in AA
ii = AA(j, 1);
jj = AA(j, 2);
Q = Pia(ii,:)' * Pia(ii,:) - 2 .* Pia(jj,:)' * Pia(ii,:) + Pia(jj,:)' * Pia(jj,:);
Q = (Q + Q') ./ 2;
it = find(abs(Q) > pars.ep .^ 2);
% Constraint found
if ~isempty(it)
% Allocate more memory if needed
pos = pos + 1;
if pos2 + length(it) > size(A2, 1)
A2 = [A2; zeros(ceil((size(AA, 1) - j) / j * size(A2, 1)), 3)];
end
% Set constraint
A2(1 + pos2:pos2 + length(it), 1) = ones(length(it), 1) .* pos;
A2(1 + pos2:pos2 + length(it), 2) = it;
A2(1 + pos2:pos2 + length(it), 3) = full(Q(it));
pos2 = pos2 + length(it);
end
end
% Construct sparse constraint matrix
reqmem = pos2;
A2 = A2(1:pos2,:);
A = sparse(A2(:,1), A2(:,2), A2(:,3), size(AA,1), B .^ 2);
b = bb';
% Function that vectorizes a matrix
function v = vec(M)
v = M(:);
% Function that matrixizes a vector
function M = mat(C)
r = round(sqrt(size(C, 1)));
M = reshape(C, r, r);
|
github
|
pvarin/DynamicVAE-master
|
cca.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/cca.m
| 14,846 |
utf_8
|
935e971ffe825a64e0eb80c535d71ebb
|
function [Z, ccaEigen, ccaDetails] = cca(X, Y, EDGES, OPTS)
%
% Function [Z, CCAEIGEN, CCADETAILS] = CCA(X, Y, EDGES, OPTS) computes a low
% dimensional embedding Z in R^d that maximally preserves angles among input
% data X that lives in R^D, with the algorithm Conformal Component Analysis.
%
% The embedding Z is constrained to be Z = L*Y where Y is a partial basis that
% spans the space of R^d. Such Y can be computed from graph Laplacian (such as
% the outputs of Laplacian eigenmap and Locally Linear Embedding, ie, LLE).
% The parameterization matrix L is found by this function as to maximally
% prserve angles between edges coded in the sparse matrix EDGES.
%
% A basic usage of this function is given below:
%
% Inputs:
% X: input data stored in matrix (D x N) where D is the dimensionality
%
% Y: partial basis stored in matrix (d x N)
%
% EDGES: a sparse matrix of (N x N). In each column i, the row indices j to
% nonzero entrices define data points that are in the nearest neighbors of
% data point i.
%
% OPTS:
% OPTS.method: 'CCA'
%
% Outputs:
% Z: low dimensional embedding (d X N)
% CCAEIGN: eigenspectra of the matrix P = L'*L. If P is low-rank (say d' < d),
% then Z can be cutoff at d' dimension as dimensionality reduced further.
%
% The CCA() function is fairly versatile. For more details, consult the file
% README.
%
% by [email protected] Aug 18, 2006
% Feel free to use it for educational and research purpose.
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
% sanity check
if nargin ~= 4
error('Incorrect number of inputs supplied to cca().');
end
N = size(X,2);
if (N~=size(Y,2)) || (N ~= size(EDGES,1)) || (N~=size(EDGES,2))
disp('Unmatched matrix dimensions in cca().');
fprintf('# of data points: %d\n', N);
fprintf('# of data points in Y: %d\n', size(Y,2));
fprintf('Size of the sparse matrix for edges: %d x %d\n', size(EDGES,1), size(EDGES,2));
error('All above 4 numbers should be the same.');
end
% check necessary programs
if exist('mexCCACollectData') ~= 3
error('Missing mexCCACollectData mex file on the path');
end
if exist('csdp') ~= 2
error('You will need CSDP solver to run cca(). Please make sure csdp.m is in your path');
end
% check options
OPTS = check_opt(OPTS);
D = size(X, 1);
d = size(Y, 1);
%disp('Step I. collect data needed for SDP formulation');
[tnn, vidx] = triangNN(EDGES, OPTS.CCA);
[erow, ecol, evalue] = sparse_nn(tnn);
irow = int32(erow); icol = int32(ecol);
ividx = int32(vidx); ivalue = int32(evalue);
[A,B, g] = mexCCACollectData(X,Y, irow, icol, int32(OPTS.relative), ivalue, ividx );
clear erow ecol irow icol tnn ividx ivalue evalue vidx;
lst = find(g~=0);
g = g(lst); B = B(:, lst);
if OPTS.CCA == 1
BG = B*spdiags(1./sqrt(g),0, length(g),length(g));
Q = A - BG*BG';
BIAS = OPTS.regularizer*reshape(eye(d), d^2,1);
else
Q = A; BIAS = 2*sum(B,2)+OPTS.regularizer*reshape(eye(d), d^2,1);
end
[V, E] = eig(Q+eye(size(Q))); % adding an identity matrix to Q for numerical
E = E-eye(size(Q)); % stability
E(E<0) = 0;
if ~isreal(diag(E))
warning('\tThe quadratic matrix is not positive definite..forced to be positive definite...\n');
E=real(E);
V = real(V);
S = sqrt(E)*V';
else
S = sqrt(E)*V';
end
% Formulate the SDP problem
[AA, bb, cc] = formulateSDP(S, d, BIAS, (OPTS.CCA==1));
sizeSDP = d^2+1 + d + 2*(OPTS.CCA==1);
csdppars.s = sizeSDP;
csdpopts.printlevel = 0;
% Solve it using CSDP
[xx, yy, zz, info] = csdp(AA, bb, cc, csdppars,csdpopts);
ccaDetails.sdpflag = info;
% The negate of yy is our solution
yy = -yy;
idx = 0;
P = zeros(d);
for col=1:d
for row = col:d
idx=idx+1;
P(row, col) = yy(idx);
end
end
% Convert P to a positive definite matrix
P = P + P' - diag(diag(P));
% Transform the original projection to the new projection
[V, E] = eig(P);
E(E < 0) = 0;
L = diag(sqrt(diag(E))) * V';
newY = L * Y;
% Eigenvalue of the new projection, doing PCA using covariance matrix
[newV, newE] = eig(newY * newY');
newE = diag(newE);
[dummy, idx] = sort(newE);
newE = newE(idx(end:-1:1));
newY = newV' * newY;
Z = newY(idx(end:-1:1),:);
ccaEigen = newE;
ccaDetails.cost = P(:)'*Q*P(:) - BIAS'*P(:) + sum(g(:))*(OPTS.MVU==1);
if OPTS.CCA == 1
ccaDetails.c = spdiags(1./sqrt(g),0, length(g),length(g))*B'*P(:);
else
ccaDetails.c = [];
end
ccaDetails.P = P;
ccaDetails.opts = OPTS;
%%%%%%%%%%%%%%%%%%%% FOLLOWING IS SUPPORTING MATLAB FUNCTIONS
function [A, b, c] = formulateSDP(S, D, bb, TRACE)
[F0, FI, c] = localformulateSDP(S, D, bb, TRACE);
[A, b, c] = sdpToSeDuMi(F0, FI, c);
function [F0, FI, c] = localformulateSDP(S, D, b, TRACE)
% formulate SDP problem
% each FI that corresponds to the LMI for the quadratic cost function has
% precisely 2*D^2 nonzero elements. But we need only D^2 storage for
% indexing these elements since the FI are symmetric
tempFidx = zeros(D^2, 3);
dimF = (D^2+1) + D + 2*TRACE;
idx= 0;
tracearray = ones(TRACE,1);
for col=1:D
for row=col:D
idx = idx+1;
lindx1 = sub2ind([D D], row, col);
lindx2 = sub2ind([D D], col, row);
tempFidx(:,1) = [1:D^2]';
tempFidx(:,2) = D^2+1;
if col==row
tempFidx(:,3) = S(:, lindx1) ;
FI{idx} = sparse([tempFidx(:,1); ... % for cost function
tempFidx(:,2); ... % symmetric
row+D^2+1; ... % for P being p.s.d
tracearray*(D^2+1+D+1); % for trace
tracearray*(D^2+1+D+2); % for negate trace
], ...
[tempFidx(:,2); ... % for cost function
tempFidx(:,1); ... % symmetric
row+D^2+1; ... % for P being p.s.d
tracearray*(D^2+1+D+1); % for trace
tracearray*(D^2+1+D+2); % for negate trace
],...
[tempFidx(:,3); ... % for cost function
tempFidx(:,3); ... % symmetric
1; % for P being p.s.d
tracearray*1; % for trace
tracearray*(-1); % for negate trace
], dimF, dimF);
else
tempFidx(:,3) = S(:, lindx1) + S(:, lindx2);
FI{idx} = sparse([tempFidx(:,1); ... % for cost function
tempFidx(:,2); ... % symmetric
row+D^2+1; ... % for P being p.s.d
col+D^2+1; ... % symmetric
], ...
[tempFidx(:,2); ... % for cost function
tempFidx(:,1); ... % symmetric
col+D^2+1; ... % for P being p.s.d
row+D^2+1; ... % being symmetric
],...
[tempFidx(:,3); ... % for cost function
tempFidx(:,3); ... % symmetric
1; % for P being p.s.d
1; % symmetric
], dimF, dimF);
end
end
end
idx=idx+1;
% for the F matrix corresponding to t
FI{idx} = sparse(D^2+1, D^2+1, 1, dimF, dimF);
% now for F0
if TRACE==1
F0 = sparse( [[1:D^2] dimF-1 dimF], [[1:D^2] dimF-1 dimF], [ones(1, D^2) -1 1], dimF, dimF);
else
F0 = sparse( [[1:D^2]], [[1:D^2]], [ones(1, D^2)], dimF, dimF);
end
% now for c
b = reshape(-b, D, D);
b = b*2 - diag(diag(b));
c = zeros(idx-1,1);
kdx=0;
%keyboard;
for col=1:D
for row=col:D
kdx = kdx+1;
c(kdx) = b(row, col);
end
end
%keyboard;
c = [c; 1]; % remember: we use only half of P
return;
function [A, b, c] = sdpToSeDuMi(F0, FI, cc)
% convert the canonical SDP dual formulation:
% (see Vandenberche and Boyd 1996, SIAM Review)
% max -Tr(F0 Z)
% s.t. Tr(Fi Z) = cci and Z is positive definite
%
% in which cc = (cc1, cc2, cc3,..) and FI = {F1, F2, F3,...}
%
% to SeDuMi format (formulated as vector decision variables ):
% min c'x
% s.t. Ax = b and x is positive definite (x is a vector, so SeDuMi
% really means that vec2mat(x) is positive definite)
%
% by [email protected], June, 10, 2004
if nargin < 3
error('Cannot convert SDP formulation to SeDuMi formulation in sdpToSeDumi!');
end
[m, n] = size(F0);
if m ~= n
error('F0 matrix must be squared matrix in sdpToSeDumi(F0, FI, b)');
end
p = length(cc);
if p ~= length(FI)
error('FI matrix cellarray must have the same length as b in sdpToSeDumi(F0,FI,b)');
end
% should check every element in the cell array FI...later..
% x = reshape(Z, n*n, 1); % optimization variables from matrix to vector
% converting objective function of the canonical SDP
c = reshape(F0', n*n,1);
% converting equality constraints of the canonical SDP
zz= 0;
for idx=1:length(FI)
zz= zz + nnz(FI{idx});
end
A = spalloc( n*n, p, zz);
for idx = 1:p
temp = reshape(FI{idx}, n*n,1);
lst = find(temp~=0);
A(lst, idx) = temp(lst);
end
% The SeDuMi solver actually expects the transpose of A as in following
% dual problem
% max b'y
% s.t. c - A'y is positive definite
% Therefore, we transpose A
% A = A';
% b doesn't need to be changed
b = cc;
return;
% Check OPTS that is passed into
function OPTS = check_opt(OPTS)
if isfield(OPTS,'method') == 0
OPTS.method = 'cca';
disp('Options does''t have method field, so running CCA');
end
if strncmpi(OPTS.method, 'MVU',3)==1
OPTS.CCA = 0; OPTS.MVU = 1;
else
OPTS.CCA = 1; OPTS.MVU = 0;
end
if isfield(OPTS, 'relative')==0
OPTS.relative = 0;
end
if OPTS.CCA==1 && OPTS.relative ==1
disp('Running CCA, so the .relative flag set to 0');
OPTS.relative = 0;
end
if isfield(OPTS, 'regularizer')==0
OPTS.regularizer = 0;
end
return
function [tnn vidx]= triangNN(snn, TRI)
% function [TNN VIDX]= triangNN(SNN) triangulates a sparse graph coded by spare matrix
% SNN. TNN records the original edges in SNN as well as those that are
% triangulated. Each edge is associated with a scaling factor that is specific
% to a vertex. And VIDX records the id of the vertex.
%
% by [email protected] Aug. 15, 2006.
N = size(snn,1);
%fprintf('The graph has %d vertices\n', N);
% figure out maximum degree a vertex has
connectivs = sum(snn,1);
maxDegree = max(connectivs);
tnn = spalloc(N, N, round(maxDegree*N)); % prealloc estimated storage for speedup
% triangulation
for idx=1:N
lst = find(snn(:, idx)>0);
for jdx=1:length(lst)
col = min (idx, lst(jdx));
row = max(idx, lst(jdx));
tnn(row, col) = tnn(row, col)+1;
if TRI == 1
for kdx = jdx+1:length(lst)
col = min(lst(jdx), lst(kdx));
row = max(lst(jdx), lst(kdx));
tnn(row, col) = tnn(row, col)+1;
end
end
end
end
numVertexIdx = full(sum(tnn(:)));
%fprintf('%d vertex entries are needed\n', numVertexIdx);
rowIdx = zeros(numVertexIdx,1);
colIdx = zeros(numVertexIdx,1);
vidx = zeros(numVertexIdx,1);
whichEdge = 0;
for idx=1:N
lst = find(snn(:, idx)>0);
for jdx=1:length(lst)
col = min(lst(jdx), idx);
row = max(lst(jdx), idx);
whichEdge = whichEdge+1;
rowIdx(whichEdge) = row;
colIdx(whichEdge) = col;
vidx(whichEdge) = idx;
if TRI==1
for kdx = jdx+1:length(lst)
col = min(lst(jdx), lst(kdx));
row = max(lst(jdx), lst(kdx));
whichEdge = whichEdge+1;
rowIdx(whichEdge) = row;
colIdx(whichEdge) = col;
vidx(whichEdge) = idx;
end
end
end
end
linearIdx = sub2ind([N N],rowIdx, colIdx);
[sa, sIdx] = sort(linearIdx);
vidx = vidx(sIdx);
return
% turn sparse graph snn into row and col indices
function [edgesrow, edgescol, value] = sparse_nn(snn)
N = size(snn,1);
edgescol = zeros(N+1,1);
nnzer = nnz(snn);
edgesrow = zeros(nnzer,1);
value = zeros(nnzer,1);
edgescol(1) = 0;
for jdx=1:N
lst = find(snn(:, jdx)>0);
%lst = lst(find(lst>jdx));
edgescol(jdx+1) = edgescol(jdx)+length(lst);
edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1;
value(edgescol(jdx)+1:edgescol(jdx+1)) = snn(lst, jdx);
end
return
|
github
|
pvarin/DynamicVAE-master
|
x2p.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/x2p.m
| 3,597 |
utf_8
|
4a102e94922f4af38e36c374dccbc5a2
|
function [P, beta] = x2p(X, u, tol)
%X2P Identifies appropriate sigma's to get kk NNs up to some tolerance
%
% [P, beta] = x2p(xx, kk, tol)
%
% Identifies the required precision (= 1 / variance^2) to obtain a Gaussian
% kernel with a certain uncertainty for every datapoint. The desired
% uncertainty can be specified through the perplexity u (default = 15). The
% desired perplexity is obtained up to some tolerance that can be specified
% by tol (default = 1e-4).
% The function returns the final Gaussian kernel in P, as well as the
% employed precisions per instance in beta.
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
if ~exist('u', 'var') || isempty(u)
u = 15;
end
if ~exist('tol', 'var') || isempty(tol)
tol = 1e-4;
end
% Initialize some variables
n = size(X, 1); % number of instances
P = zeros(n, n); % empty probability matrix
beta = ones(n, 1); % empty precision vector
logU = log(u); % log of perplexity (= entropy)
% Compute pairwise distances
% disp('Computing pairwise distances...');
D = squareform(pdist(X, 'euclidean') .^ 2);
% Run over all datapoints
% disp('Computing P-values...');
for i=1:n
% if ~rem(i, 500)
% disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']);
% end
% Set minimum and maximum values for precision
betamin = -Inf;
betamax = Inf;
% Compute the Gaussian kernel and entropy for the current precision
Di = D(i, [1:i-1 i+1:end]);
[H, thisP] = Hbeta(Di, beta(i));
% Evaluate whether the perplexity is within tolerance
Hdiff = H - logU;
tries = 0;
while abs(Hdiff) > tol && tries < 50
% If not, increase or decrease precision
if Hdiff > 0
betamin = beta(i);
if isinf(betamax)
beta(i) = beta(i) * 2;
else
beta(i) = (beta(i) + betamax) / 2;
end
else
betamax = beta(i);
if isinf(betamin)
beta(i) = beta(i) / 2;
else
beta(i) = (beta(i) + betamin) / 2;
end
end
% Recompute the values
[H, thisP] = Hbeta(Di, beta(i));
Hdiff = H - logU;
tries = tries + 1;
end
% Set the final row of P
P(i, [1:i - 1, i + 1:end]) = thisP;
end
% disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]);
% disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]);
% disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]);
end
% Function that computes the Gaussian kernel values given a vector of
% squared Euclidean distances, and the precision of the Gaussian kernel.
% The function also computes the perplexity of the distribution.
function [H, P] = Hbeta(D, beta)
P = exp(-D * beta);
sumP = sum(P);
H = log(sumP) + beta * sum(D .* P) / sumP;
P = P / sumP;
end
|
github
|
pvarin/DynamicVAE-master
|
sammon.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/sammon.m
| 7,108 |
utf_8
|
8a1fccbea9525bbebae4039127005ea6
|
function [y, E] = sammon(x, n, opts)
%SAMMON Performs Sammon's MDS mapping on dataset X
%
% Y = SAMMON(X) applies Sammon's nonlinear mapping procedure on
% multivariate data X, where each row represents a pattern and each column
% represents a feature. On completion, Y contains the corresponding
% co-ordinates of each point on the map. By default, a two-dimensional
% map is created. Note if X contains any duplicated rows, SAMMON will
% fail (ungracefully).
%
% [Y,E] = SAMMON(X) also returns the value of the cost function in E (i.e.
% the stress of the mapping).
%
% An N-dimensional output map is generated by Y = SAMMON(X,N) .
%
% A set of optimisation options can also be specified using a third
% argument, Y = SAMMON(X,N,OPTS) , where OPTS is a structure with fields:
%
% MaxIter - maximum number of iterations
% TolFun - relative tolerance on objective function
% MaxHalves - maximum number of step halvings
% Input - {'raw','distance'} if set to 'distance', X is
% interpreted as a matrix of pairwise distances.
% Display - {'off', 'on', 'iter'}
% Initialisation - {'pca', 'random'}
%
% The default options structure can be retrieved by calling SAMMON with
% no parameters.
%
% References :
%
% [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data Structure
% Analysis", IEEE Transactions on Computers, vol. C-18, no. 5,
% pp 401-409, May 1969.
%
% See also : SAMMON_TEST
%
% File : sammon.m
%
% Date : Monday 12th November 2007.
%
% Author : Gavin C. Cawley and Nicola L. C. Talbot
%
% Description : Simple vectorised MATLAB implementation of Sammon's non-linear
% mapping algorithm [1].
%
% References : [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data
% Structure Analysis", IEEE Transactions on Computers,
% vol. C-18, no. 5, pp 401-409, May 1969.
%
% History : 10/08/2004 - v1.00
% 11/08/2004 - v1.10 Hessian made positive semidefinite
% 13/08/2004 - v1.11 minor optimisation
% 12/11/2007 - v1.20 initialisation using the first n principal
% components.
%
% Thanks : Dr Nick Hamilton ([email protected]) for supplying the
% code for implementing initialisation using the first n
% principal components (introduced in v1.20).
%
% To do : The current version does not take advantage of the symmetry
% of the distance matrix in order to allow for easy
% vectorisation. This may not be a good choice for very large
% datasets, so perhaps one day I'll get around to doing a MEX
% version using the BLAS library etc. for very large datasets.
%
% Copyright : (c) Dr Gavin C. Cawley, November 2007.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
% use the default options structure
if nargin < 3
opts.Display = 'iter';
opts.Input = 'raw';
opts.MaxHalves = 20;
opts.MaxIter = 500;
opts.TolFun = 1e-9;
opts.Initialisation = 'random';
end
% the user has requested the default options structure
if nargin == 0
y = opts;
return;
end
% Create a two-dimensional map unless dimension is specified
if nargin < 2
n = 2;
end
% Set level of verbosity
if strcmp(opts.Display, 'iter')
display = 2;
elseif strcmp(opts.Display, 'on')
display = 1;
else
display = 0;
end
% Create distance matrix unless given by parameters
if strcmp(opts.Input, 'distance')
D = x;
else
D = euclid(x, x);
end
% Remaining initialisation
N = size(x, 1);
scale = 0.5 / sum(D(:));
D = D + eye(N);
Dinv = 1 ./ D;
if strcmp(opts.Initialisation, 'pca')
[UU,DD] = svd(x);
y = UU(:,1:n)*DD(1:n,1:n);
else
y = randn(N, n);
end
one = ones(N,n);
d = euclid(y,y) + eye(N);
dinv = 1./d;
delta = D - d;
E = sum(sum((delta.^2).*Dinv));
% Get on with it
for i=1:opts.MaxIter
% Compute gradient, Hessian and search direction (note it is actually
% 1/4 of the gradient and Hessian, but the step size is just the ratio
% of the gradient and the diagonal of the Hessian so it doesn't
% matter).
delta = dinv - Dinv;
deltaone = delta * one;
g = delta * y - y .* deltaone;
dinv3 = dinv .^ 3;
y2 = y .^ 2;
H = dinv3 * y2 - deltaone - 2 * y .* (dinv3 * y) + y2 .* (dinv3 * one);
s = -g(:) ./ abs(H(:));
y_old = y;
% Use step-halving procedure to ensure progress is made
for j=1:opts.MaxHalves
y(:) = y_old(:) + s;
d = euclid(y, y) + eye(N);
dinv = 1 ./ d;
delta = D - d;
E_new = sum(sum((delta .^ 2) .* Dinv));
if E_new < E
break;
else
s = 0.5*s;
end
end
% Bomb out if too many halving steps are required
if j == opts.MaxHalves
warning('MaxHalves exceeded. Sammon mapping may not converge...');
end
% Evaluate termination criterion
if abs((E - E_new) / E) < opts.TolFun
if display
fprintf(1, 'Optimisation terminated - TolFun exceeded.\n');
end
break;
end
% Report progress
E = E_new;
if display > 1
fprintf(1, 'epoch = %d : E = %12.10f\n', i, E * scale);
end
end
% Fiddle stress to match the original Sammon paper
E = E * scale;
end
function d = euclid(x, y)
d = sqrt(sum(x.^2,2)*ones(1,size(y,1))+ones(size(x,1),1)*sum(y.^2,2)'-2*(x*y'));
end
|
github
|
pvarin/DynamicVAE-master
|
sdecca2.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/sdecca2.m
| 7,185 |
utf_8
|
e53979561adda6a23883da0e72af5bf6
|
function [P, newY, L, newV, idx]= sdecca2(Y, snn, regularizer, relative)
% doing semidefinitve embedding/MVU with output being parameterized by graph
% laplacian's eigenfunctions..
%
% the algorithm is same as conformal component analysis except that the scaling
% factor there is set as 1
%
%
% function [P, newY, Y] = CDR2(X, Y, NEIGHBORS) implements the
% CONFORMAL DIMENSIONALITY REDUCTION of data X. It finds a linear map
% of Y -> L*Y such that X and L*Y is related by a conformal mapping.
%
% No tehtat The algorithm use the formulation of only distances.
%
% Input:
% Y: matrix of d'xN, with each column is a point in R^d'
% NEIGHBORS: matrix of KxN, each column is a list of indices (between 1
% and N) to the nearest-neighbor of the corresponding column in X
% Output:
% P: square of the linear map L, i.e., P = L'*L
% newY: transformed data points, i.e., newY = L*Y;
% Y: the linear map L itself, i.e., L = L
%
% The algorithm finds L by solving a semidefinite programming problem. It
% calls csdp() SDP solver by default and assumes that it is on the path.
%
% written by [email protected]
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
% Collect the data
[erow, ecol, edist] = sparse_nn(snn);
irow = int32(erow);
icol = int32(ecol);
[A, B, g] = mexCCACollectData2(Y, irow, icol, edist, int32(relative));
BG = 2 * sum(B, 2);
Q = A ;
[V, E] = eig(Q + eye(size(Q)));
E = E - eye(size(Q));
E(E < 0) = 0;
if ~isreal(diag(E))
E = real(E);
V = real(V);
S = sqrt(E) * V';
else
S = sqrt(E) * V';
end
% Put the regularizer in there
BG = BG + regularizer * reshape(eye(size(Y, 1)), size(Y, 1) ^ 2, 1);
% Formulate the SDP problem
[AA, bb, cc] = formulateSDP(S, size(Y, 1), BG);
sizeSDP = size(Y, 1) ^ 2 + 1 + size(Y, 1);
pars.s = sizeSDP;
opts.printlevel = 1;
% Solve it using CSDP
[xx, yy] = csdp(AA, bb, cc, pars, opts);
% The negate of yy is our solution
yy = -yy;
idx = 0;
P = zeros(size(Y, 1));
for col=1:size(Y, 1)
for row = col:size(Y, 1)
idx = idx + 1;
P(row, col) = yy(idx);
end
end
% Convert P to a positive definite matrix
P = P + P' - diag(diag(P));
% Transform the original projection to the new projection
[V, E] = eig(P);
E(E < 0) = 0;
L = diag(sqrt(diag(E))) * V';
newY = L * Y; % multiply with Laplacian
% Eigendecomposition of the new projection: doing PCA because the
% dimensionality of newY or Y is definitely less than the number of
% points
[newV, newE] = eig(newY * newY');
newE = diag(newE);
[dummy, idx] = sort(newE);
newY = newV' * newY;
newY = newY(idx(end:-1:1),:);
return
% Function that formulates the SDP problem
function [A, b, c]=formulateSDP(S, D, bb)
[F0, FI, c] = localformulateSDP(S, D, bb);
[A, b, c] = sdpToSeDuMi(F0, FI, c);
return
% Function that formulates the SDP problem
function [F0, FI, c] = localformulateSDP(S, D, b)
% Each FI that corresponds to the LMI for the quadratic cost function has
% precisely 2 * D^2 nonzero elements. But we need only D^2 storage for
tempFidx = zeros(D ^ 2, 3);
dimF = (D ^ 2 + 1) + D;
idx = 0;
for col=1:D
for row=col:D
idx = idx + 1;
lindx1 = sub2ind([D D], row, col);
lindx2 = sub2ind([D D], col, row);
tempFidx(:,1) = [1:D ^ 2]';
tempFidx(:,2) = D ^ 2 + 1;
if col == row
tempFidx(:,3) = S(:,lindx1) ;
FI{idx} = sparse([tempFidx(:,1); ... % for cost function
tempFidx(:,2); ... % symmetric
row + D^2 + 1 ... % for P being p.s.d
], ...
[tempFidx(:,2); ... % for cost function
tempFidx(:,1); ... % symmetric
row + D^2 + 1; ... % for P being p.s.d
],...
[tempFidx(:,3); ... % for cost function
tempFidx(:,3); ... % symmetric
1; % for P being p.s.d
], dimF, dimF);
else
tempFidx(:,3) = S(:, lindx1) + S(:,lindx2);
FI{idx} = sparse([tempFidx(:,1); ... % for cost function
tempFidx(:,2); ... % symmetric
row + D^2 + 1; ... % for P being p.s.d
col + D^2 + 1; ... % symmetric
], ...
[tempFidx(:,2); ... % for cost function
tempFidx(:,1); ... % symmetric
col + D^2 + 1; ... % for P being p.s.d
row + D^2 + 1; ... % being symmetric
], ...
[tempFidx(:,3); ... % for cost function
tempFidx(:,3); ... % symmetric
1; % for P being p.s.d
1; % symmetric
], dimF, dimF);
end
end
end
idx = idx + 1;
% For the F matrix corresponding to t
FI{idx} = sparse(D^2 + 1, D^2 + 1, 1, dimF, dimF);
% Now for F0
F0 = sparse(1:D^2, 1:D^2, ones(1, D^2), dimF, dimF);
% Now for c
b = reshape(-b, D, D);
b = b * 2 - diag(diag(b));
c = zeros(idx - 1,1);
kdx = 0;
for col=1:D
for row=col:D
kdx = kdx + 1;
c(kdx) = b(row, col);
end
end
c = [c; 1];
return
% Function that convertsthe canonical SDP dual formulation to SeDuMi format
function [A, b, c] = sdpToSeDuMi(F0, FI, cc)
% Check inputs
if nargin < 3
error('Cannot convert SDP formulation to SeDuMi formulation.');
end
[m, n] = size(F0);
if m ~= n
error('F0 matrix must be squared matrix.');
end
p = length(cc);
if p ~= length(FI)
error('FI matrix cellarray must have the same length as b.');
end
% Converting objective function of the canonical SDP
c = reshape(F0', n * n, 1);
% Converting equality constraints of the canonical SDP
zz = 0;
for idx=1:length(FI)
zz= zz + nnz(FI{idx});
end
A = spalloc(n * n, p, zz);
for idx=1:p
temp = reshape(FI{idx}, n * n, 1);
lst = find(temp ~= 0);
A(lst, idx) = temp(lst);
end
% We do not need to convert b
b = cc;
return
|
github
|
pvarin/DynamicVAE-master
|
sparse_nn.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/sparse_nn.m
| 972 |
utf_8
|
df5da172f954ec2f53125a04787cf2d3
|
%SPARSE_NN
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
function [edgesrow, edgescol,edgesdist] = sparse_nn(snn)
% turn into sparse nearest neighbor graph snn into edgesrow and edgescol index
N = size(snn,1);
edgescol = zeros(N+1,1);
nnzer = nnz(snn);
edgesrow = zeros(nnzer,1);
edgesdist = zeros(nnzer,1);
edgescol(1) = 0;
for jdx=1:N
lst = find(snn(:, jdx)>0);
%lst = lst(find(lst>jdx));
edgescol(jdx+1) = edgescol(jdx)+length(lst);
edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1;
edgesdist(edgescol(jdx)+1:edgescol(jdx+1))=snn(lst,jdx);
end
|
github
|
pvarin/DynamicVAE-master
|
jdqz.m
|
.m
|
DynamicVAE-master/drtoolbox/techniques/jdqz.m
| 78,986 |
utf_8
|
be67a038982588a6ac9cbc2d36f009e8
|
function varargout=jdqz(varargin)
%JDQZ computes a partial generalized Schur decomposition (or QZ
% decomposition) of a pair of square matrices or operators.
%
% LAMBDA=JDQZ(A,B) and JDQZ(A,B) return K eigenvalues of the matrix pair
% (A,B), where K=min(5,N) and N=size(A,1) if K has not been specified.
%
% [X,JORDAN]=JDQZ(A,B) returns the eigenvectors X and the Jordan
% structure JORDAN: A*X=B*X*JORDAN. The diagonal of JORDAN contains the
% eigenvalues: LAMBDA=DIAG(JORDAN). JORDAN is an K by K matrix with the
% eigenvalues on the diagonal and zero or one on the first upper diagonal
% elements. The other entries are zero.
%
% [X,JORDAN,HISTORY]=JDQZ(A,B) returns also the convergence history.
%
% [X,JORDAN,Q,Z,S,T,HISTORY]=JDQZ(A,B)
% If between four and seven output arguments are required, then Q and Z
% are N by K orthonormal, S and T are K by K upper triangular such that
% they form a partial generalized Schur decomposition: A*Q=Z*S and
% B*Q=Z*T. Then LAMBDA=DIAG(S)./DIAG(T) and X=Q*Y with Y the eigenvectors
% of the pair (S,T): S*Y=T*Y*JORDAN (see also OPTIONS.Schur).
%
% JDQZ(A,B)
% JDQZ('Afun','Bfun')
% The first input argument is either a square matrix (which can be full
% or sparse, symmetric or nonsymmetric, real or complex), or a string
% containing the name of an M-file which applies a linear operator to the
% columns of a given matrix. In the latter case, the M-file, say Afun.m,
% must return the dimension N of the problem with N = Afun([],'dimension').
% For example, JDQZ('fft',...) is much faster than JDQZ(F,...), where F is
% the explicit FFT matrix.
% If another input argument is a square N by N matrix or the name of an
% M-file, then B is this argument (regardless whether A is an M-file or a
% matrix). If B has not been specified, then B is assumed to be the
% identity unless A is an M-file with two output vectors of dimension N
% with [AV,BV]=Afun(V), or with AV=Afun(V,'A') and BV=Afun(V,'B').
%
% The remaining input arguments are optional and can be given in
% practically any order:
%
% [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ(A,B,K,SIGMA,OPTIONS)
% [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ('Afun','Bfun',K,SIGMA,OPTIONS)
%
% where
%
% K an integer, the number of desired eigenvalues.
% SIGMA a scalar shift or a two letter string.
% OPTIONS a structure containing additional parameters.
%
% If K is not specified, then K = MIN(N,5) eigenvalues are computed.
%
% If SIGMA is not specified, then the Kth eigenvalues largest in
% magnitude are computed. If SIGMA is a real or complex scalar, then the
% Kth eigenvalues nearest SIGMA are computed. If SIGMA is column vector
% of size (L,1), then the Jth eigenvalue nearest to SIGMA(MIN(J,L))
% is computed for J=1:K. SIGMA is the "target" for the desired eigenvalues.
% If SIGMA is one of the following strings, then it specifies the desired
% eigenvalues.
%
% SIGMA Specified eigenvalues
%
% 'LM' Largest Magnitude
% 'SM' Smallest Magnitude (same as SIGMA = 0)
% 'LR' Largest Real part
% 'SR' Smallest Real part
% 'BE' Both Ends. Computes K/2 eigenvalues
% from each end of the spectrum (one more
% from the high end if K is odd.)
%
% If 'TestSpace' is 'Harmonic' (see OPTIONS), then SIGMA = 0 is the
% default, otherwise SIGMA = 'LM' is the default.
%
%
% The OPTIONS structure specifies certain parameters in the algorithm.
%
% Field name Parameter Default
%
% OPTIONS.Tol Convergence tolerance: 1e-8
% norm(r) <= Tol/SQRT(K)
% OPTIONS.jmin Minimum dimension search subspace V K+5
% OPTIONS.jmax Maximum dimension search subspace V jmin+5
% OPTIONS.MaxIt Maximum number of iterations. 100
% OPTIONS.v0 Starting space ones+0.1*rand
% OPTIONS.Schur Gives schur decomposition 'no'
% If 'yes', then X and JORDAN are
% not computed and [Q,Z,S,T,HISTORY]
% is the list of output arguments.
% OPTIONS.TestSpace Defines the test subspace W 'Harmonic'
% 'Standard': W=sigma*A*V+B*V
% 'Harmonic': W=A*V-sigma*B*V
% 'SearchSpace': W=V
% W=V is justified if B is positive
% definite.
% OPTIONS.Disp Shows size of intermediate residuals 'no'
% and the convergence history
% OPTIONS.NSigma Take as target for the second and 'no'
% following eigenvalues, the best
% approximate eigenvalues from the
% test subspace.
% OPTIONS.Pairs Search for conjugated eigenpairs 'no'
% OPTIONS.LSolver Linear solver 'GMRES'
% OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,..
% OPTIONS.LS_MaxIt Maximum number it. linear solver 5
% OPTIONS.LS_ell ell for BiCGstab(ell) 4
% OPTIONS.Precond Preconditioner (see below) identity.
% OPTIONS.Type_Precond Way of using preconditioner 'left'
%
% For instance
%
% options=struct('Tol',1.0e-8,'LSolver','BiCGstab','LS_ell',4,'Precond',M);
%
% changes the convergence tolerance to 1.0e-8, takes BiCGstab as linear
% solver, and takes M as preconditioner (for ways of defining M, see below).
%
%
% PRECONDITIONING. The action M-inverse of the preconditioner M (an
% approximation of A-lamda*B) on an N-vector V can be defined in the
% OPTIONS
%
% OPTIONS.Precond
% OPTIONS.L_Precond same as OPTIONS.Precond
% OPTIONS.U_Precond
% OPTIONS.P_Precond
%
% If no preconditioner has been specified (or is []), then M\V=V (M is
% the identity).
% If Precond is an N by N matrix, say, K, then
% M\V = K\V.
% If Precond is an N by 2*N matrix, say, K, then
% M\V = U\L\V, where K=[L,U], and L and U are N by N matrices.
% If Precond is a string, say, 'Mi', then
% if Mi(V,'L') and Mi(V,'U') return N-vectors
% M\V = Mi(Mi(V,'L'),'U')
% otherwise
% M\V = Mi(V) or M\V=Mi(V,'preconditioner').
% Note that Precond and A can be the same string.
% If L_Precond and U_Precond are strings, say, 'Li' and 'Ui',
% respectively, then
% M\V=Ui(Li(V)).
% If (P_precond,) L_Precond, and U_precond are N by N matrices, say,
% (P,) L, and U, respectively, then
% M\V=U\L\(P*V) (P*M=L*U)
%
% OPTIONS.Type_Precond
% The preconditioner can be used as explicit left preconditioner
% ('left', default), as explicit right preconditioner ('right') or
% implicitly ('impl').
%
%
% JDQZ without input arguments returns the options and its defaults.
%
% Gerard Sleijpen.
% Copyright (c) 2002
%
%
% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology
global Qschur Zschur Sschur Tschur ...
Operator_MVs Precond_Solves ...
MinvZ QastMinvZ
if nargin==0
possibilities, return,
end
%%% Read/set parameters
[n,nselect,Sigma,kappa,SCHUR,...
jmin,jmax,tol0,maxit,V,AV,BV,TS,DISP,PAIRS,JDV0,FIX_tol,track,NSIGMA,...
lsolver,LSpar] = ReadOptions(varargin{1:nargin});
Qschur = zeros(n,0); Zschur=zeros(n,0);;
MinvZ = zeros(n,0); QastMinvZ=zeros(0,0);
Sschur = []; Tschur=[]; history = [];
%%% Return if eigenvalueproblem is trivial
if n<2
if n==1, Qschur=1; Zschur=1; [Sschur,Tschur]=MV(1); end
if nargout == 0, Lambda=Sschur/Tschur, else
[varargout{1:nargout}]=output(history,SCHUR,1,Sschur/Tschur); end,
return, end
%---------- SET PARAMETERS & STRINGS FOR OUTPUT -------------------------
if TS==0, testspace='sigma(1)''*Av+sigma(2)''*Bv';
elseif TS==1, testspace='sigma(2)*Av-sigma(1)*Bv';
elseif TS==2, testspace='v';
elseif TS==3, testspace='Bv';
elseif TS==4, testspace='Av';
end
String=['\r#it=%i #MV=%3i, dim(V)=%2i, |r_%2i|=%6.1e '];
%------------------- JDQZ -----------------------------------------------
% fprintf('Scaling with kappa=%6.4g.',kappa)
k=0; nt=0; j=size(V,2); nSigma=size(Sigma,1);
it=0; extra=0; Zero=[]; target=[]; tol=tol0/sqrt(nselect);
INITIATE=1; JDV=0;
rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0;
time=clock;
if TS ~=2
while (k<nselect & it<maxit)
%%% Initialize target, test space and interaction matrices
if INITIATE, % set new target
nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0;
if j<2
[V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol);
rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[];
j=min(jmin,n-k);
end
if DETECTED & NSIGMA
[Ur,Ul,St,Tt] = SortQZ(WAV,WBV,sigma,kappa);
y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y;
[r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa);
sigma=ScaleEig(theta);
USE_OLD=NSIGMA; rKNOWN=1; lit=10;
end
NEWSHIFT= 1;
if DETECTED & TS<2, NEWSHIFT= ~min(target==sigma); end
target=sigma; ttarget=sigma;
if ischar(ttarget), ttrack=0; else, ttrack=track; end
if NEWSHIFT
v=V; Av=AV; Bv=BV; W=eval(testspace);
%%% V=RepGS(Qschur,V); [AV,BV]=MV(V); %%% more stability??
%%% W=RepGS(Zschur,eval(testspace)); %%% dangerous if sigma~lambda
if USE_OLD, W(:,1)=V(:,1); end,
W=RepGS(Zschur,W); WAV=W'*AV; WBV=W'*BV;
end
INITIATE=0; DETECTED=0; JDV=0;
end % if INITIATE
%%% Solve the preconditioned correction equation
if rKNOWN,
if JDV, z=W; q=V; extra=extra+1;
if DISP, fprintf(' %2i-d proj.\n',k+j-1), end
end
if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end
t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit);
nlit=nlit+1; lit=lit+1; it=it+1;
EXPAND=1; rKNOWN=0; JDV=0;
end % if rKNOWN
%%% Expand the subspaces and the interaction matrices
if EXPAND
[v,zeta]=RepGS([Qschur,V],t);
V=[V,v];
[Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv];
w=eval(testspace); w=RepGS([Zschur,W],w);
WAV=[WAV,W'*Av;w'*AV]; WBV=[WBV,W'*Bv;w'*BV]; W=[W,w];
j=j+1; EXPAND=0;
%%% Check for stagnation
if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end
end % if EXPAND
%%% Solve projected eigenproblem
if USE_OLD
[Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,y);
else
[Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin);
end
%%% Compute approximate eigenpair and residual
y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y;
[r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa);
%%%=== an alternative, but less stable way of computing z =====
% beta=Tt(1,1); alpha=St(1,1); theta=[alpha,beta];
% r=RepGS(Zschur,beta*Av-alpha*Bv,0); nr=norm(r); z=W*Ul(:,1);
rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end
if DISP, %%% display history
fprintf(String,it,Operator_MVs,j,nlit,nr),
end
history=[history;nr,it,Operator_MVs]; %%% save history
%%% check convergence
if (nr<tol)
%%% EXPAND Schur form
Qschur=[Qschur,q]; Zschur=[Zschur,z];
Sschur=[[Sschur;zeros(1,k)],Zschur'*Av];
Tschur=[[Tschur;zeros(1,k)],Zschur'*Bv]; Zero=[Zero,0];
k=k+1;
if ischar(target), Target(k,:)=[nt,0,0];
else, Target(k,:)=[0,target]; end
if DISP, ShowEig(theta,target,k); end
if (k>=nselect), break; end;
%%% Expand preconditioned Schur matrix MinvZ=M\Zschur
UpdateMinvZ;
J=[2:j]; j=j-1; Ur=Ur(:,J); Ul=Ul(:,J);
V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul;
WAV=St(J,J); WBV=Tt(J,J);
rKNOWN=0; DETECTED=1; USE_OLD=0;
%%% check for conjugate pair
if PAIRS & (abs(imag(theta(1)/theta(2)))>tol)
t=ImagVector(q); % t=conj(q); t=t-q*(q'*t);
if norm(t)>tol, t=RepGS([Qschur,V],t,0);
if norm(t)>200*tol
target=ScaleEig(conj(theta));
EXPAND=1; DETECTED=0;
if DISP, fprintf('--- Checking for conjugate pair ---\n'), end
end
end
end
INITIATE = ( j==0 & DETECTED);
elseif DETECTED %%% To detect whether another eigenpair is accurate enough
INITIATE=1;
end % if (nr<tol)
%%% restart if dim(V)> jmax
if j==jmax
j=jmin; J=[1:j];
Ur=Ur(:,J); Ul=Ul(:,J);
V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul;
WAV=St(J,J); WBV=Tt(J,J);
end % if j==jmax
end % while k
end % if TS~=2
if TS==2
Q0=Qschur; ZastQ=[];
% WAV=V'*AV; WBV=V'*BV;
while (k<nselect & it<maxit)
%%% Initialize target, test space and interaction matrices
if INITIATE & ( nSigma>k | NSIGMA), % set new target
nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0;
if j<2
[V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol);
rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[];
j=min(jmin,n-k);;
end
if DETECTED & NSIGMA
[Ur,Ul,St,Tt]=SortQZ(WAV,WBV,sigma,kappa,1);
q=RepGS(Zschur,V*Ur(:,1)); [Av,Bv]=MV(q);
[r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa);
sigma=ScaleEig(theta);
USE_OLD=NSIGMA; rKNOWN=1; lit=10;
end
target=sigma; ttarget=sigma;
if ischar(ttarget), ttrack=0; else, ttrack=track; end
if ~DETECTED
%%% additional stabilisation. May not be needed
%%% V=RepGS(Zschur,V); [AV,BV]=MV(V);
%%% end add. stab.
WAV=V'*AV; WBV=V'*BV;
end
DETECTED=0; INITIATE=0; JDV=0;
end % if INITIATE
%%% Solve the preconditioned correction equation
if rKNOWN,
if JDV, z=V; q=V; extra=extra+1;
if DISP, fprintf(' %2i-d proj.\n',k+j-1), end
end
if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end
t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit);
nlit=nlit+1; lit=lit+1; it=it+1;
EXPAND=1; rKNOWN=0; JDV=0;
end % if rKNOWN
%%% expand the subspaces and the interaction matrices
if EXPAND
[v,zeta]=RepGS([Zschur,V],t); [Av,Bv]=MV(v);
WAV=[WAV,V'*Av;v'*AV,v'*Av]; WBV=[WBV,V'*Bv;v'*BV,v'*Bv];
V=[V,v]; AV=[AV,Av]; BV=[BV,Bv];
j=j+1; EXPAND=0;
%%% Check for stagnation
if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end
end % if EXPAND
%%% compute approximate eigenpair
if USE_OLD
[Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,Ur(:,1));
else
[Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin);
end
%%% Compute approximate eigenpair and residual
q=V*Ur(:,1); Av=AV*Ur(:,1); Bv=BV*Ur(:,1);
[r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa);
rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end
if DISP, %%% display history
fprintf(String,it,Operator_MVs, j,nlit,nr),
end
history=[history;nr,it,Operator_MVs]; %%% save history
%%% check convergence
if (nr<tol)
%%% expand Schur form
[q,a]=RepGS(Q0,q); a1=a(k+1,1); a=a(1:k,1);
%%% ZastQ=Z'*Q0
Q0=[Q0,q]; %%% the final Qschur
ZastQ=[ZastQ,Zschur'*q;z'*Q0]; Zschur=[Zschur,z]; Qschur=[Qschur,z];
Sschur=[[Sschur;Zero],a1\(Zschur'*Av-[Sschur*a;0])];
Tschur=[[Tschur;Zero],a1\(Zschur'*Bv-[Tschur*a;0])]; Zero=[Zero,0];
k=k+1;
if ischar(target), Target(k,:)=[nt,0,0];
else, Target(k,:)=[0,target]; end
if DISP, ShowEig(theta,target,k); end
if (k>=nselect), break; end;
UpdateMinvZ;
J=[2:j]; j=j-1; rKNOWN=0; DETECTED=1;
Ul=Ul(:,J);
V=V*Ul; AV=AV*Ul; BV=BV*Ul;
WAV=Ul'*WAV*Ul; WBV=Ul'*WBV*Ul;
Ul=eye(j); Ur=Ul;
%%% check for conjugate pair
if PAIRS & (abs(imag(theta(2)/theta(1)))>tol)
t=ImagVector(q);
if norm(t)>tol,
%%% t perp Zschur, t in span(Q0,imag(q))
t=t-Q0*(ZastQ\(Zschur'*t));
if norm(t)>100*tol
target=ScaleEig(conj(theta));
EXPAND=1; DETECTED=0; USE_OLD=0;
if DISP, fprintf('--- Checking for conjugate pair ---\n'), end
end
end
end
INITIATE = ( j==0 & DETECTED);
elseif DETECTED %%% To detect whether another eigenpair is accurate enough
INITIATE=1;
end % if (nr<tol)
%%% restart if dim(V)> jmax
if j==jmax
j=jmin; J=[1:j];
Ur=Ur(:,J);
V=V*Ur; AV=AV*Ur; BV=BV*Ur;
WAV=Ur'*WAV*Ur; WBV=Ur'*WBV*Ur;
Ur=eye(j);
end % if jmax
end % while k
Qschur=Q0;
end
time_needed=etime(clock,time);
if JDV0 & extra>0 & DISP
fprintf('\n\n# j-dim. proj.: %2i\n\n',extra)
end
I=CheckSortSchur(Sigma,kappa); Target(1:length(I),:)=Target(I,:);
XKNOWN=0;
if nargout == 0
if ~DISP
eigenvalues=diag(Sschur)./diag(Tschur)
% Result(eigenvalues)
return, end
else
Jordan=[]; X=zeros(n,0);
if SCHUR ~= 1
if k>0
[Z,D,Jor]=FindJordan(Sschur,Tschur,SCHUR);
DT=abs(diag(D)); DS=abs(diag(Jor));
JT=find(DT<=tol & DS>tol); JS=find(DS<=tol & DT<=tol);
msg=''; DT=~isempty(JT); DS=~isempty(JS);
if DT
msg1='The eigenvalues'; msg2=sprintf(', %i',JT);
msg=[msg1,msg2,' are numerically ''Inf'''];
end,
if DS
msg1='The pencil is numerically degenerated in the directions';
msg2=sprintf(', %i',JS);
if DT, msg=[msg,sprintf('\n\n')]; end, msg=[msg,msg1,msg2,'.'];
end,
if (DT | DS), warndlg(msg,'Unreliable directions'), end
Jordan=Jor/D; X=Qschur*Z; XKNOWN=1;
end
end
[varargout{1:nargout}]=output(history,SCHUR,X,Jordan);
end
%-------------- display results -----------------------------------------
if DISP & size(history,1)>0
rs=history(:,1); mrs=max(rs);
if mrs>0, rs=rs+0.1*eps*mrs;
subplot(2,1,1); t=history(:,2);
plot(t,log10(rs),'*-',t,log10(tol)+0*t,':')
legend('log_{10} || r_{#it} ||_2')
String=sprintf('The test subspace is computed as %s.',testspace);
title(String)
subplot(2,1,2); t=history(:,3);
plot(t,log10(rs),'-*',t,log10(tol)+0*t,':')
legend('log_{10} || r_{#MV} ||_2')
String=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',...
jmin,jmax,tol);
title(String)
String=sprintf('Correction equation solved with %s.',lsolver);
xlabel(String),
date=fix(clock);
String=sprintf('%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6));
ax=axis; text(0.2*ax(1)+0.8*ax(2),1.2*ax(3)-0.2*ax(4),String)
drawnow
end
Result(Sigma,Target,diag(Sschur),diag(Tschur),tol)
end
%------------------------ TEST ACCURACY ---------------------------------
if k>nselect & DISP
fprintf('\n%i additional eigenpairs have been detected.\n',k-nselect)
end
if k<nselect & DISP
fprintf('\nFailed to detect %i eigenpairs.\n',nselect-k)
end
if (k>0) & DISP
Str='time_needed'; texttest(Str,eval(Str))
fprintf('\n%39s: %9i','Number of Operator actions',Operator_MVs)
if Precond_Solves
fprintf('\n%39s: %9i','Number of preconditioner solves',Precond_Solves)
end
if 1
if SCHUR ~= 1 & XKNOWN
% Str='norm(Sschur*Z-Tschur*Z*Jordan)'; texttest(Str,eval(Str),tol0)
ok=1; eval('[AX,BX]=MV(X);','ok=0;')
if ~ok, for j=1:size(X,2), [AX(:,j),BX(:,j)]=MV(X(:,j)); end, end
Str='norm(AX*D-BX*Jor)'; texttest(Str,eval(Str),tol0)
end
ok=1; eval('[AQ,BQ]=MV(Qschur);','ok=0;')
if ~ok, for j=1:size(Qschur,2), [AQ(:,j),BQ(:,j)]=MV(Qschur(:,j)); end, end
if kappa == 1
Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str),tol0)
else
Str='norm(AQ-Zschur*Sschur)/kappa'; texttest(Str,eval(Str),tol0)
end
Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str),tol0)
I=eye(k);
Str='norm(Qschur''*Qschur-I)'; texttest(Str,eval(Str))
Str='norm(Zschur''*Zschur-I)'; texttest(Str,eval(Str))
nrmSschur=max(norm(Sschur),1.e-8);
nrmTschur=max(norm(Tschur),1.e-8);
Str='norm(tril(Sschur,-1))/nrmSschur'; texttest(Str,eval(Str))
Str='norm(tril(Tschur,-1))/nrmTschur'; texttest(Str,eval(Str))
end
fprintf('\n==================================================\n')
end
if k==0
disp('no eigenvalue could be detected with the required precision')
end
return
%%%======== END JDQZ ====================================================
%%%======================================================================
%%%======== PREPROCESSING ===============================================
%%%======================================================================
%%%======== ARNOLDI (for initial spaces) ================================
function [V,AV,BV]=Arnoldi(v,Av,Bv,sigma,jmin,nselect,tol)
% Apply Arnoldi with M\(A*sigma(1)'+B*sigma(2)'), to construct an
% initial search subspace
%
global Qschur
if ischar(sigma), sigma=[0,1]; end
[n,j]=size(v); k=size(Qschur,2); jmin=min(jmin,n-k);
if j==0 & k>0
v=RepGS(Qschur,rand(n,1)); [Av,Bv]=MV(v); j=1;
end
V=v; AV=Av; BV=Bv;
while j<jmin;
v=[Av,Bv]*sigma';
v0=SolvePrecond(v);
if sigma(1)==0 & norm(v0-v)<tol,
%%%% then precond=I and target = 0: apply Arnoldi with A
sigma=[1,0]; v0=Av;
end
v=RepGS([Qschur,V],v0); V=[V,v];
[Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv]; j=j+1;
end % while
return
%%%======== END ARNOLDI =================================================
%%%======================================================================
%%%======== POSTPROCESSING ==============================================
%%%======================================================================
%%%======== SORT QZ DECOMPOSITION INTERACTION MATRICES ==================
function I=CheckSortSchur(Sigma,kappa)
% I=CheckSortSchur(Sigma)
% Scales Qschur, Sschur, and Tschur such that diag(Tschur) in [0,1]
% Reorders the Partial Schur decomposition such that the `eigenvalues'
% (diag(S),diag(T)) appear in increasing chordal distance w.r.t. to
% Sigma.
% If diag(T) is non-singular then Lambda=diag(S)./diag(T) are the
% eigenvalues.
global Qschur Zschur Sschur Tschur
k=size(Sschur,1); if k==0, I=[]; return, end
% [AQ,BQ]=MV(Qschur);
% Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str))
% Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str))
%--- scale such that diag(Tschur) in [0,1] ----
[Tschur,D]=ScaleT(Tschur); Sschur=D\Sschur;
% kappa=max(norm(Sschur,inf)/norm(Tschur,inf),1);
s=diag(Sschur); t=diag(Tschur);
I=(1:k)'; l=size(Sigma,1);
for j=1:k
J0=(j:k)';
J=SortEig(s(I(J0)),t(I(J0)),Sigma(min(j,l),:),kappa);
I(J0)=I(J0(J));
end
if ~min((1:k)'==I)
[Q,Z,Sschur,Tschur]=SwapQZ(eye(k),eye(k),Sschur,Tschur,I);
[Tschur,D2]=ScaleT(Tschur); Sschur=D2\Sschur;
Qschur=Qschur*Q; Zschur=Zschur*(D*Z*D2);
else
Zschur=Zschur*D;
end
return
%========================================================================
function [T,D]=ScaleT(T)
% scale such that diag(T) in [0,1] ----
n=sign(diag(T)); n=n+(n==0); D=diag(n);
T=D\T; IT=imag(T); RT=real(T);
T=RT+IT.*(abs(IT)>eps*abs(RT))*sqrt(-1);
return
%%%======== COMPUTE SORTED JORDAN FORM ==================================
function [X,D,Jor]=FindJordan(S,T,SCHUR)
% [X,D,J]=FINDJORDAN(S,T)
% For S and T k by k upper triangular matrices
% FINDJORDAN computes the Jordan decomposition.
% X is a k by k matrix of eigenvectors and principal vectors
% D and J are k by matrices, D is diagonal, J is Jordan
% such that S*X*D=T*X*J. (diag(D),diag(J)) are the eigenvalues.
% If D is non-singular then Lambda=diag(J)./diag(D)
% are the eigenvalues.
% coded by Gerard Sleijpen, May, 2002
k=size(S,1);
s=diag(S); t=diag(T); n=sign(t); n=n+(n==0);
D=sqrt(conj(s).*s+conj(t).*t).*n;
S=diag(D)\S; T=diag(D)\T; D=diag(diag(T));
if k<1,
if k==0, X=[]; D=[]; Jor=[]; end
if k==1, X=1; Jor=s; end
return
end
tol=k*(norm(S,1)+norm(T,1))*eps;
[X,Jor,I]=PseudoJordan(S,T,tol);
if SCHUR == 0
for l=1:length(I)-1
if I(l)<I(l+1)-1,
J=[I(l):I(l+1)-1];
[U,JJor]=JordanBlock(Jor(J,J),tol);
X(:,J)=X(:,J)*U; Jor(J,J)=JJor;
end
end
end
Jor=Jor+diag(diag(S)); Jor=Jor.*(abs(Jor)>tol);
return
%==================================================
function [X,Jor,J]=PseudoJordan(S,T,delta)
% Computes a pseudo-Jordan decomposition for the upper triangular
% matrices S and T with ordered diagonal elements.
% S*X*(diag(diag(T)))=T*X*(diag(diag(S))+Jor)
% with X(:,i:j) orthonormal if its
% columns span an invariant subspace of (S,T).
k=size(S,1); s=diag(S); t=diag(T);
Jor=zeros(k); X=eye(k); J=1;
for i=2:k
I=[1:i];
C=t(i,1)*S(I,I)-s(i,1)*T(I,I); C(i,i)=norm(C,inf);
if C(i,i)>0
tol=delta*C(i,i);
for j=i:-1:1
if j==1 | abs(C(j-1,j-1))>tol, break; end
end
e=zeros(i,1); e(i,1)=1;
if j==i
J=[J,i]; q=C\e; X(I,i)=q/norm(q);
else
q=X(I,j:i-1);
q=[C,T(I,I)*q;q',zeros(i-j)]\[e;zeros(i-j,1)];
q=q/norm(q(I,1)); X(I,i)=q(I,1);
Jor(j:i-1,i)=-q(i+1:2*i-j,1);
end
end
end
J=[J,k+1];
return
%==================================================
function [X,Jor,U]=JordanBlock(A,tol)
% If A is nilpotent, then A*X=X*Jor with
% Jor a Jordan block
%
k=size(A,1); Id=eye(k);
U=Id; aa=A; j=k; jj=[]; J=1:k;
while j>0
[u,s,v]=svd(aa); U(:,J)=U(:,J)*v;
sigma=diag(s); delta=tol;
J=find(sigma<delta);
if isempty(J),j=0; else, j=min(J)-1; end
jj=[jj,j]; if j==0, break, end
aa=v'*u*s; J=1:j; aa=aa(J,J);
end
Jor=U'*A*U; Jor=Jor.*(abs(Jor)>tol);
l=length(jj); jj=[jj(l:-1:1),k];
l2=jj(2)-jj(1); J=jj(1)+(1:l2);
JX=Id(:,J); X=Id;
for j=2:l
l1=l2+1; l2=jj(j+1)-jj(j);
J2=l1:l2; J=jj(j)+(1:l2);
JX=Jor*JX; D=diag(sqrt(diag(JX'*JX))); JX=JX/D;
[Q,S,V]=svd(JX(J,:));
JX=[JX,Id(:,J)*Q(:,J2)]; X(:,J)=JX;
end
J=[];
for i=1:l2
for k=l:-1:1
j=jj(k)+i; if j<=jj(k+1), J=[J,j]; end
end
end
X=X(:,J); Jor=X\(Jor*X); X=U*X;
Jor=Jor.*(abs(Jor)>100*tol);
return
%%%======== END JORDAN FORM =============================================
%%%======== OUTPUT ======================================================
function varargout=output(history,SCHUR,X,Lambda)
global Qschur Zschur Sschur Tschur
if nargout == 1, varargout{1}=diag(Sschur)./diag(Tschur); return, end
if nargout > 2, varargout{nargout}=history; end
if nargout < 6 & SCHUR == 1
if nargout >1, varargout{1}=Qschur; varargout{2}=Zschur; end
if nargout >2, varargout{3}=Sschur; end
if nargout >3, varargout{4}=Tschur; end
end
%-------------- compute eigenpairs --------------------------------------
if SCHUR ~= 1
varargout{1}=X; varargout{2}=Lambda;
if nargout >3, varargout{3}=Qschur; varargout{4}=Zschur; end
if nargout >4, varargout{5}=Sschur; end
if nargout >5, varargout{6}=Tschur; end
end
return
%%%======================================================================
%%%======== UPDATE PRECONDITIONED SCHUR VECTORS =========================
%%%======================================================================
function UpdateMinvZ
global Qschur Zschur MinvZ QastMinvZ
[n,k]=size(Qschur);
if k==1, MinvZ=zeros(n,0); QastMinvZ = []; end
Minv_z=SolvePrecond(Zschur(:,k));
QastMinvZ=[[QastMinvZ;Qschur(:,k)'*MinvZ],Qschur'*Minv_z];
MinvZ=[MinvZ,Minv_z];
return
%%%======================================================================
%%%======== SOLVE CORRECTION EQUATION ===================================
%%%======================================================================
function [t,xtol]=SolvePCE(theta,q,z,r,lsolver,par,nit)
global Qschur Zschur
Q=[Qschur,q]; Z=[Zschur,z];
switch lsolver
case 'exact'
[t,xtol] = exact(theta,Q,Z,r);
case {'gmres','cgstab','olsen'}
[MZ,QMZ]=FormPM(q,z);
%%% solve preconditioned system
[t,xtol] = feval(lsolver,theta,Q,Z,MZ,QMZ,r,spar(par,nit));
end
return
%------------------------------------------------------------------------
function [MZ,QMZ]=FormPM(q,z)
% compute vectors and matrices for skew projection
global Qschur MinvZ QastMinvZ
Minv_z=SolvePrecond(z);
QMZ=[QastMinvZ,Qschur'*Minv_z;q'*MinvZ,q'*Minv_z];
MZ=[MinvZ,Minv_z];
return
%%%======================================================================
%%%======== LINEAR SOLVERS ==============================================
%%%======================================================================
function [x,xtol] = exact(theta,Q,Z,r)
% produces the exact solution if matrices are given
% Is only feasible for low dimensional matrices
% Only of interest for experimental purposes
%
global Operator_A Operator_B
n=size(r,1);
if ischar(Operator_A)
[MZ,QMZ]=FormPM(Q(:,end),Z(:,end));
if n>200
[x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'cgstab',[1.0e-10,500,4]);
else
[x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'gmres',[1.0e-10,100]);
end
return
end
k=size(Q,2);
Aug=[theta(2)*Operator_A-theta(1)*Operator_B,Z;Q',zeros(k,k)];
x=Aug\[r;zeros(k,1)]; x([n+1:n+k],:)=[]; xtol=1;
% L=eig(full(Aug)); plot(real(L),imag(L),'*'), pause
%%% [At,Bt]=MV(x); At=theta(2)*At-theta(1)*Bt;
%%% xtol=norm(r-At+Z*(Z'*At))/norm(r);
return
%%%===== Iterative methods ==============================================
function [r,xtol] = olsen(theta,Q,Z,MZ,M,r,par)
% returns the preconditioned residual as approximate solution
% May be sufficient in case of an excellent preconditioner
r=SkewProj(Q,MZ,M,SolvePrecond(r)); xtol=0;
return
%------------------------------------------------------------------------
function [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par)
% BiCGstab(ell) with preconditioning
% [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=r
% where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q').
% using (I-MZ*(M\Q'))*inv(K) as preconditioner
%
% This function is specialized for use in JDQZ.
% integer nmv: number of matrix multiplications
% rnrm: relative residual norm
%
% par=[tol,mxmv,ell] where
% integer m: max number of iteration steps
% real tol: residual reduction
%
% rnrm: obtained residual reduction
%
% -- References: ETNA
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization --
%
global Precond_Type
tol=par(1); max_it=par(2); l=par(3); n=size(r,1);
rnrm=1; nmv=0;
if max_it < 2 | tol>=1, x=r; return, end
%%% 0 step of bicgstab eq. 1 step of bicgstab
%%% Then x is a multiple of b
TP=Precond_Type;
if TP==0, r=SkewProj(Q,MZ,M,SolvePrecond(r)); tr=r;
else, tr=RepGS(Z,r); end
rnrm=norm(r); snrm=rnrm; tol=tol*snrm;
sigma=1; omega=1;
x=zeros(n,1); u=zeros(n,1);
J1=2:l+1;
%%% HIST=[0,1];
if TP <2 %% explicit preconditioning
% -- Iteration loop
while (nmv < max_it)
sigma=-omega*sigma;
for j = 1:l,
rho=tr'*r(:,j); bet=rho/sigma;
u=r-bet*u;
u(:,j+1)=PreMV(theta,Q,MZ,M,u(:,j));
sigma=tr'*u(:,j+1); alp=rho/sigma;
r=r-alp*u(:,2:j+1);
r(:,j+1)=PreMV(theta,Q,MZ,M,r(:,j));
x=x+alp*u(:,1);
G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1));
if rnrm<tol, l=j; J1=2:l+1; r=r(:,1:l+1); break, end
end
nmv = nmv+2*l;
for i=2:l+1
G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)';
end
if TP, g=Z'*r; G=G-g'*g; end
d=G(J1,1); gamma=G(J1,J1)\d;
rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space
%%% HIST=[HIST;[nmv,rnrm/snrm]];
x=x+r(:,1:l)*gamma;
if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u
omega=gamma(l,1); gamma=[1;-gamma];
u=u*gamma; r=r*gamma;
if TP, g=g*gamma; r=r-Z*g; end
% rnrm = norm(r);
end
else %% implicit preconditioning
I=eye(2*l); v0=I(:,1:l); s0=I(:,l+1:2*l);
y0=zeros(2*l,1); V=zeros(n,2*l);
while (nmv < max_it)
sigma=-omega*sigma;
y=y0; v=v0; s=s0;
for j = 1:l,
rho=tr'*r(:,j); bet=rho/sigma;
u=r-bet*u;
if j>1, %%% collect the updates for x in l-space
v(:,1:j-1)=s(:,1:j-1)-bet*v(:,1:j-1);
end
[u(:,j+1),V(:,j)]=PreMV(theta,Q,MZ,M,u(:,j));
sigma=tr'*u(:,j+1); alp=rho/sigma;
r=r-alp*u(:,2:j+1);
if j>1,
s(:,1:j-1)=s(:,1:j-1)-alp*v(:,2:j);
end
[r(:,j+1),V(:,l+j)]=PreMV(theta,Q,MZ,M,r(:,j));
y=y+alp*v(:,1);
G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1));
if rnrm<tol, l=j; J1=2:l+1; s=s(:,1:l); break, end
end
nmv = nmv+2*l;
for i=2:l+1
G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)';
end
g=Z'*r; G=G-g'*g; %%% but, do the orth to Z implicitly
d=G(J1,1); gamma=G(J1,J1)\d;
rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space
x=x+V*(y+s*gamma);
%%% HIST=[HIST;[nmv,rnrm/snrm]];
if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u
omega=gamma(l,1); gamma=[1;-gamma];
u=u*gamma; r=r*gamma;
g=g*gamma; r=r-Z*g; %%% Do the orth to Z explicitly
%%% In exact arithmetic not needed, but
%%% appears to be more stable.
end
end
if TP==1, x=SkewProj(Q,MZ,M,SolvePrecond(x)); end
rnrm = rnrm/snrm;
%%% plot(HIST(:,1),log10(HIST(:,2)+eps),'*'), drawnow
return
%----------------------------------------------------------------------
function [v,rnrm] = gmres0(theta,Q,Z,MZ,M,v,par)
% GMRES
% [x,rnrm] = gmres(theta,Q,Z,MZ,M,v,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=b
% where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q').
% using (I-MZ*(M\Q'))*inv(K) as preconditioner
%
% If used as implicit preconditioner then FGMRES.
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% rnrm: obtained residual reduction
%
% -- References: Saad & Schultz SISC 1986
% Gerard Sleijpen ([email protected])
% Copyright (c) 1998, Gerard Sleijpen
% -- Initialization
global Precond_Type
tol=par(1); max_it=par(2); n = size(v,1);
rnrm = 1; j=0;
if max_it < 2 | tol>=1, return, end
%%% 0 step of gmres eq. 1 step of gmres
%%% Then x is a multiple of b
H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)];
TP=Precond_Type;
TP=Precond_Type;
if TP==0
v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0;
else
v=RepGS(Z,v);
end
V = [v];
tol = tol * rnrm;
y = [ rnrm ; zeros(max_it,1) ];
while (j < max_it) & (rnrm > tol),
j=j+1;
[v,w]=PreMV(theta,Q,MZ,M,v);
if TP
if TP == 2, W=[W,w]; end
v=RepGS(Z,v,0);
end
[v,h] = RepGS(V,v); H(1:size(h,1),j) = h;
V = [V, v];
for i = 1:j-1,
a = Rot(:,i);
H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j);
end
J=[j, j+1];
a=H(J,j);
if a(2) ~= 0
cs = norm(a);
a = a/cs; Rot(:,j) = a;
H(J,j) = [cs; 0];
y(J) = [a'; -a(2) a(1)]*y(J);
end
rnrm = abs(y(j+1));
end
J=[1:j];
if TP == 2
v = W(:,J)*(H(J,J)\y(J));
else
v = V(:,J)*(H(J,J)\y(J));
end
if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end
return
%%%======================================================================
function [v,rnrm] = gmres(theta,Q,Z,MZ,M,v,par)
% GMRES
% [x,nmv,rnrm] = gmres(theta,Q,Z,MZ,M,v,par)
% Computes iteratively an approximation to the solution
% of the linear system Q'*x = 0 and Atilde*x=r
% where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q').
% using (I-MZ*(M\Q'))*inv(K) as preconditioner.
%
% If used as implicit preconditioner, then FGMRES.
%
% par=[tol,m] where
% integer m: degree of the minimal residual polynomial
% real tol: residual reduction
%
% nmv: number of MV with Atilde
% rnrm: obtained residual reduction
%
% -- References: Saad
% Same as gmres0. However this variant uses MATLAB built-in functions
% slightly more efficient (see Sleijpen and van den Eshof).
%
%
% Gerard Sleijpen ([email protected])
% Copyright (c) 2002, Gerard Sleijpen
global Precond_Type
% -- Initialization
tol=par(1); max_it=par(2); n = size(v,1);
j=0;
if max_it < 2 | tol>=1, rnrm=1; return, end
%%% 0 step of gmres eq. 1 step of gmres
%%% Then x is a multiple of b
H = zeros(max_it +1,max_it); Gamma=1; rho=1;
TP=Precond_Type;
if TP==0
v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0;
else
v=RepGS(Z,v); rho0=1;
end
V = zeros(n,0); W=zeros(n,0);
tol0 = 1/(tol*tol);
%% HIST=1;
while (j < max_it) & (rho < tol0)
V=[V,v]; j=j+1;
[v,w]=PreMV(theta,Q,MZ,M,v);
if TP
if TP == 2, W=[W,w]; end
v=RepGS(Z,v,0);
end
[v,h] = RepGS(V,v);
H(1:size(h,1),j)=h; gamma=H(j+1,j);
if gamma==0, break %%% Lucky break-down
else
gamma= -Gamma*h(1:j)/gamma;
Gamma=[Gamma,gamma];
rho=rho+gamma'*gamma;
end
%% HIST=[HIST;(gamma~=0)/sqrt(rho)];
end
if gamma==0; %%% Lucky break-down
e1=zeros(j,1); e1(1)=rho0; rnrm=0;
if TP == 2
v=W*(H(1:j,1:j)\e1);
else
v=V*(H(1:j,1:j)\e1);
end
else %%% solve in least square sense
e1=zeros(j+1,1); e1(1)=rho0; rnrm=1/sqrt(rho);
if TP == 2
v=W*(H(1:j+1,1:j)\e1);
else
v=V*(H(1:j+1,1:j)\e1);
end
end
if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end
%% HIST=log10(HIST+eps); J=[0:size(HIST,1)-1]';
%% plot(J,HIST(:,1),'*'); drawnow
return
%%%======== END SOLVE CORRECTION EQUATION ===============================
%%%======================================================================
%%%======== BASIC OPERATIONS ============================================
%%%======================================================================
function [Av,Bv]=MV(v)
% [y,z]=MV(x)
% y=A*x, z=B*x
% y=MV(x,theta)
% y=(A-theta*B)*x
%
global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params
Bv=v;
switch Operator_Form
case 1 % both Operator_A and B are strings
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
Bv=feval(Operator_B,Operator_Params{:});
case 2
Operator_Params{1}=v;
[Av,Bv]=feval(Operator_A,Operator_Params{:});
case 3
Operator_Params{1}=v;
Operator_Params{2}='A';
Av=feval(Operator_A,Operator_Params{:});
Operator_Params{2}='B';
Bv=feval(Operator_A,Operator_Params{:});
case 4
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
Bv=Operator_B*v;
case 5
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
case 6
Av=Operator_A*v;
Operator_Params{1}=v;
Bv=feval(Operator_B,Operator_Params{:});
case 7
Av=Operator_A*v;
Bv=Operator_B*v;
case 8
Av=Operator_A*v;
end
Operator_MVs = Operator_MVs +size(v,2);
% [Av(1:5,1),Bv(1:5,1)], pause
return
%------------------------------------------------------------------------
function y=SolvePrecond(y);
global Precond_Form Precond_L Precond_U Precond_P Precond_Params Precond_Solves
switch Precond_Form
case 0,
case 1, Precond_Params{1}=y;
y=feval(Precond_L,Precond_Params{:});
case 2, Precond_Params{1}=y; Precond_Params{2}='preconditioner';
y=feval(Precond_L,Precond_Params{:});
case 3, Precond_Params{1}=y;
Precond_Params{1}=feval(Precond_L,Precond_Params{:});
y=feval(Precond_U,Precond_Params{:});
case 4, Precond_Params{1}=y; Precond_Params{2}='L';
Precond_Params{1}=feval(Precond_L,Precond_Params{:});
Precond_Params{2}='U';
y=feval(Precond_L,Precond_Params{:});
case 5, y=Precond_L\y;
case 6, y=Precond_U\(Precond_L\y);
case 7, y=Precond_U\(Precond_L\(Precond_P*y));
end
if Precond_Form
Precond_Solves = Precond_Solves +size(y,2);
end
%% y(1:5,1), pause
return
%------------------------------------------------------------------------
function [v,u]=PreMV(theta,Q,Z,M,v)
% v=Atilde*v
global Precond_Type
if Precond_Type
u=SkewProj(Q,Z,M,SolvePrecond(v));
[v,w]=MV(u); v=theta(2)*v-theta(1)*w;
else
[v,u]=MV(v); u=theta(2)*v-theta(1)*u;
v=SkewProj(Q,Z,M,SolvePrecond(u));
end
return
%------------------------------------------------------------------------
function r=SkewProj(Q,Z,M,r);
if ~isempty(Q),
r=r-Z*(M\(Q'*r));
end
return
%------------------------------------------------------------------------
function ppar=spar(par,nit)
k=size(par,2)-2;
ppar=par(1,k:k+2);
if k>1
if nit>k
ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k));
else
ppar(1,1)=par(1,max(nit,1));
end
end
ppar(1,1)=max(ppar(1,1),1.0e-8);
return
%------------------------------------------------------------------------
function u=ImagVector(u)
% computes "essential" imaginary part of a vector
maxu=max(u); maxu=maxu/abs(maxu); u=imag(u/maxu);
return
%------------------------------------------------------------------------
function Sigma=ScaleEig(Sigma)
%
%
n=sign(Sigma(:,2)); n=n+(n==0);
d=sqrt((Sigma.*conj(Sigma))*[1;1]).*n;
Sigma=diag(d)\Sigma;
return
%%%======== COMPUTE r AND z =============================================
function [r,z,nrm,theta]=Comp_rz(E,kappa)
%
% [r,z,nrm,theta]=Comp_rz(E)
% computes the direction r of the minimal residual,
% the left projection vector z,
% the approximate eigenvalue theta
%
% [r,z,nrm,theta]=Comp_rz(E,kappa)
% kappa is a scaling factor.
%
% coded by Gerard Sleijpen, version Januari 7, 1998
if nargin == 1
kappa=norm(E(:,1))/norm(E(:,2)); kappa=2^(round(log2(kappa)));
end
if kappa ~=1, E(:,1)=E(:,1)/kappa; end
[Q,sigma,u]=svd(E,0); %%% E*u=Q*sigma, sigma(1,1)>sigma(2,2)
r=Q(:,2); z=Q(:,1); nrm=sigma(2,2);
% nrm=nrm/sigma(1,1); nrmz=sigma(1,1)
u(1,:)=u(1,:)/kappa; theta=[-u(2,2),u(1,2)];
return
%%%======== END computation r and z =====================================
%%%======================================================================
%%%======== Orthogonalisation ===========================================
%%%======================================================================
function [V,R]=RepGS(Z,V,gamma)
%
% Orthonormalisation using repeated Gram-Schmidt
% with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion
%
% Q=RepGS(V)
% The n by k matrix V is orthonormalized, that is,
% Q is an n by k orthonormal matrix and
% the columns of Q span the same space as the columns of V
% (in fact the first j columns of Q span the same space
% as the first j columns of V for all j <= k).
%
% Q=RepGS(Z,V)
% Assuming Z is n by l orthonormal, V is orthonormalized against Z:
% [Z,Q]=RepGS([Z,V])
%
% Q=RepGS(Z,V,gamma)
% With gamma=0, V is only orthogonalized against Z
% Default gamma=1 (the same as Q=RepGS(Z,V))
%
% [Q,R]=RepGS(Z,V,gamma)
% if gamma == 1, V=[Z,Q]*R; else, V=Z*R+Q; end
% coded by Gerard Sleijpen, March, 2002
% if nargin == 1, V=Z; Z=zeros(size(V,1),0); end
if nargin <3, gamma=1; end
[n,dv]=size(V); [m,dz]=size(Z);
if gamma, l0=min(dv+dz,n); else, l0=dz; end
R=zeros(l0,dv);
if dv==0, return, end
if dz==0 & gamma==0, return, end
% if m~=n
% if m<n, Z=[Z;zeros(n-m,dz)]; end
% if m>n, V=[V;zeros(m-n,dv)]; n=m; end
% end
if (dz==0 & gamma)
j=1; l=1; J=1;
q=V(:,1); nr=norm(q); R(1,1)=nr;
while nr==0, q=rand(n,1); nr=norm(q); end, V(:,1)=q/nr;
if dv==1, return, end
else
j=0; l=0; J=[];
end
while j<dv,
j=j+1; q=V(:,j); nr_o=norm(q); nr=eps*nr_o;
if dz>0, yz=Z'*q; q=q-Z*yz; end
if l>0, y=V(:,J)'*q; q=q-V(:,J)*y; end
nr_n=norm(q);
while (nr_n<0.5*nr_o & nr_n > nr)
if dz>0, sz=Z'*q; q=q-Z*sz; yz=yz+sz; end
if l>0, s=V(:,J)'*q; q=q-V(:,J)*s; y=y+s; end
nr_o=nr_n; nr_n=norm(q);
end
if dz>0, R(1:dz,j)=yz; end
if l>0, R(dz+J,j)=y; end
if ~gamma
V(:,j)=q;
elseif l+dz<n, l=l+1;
if nr_n <= nr % expand with a random vector
% if nr_n==0
V(:,l)=RepGS([Z,V(:,J)],rand(n,1));
% else % which can be numerical noice
% V(:,l)=q/nr_n;
% end
else
V(:,l)=q/nr_n; R(dz+l,j)=nr_n;
end
J=[1:l];
end
end % while j
if gamma & l<dv, V=V(:,J); end
return
%%%======== END Orthogonalisation ======================================
%%%======================================================================
%%%======== Sorts Schur form ============================================
%%%======================================================================
function [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u)
%
% [Q,Z,S,T]=SortQZ(A,B,tau)
% A and B are k by k matrices, tau is a complex pair [alpha,beta].
% SortQZ computes the qz-decomposition of (A,B) with prescribed
% ordering: A*Q=Z*S, B*Q=Z*T;
% Q and Z are unitary k by k matrices,
% S and T are upper triangular k by k matrices.
% The ordering is as follows:
% (diag(S),diag(T)) are the eigenpairs of (A,B) ordered
% with increasing "chordal distance" w.r.t. tau.
%
% If tau is a scalar then [tau,1] is used.
% Default value for tau is tau=0, i.e., tau=[0,1].
%
% [Q,Z,S,T]=SortQZ(A,B,tau,kappa)
% kappa scales A first: A/kappa. Default kappa=1.
%
% [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma)
% Sorts the first MAX(gamma,1) elements. Default: gamma=k
%
% [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u)
% Now, with ordering such that angle u and Q(:,1) is less than 45o,
% and, except for the first pair, (diag(S),diag(T)) are
% with increasing "chordal distance" w.r.t. tau.
% If such an ordering does not exist, ordering is as without u.
%
% coded by Gerard Sleijpen, version April, 2002
k=size(A,1);
if k==1, Q=1; Z=1; S=A;T=B; return, end
kk=k-1;
if nargin < 3, tau=[0,1]; end
if nargin < 4, kappa=1; end
if nargin > 4, kk=max(1,min(gamma,k-1)); end
%% kappa=max(norm(A,inf)/max(norm(B,inf),1.e-12),1);
%% kappa=2^(round(log2(kappa)));
%%%------ compute the qz factorization -------
[S,T,Z,Q]=qz(A,B); Z=Z';
% kkappa=max(norm(A,inf),norm(B,inf));
% Str='norm(A*Q-Z*S)';texttest(Str,eval(Str))
% Str='norm(B*Q-Z*T)';texttest(Str,eval(Str))
%%%------ scale the eigenvalues --------------
t=diag(T); n=sign(t); n=n+(n==0); D=diag(n);
Q=Q/D; S=S/D; T=T/D;
%%%------ sort the eigenvalues ---------------
I=SortEig(diag(S),real(diag(T)),tau,kappa);
%%%------ swap the qz form -------------------
[Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk));
% Str='norm(A*Q-Z*S)';texttest(Str,eval(Str))
% Str='norm(B*Q-Z*T)';texttest(Str,eval(Str))
if nargin < 6 | size(u,2) ~= 1
return
else
%%% repeat SwapQZ if angle is too small
kk=min(size(u,1),k); J=1:kk; u=u(J,1)'*Q(J,:);
if abs(u(1,1))>0.7, return, end
for j=2:kk
J=1:j;
if norm(u(1,J))>0.7
J0=[j,1:j-1];
[Qq,Zz,Ss,Tt]=SwapQZ(eye(j),eye(j),S(J,J),T(J,J),J0);
if abs(u(1,J)*Qq(:,1))>0.71
Q(:,J)=Q(:,J)*Qq; Z(:,J)=Z(:,J)*Zz;
S(J,J)=Ss; S(J,j+1:k)=Zz'*S(J,j+1:k);
T(J,J)=Tt; T(J,j+1:k)=Zz'*T(J,j+1:k);
% Str='norm(A*Q-Z*S)';texttest(Str,eval(Str))
% Str='norm(B*Q-Z*T)';texttest(Str,eval(Str))
fprintf(' Took %2i:%6.4g\n',j,S(1,1)./T(1,1))
return
end
end
end
disp([' Selection problem: took ',num2str(1)])
return
end
%%%======================================================================
function I=SortEig(s,t,sigma,kappa);
%
% I=SortEig(S,T,SIGMA) sorts the indices of [S,T] as prescribed by SIGMA
% S and T are K-vectors.
%
% If SIGMA=[ALPHA,BETA] is a complex pair then
% if CHORDALDISTANCE
% sort [S,T] with increasing chordal distance w.r.t. SIGMA.
% else
% sort S./T with increasing distance w.r.t. SIGMA(1)/SIGMA(2)
%
% The chordal distance D between a pair A and a pair B is
% defined as follows.
% Scale A by a scalar F such that NORM(F*A)=1.
% Scale B by a scalar G such that NORM(G*B)=1.
% Then D(A,B)=SQRT(1-ABS((F*A)*(G*B)')).
%
% I=SortEig(S,T,SIGMA,KAPPA). Kappa is a caling that effects the
% chordal distance: [S,KAPPA*T] w.r.t. [SIGMA(1),KAPPA*SIGMA(2)].
% coded by Gerard Sleijpen, version April 2002
global CHORDALDISTANCE
if ischar(sigma)
warning off, s=s./t; warning on
switch sigma
case 'LM'
[s,I]=sort(-abs(s));
case 'SM'
[s,I]=sort(abs(s));
case 'LR';
[s,I]=sort(-real(s));
case 'SR';
[s,I]=sort(real(s));
case 'BE';
[s,I]=sort(real(s)); I=twistdim(I,1);
end
elseif CHORDALDISTANCE
if kappa~=1, t=kappa*t; sigma(2)=kappa*sigma(2); end
n=sqrt(s.*conj(s)+t.*t);
[s,I]=sort(-abs([s,t]*sigma')./n);
else
warning off, s=s./t; warning on
if sigma(2)==0; [s,I]=sort(-abs(s));
else, [s,I]=sort(abs(s-sigma(1)/sigma(2)));
end
end
return
%------------------------------------------------------------------------
function t=twistdim(t,k)
d=size(t,k); J=1:d; J0=zeros(1,2*d);
J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J);
if k==1, t=t(I,:); else, t=t(:,I); end
return
%%%======================================================================
function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I)
% [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P)
% QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular.
% P is the first part of a permutation of (1:K)'.
%
% Then Q and Z are K by K unitary, S and T are K by K upper triangular,
% such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have
% A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where
% LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT).
%
% Computation uses Givens rotations.
%
% coded by Gerard Sleijpen, version October 12, 1998
kk=min(length(I),size(S,1)-1);
j=1; while (j<=kk & j==I(j)), j=j+1; end
while j<=kk
i=I(j);
for k = i-1:-1:j,
%%% i>j, move ith eigenvalue to position j
J = [k,k+1];
q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J);
if q(1) ~= 0
q = q/norm(q);
G = [[q(2);-q(1)],q'];
Q(:,J) = Q(:,J)*G;
S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G;
end
if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end
if q(2) ~= 0
q=q/norm(q);
G = [q';q(2),-q(1)];
Z(:,J) = Z(:,J)*G';
S(J,:) = G*S(J,:); T(J,:) = G*T(J,:);
end
T(k+1,k) = 0;
S(k+1,k) = 0;
end
I=I+(I<i);
j=j+1; while (j<=kk & j==I(j)), j=j+1; end
end
return
%------------------------------------------------------------------------
function [Q,Z,S,T]=SwapQZ0(Q,Z,S,T,I)
%
% [Q,Z,S,T]=sortqz0(A,B,s,t,k)
% A and B are k by k matrices, t and s are k vectors such that
% (t(i),s(i)) eigenpair (A,B), i.e. t(i)*A-s(i)*B singular.
% Computes the Schur form with a ordering prescribed by (t,s):
% A*Q=Z*S, B*Q=Z*T such that diag(S)./diag(T)=s./t.
% Computation uses Householder reflections.
%
% coded by Gerard Sleijpen, version October 12, 1997
k=size(S,1); s=diag(S); t=diag(T); s=s(I,1); t=t(I,1);
for i=1:k-1
%%% compute q s.t. C*q=(t(i,1)*S-s(i,1)*T)*q=0
C=t(i,1)*S(i:k,i:k)-s(i,1)*T(i:k,i:k);
[q,r,p]=qr(C); %% C*P=Q*R
%% check whether last but one diag. elt r nonzero
j=k-i; while abs(r(j,j))<eps*norm(r); j=j-1; end; j=j+1;
r(j,j)=1; e=zeros(j,1); e(j,1)=1;
q=p*([r(1:j,1:j)\e;zeros(k-i+1-j,1)]); q=q/norm(q);%% C*q
%%% end computation q
z=conj(s(i,1))*S(i:k,i:k)*q+conj(t(i,1))*T(i:k,i:k)*q; z=z/norm(z);
a=q(1,1); if a ~=0, a=abs(a)/a; q=a*q; end
a=z(1,1); if a ~=0, a=abs(a)/a; z=a*z; end
q(1,1)=q(1,1)+1; q=q/norm(q); q=[zeros(i-1,1);q];
z(1,1)=z(1,1)+1; z=z/norm(z); z=[zeros(i-1,1);z];
S=S-(S*q)*(2*q)'; S=S-(2*z)*(z'*S);
T=T-(T*q)*(2*q)'; T=T-(2*z)*(z'*T);
Q=Q-(Q*q)*(2*q)'; Z=Z-(Z*z)*(2*z)';
end
return
%%%======== END sort QZ decomposition interaction matrices ==============
%%%======================================================================
%%%======== INITIALIZATION ==============================================
%%%======================================================================
function MyClear
global Operator_Form Operator_A Operator_B Operator_Params ...
Precond_L Precond_U Precond_P Precond_Params ...
Precond_Form Precond_Type ...
Operator_MVs Precond_Solves ...
CHORDALDISTANCE ...
Qschur Zschur Sschur Tschur ...
MinvZ QastMinvZ
return
%%%======================================================================
function [n,nselect,Sigma,kappa,SCHUR,...
jmin,jmax,tol,maxit,V,AV,BV,TS,DISP,PAIRS,JDV,FIX,track,NSIGMA,...
lsolver,par] = ReadOptions(varargin)
% Read options and set defaults
global Operator_Form Operator_A Operator_B Operator_Params ...
Precond_Form Precond_L Precond_U Precond_P Precond_Params ...
CHORDALDISTANCE
Operator_A = varargin{1};
n=CheckMatrix(Operator_A,1);
% defaults %%%% search for 'xx' in fieldnames
nselect0= 5;
maxit = 200; %%%% 'ma'
SCHUR = 0; %%%% 'sch'
tol = 1e-8; %%%% 'to'
DISP = 0; %%%% 'di'
p0 = 5; %%% jmin=nselect+p0 %%%% 'jmi'
p1 = 5; %%% jmax=jmin+p1 %%%% 'jma'
TS = 1; %%%% 'te'
PAIRS = 0; %%%% 'pai'
JDV = 0; %%%% 'av'
track = 1e-4; %%%% 'tr'
FIX = 1000; %%%% 'fix'
NSIGMA = 0; %%%% 'ns'
CHORD = 1; %%%% 'ch'
lsolver = 'gmres'; %%%% 'lso'
ls_maxit= 200; %%%% 'ls_m'
ls_tol = [0.7,0.49]; %%%% 'ls_t'
ell = 4; %%%% 'ls_e'
TP = 0; %%%% 'ty'
L = []; %%%% 'l_'
U = []; %%%% 'u_'
P = []; %%%% 'p_'
kappa = 1; %%%% 'sca'
V0 = 'ones(n,1)+rand(n,1)'; %%%% 'v0'
%% initiation
nselect=[]; Sigma=[]; options=[]; Operator_B=[];
jmin=-1; jmax=-1; V=[]; AV=[]; BV=[]; par=[];
%------------------------------------------------
%------- Find quantities ------------------------
%------------------------------------------------
jj=[];
for j = 2:nargin
if isstruct(varargin{j})
options = varargin{j};
elseif ischar(varargin{j})
s=varargin{j};
if exist(s)==2 & isempty(Operator_B)
Operator_B=s;
elseif length(s) == 2 & isempty(Sigma)
s=upper(s);
switch s
case {'LM','SM','LR','SR','BE'}, Sigma=s;
otherwise
jj=[jj,j];
end
else
jj=[jj,j];
end
elseif min([n,n]==size(varargin{j})) & isempty(Operator_B)
Operator_B=varargin{j};
elseif length(varargin{j}) == 1
s = varargin{j};
if isempty(nselect) & isreal(s) & (s == fix(s)) & (s > 0)
nselect = min(n,s);
elseif isempty(Sigma)
Sigma = s;
else
jj=[jj,j];
end
elseif min(size(varargin{j}))==1 & isempty(Sigma)
Sigma = varargin{j}; if size(Sigma,1)==1, Sigma=Sigma'; end
elseif min(size(varargin{j}))==2 & isempty(Sigma)
Sigma = varargin{j}; if size(Sigma,2)>2 , Sigma=Sigma'; end
else
jj=[jj,j];
end
end
%------- find parameters for operators -----------
Operator_Params=[]; Operator_Params{2}='';
k=length(jj);
if k>0
Operator_Params(3:k+2)=varargin(jj);
if ~ischar(Operator_A)
msg=sprintf(', %i',jj);
msg=sprintf('Input argument, number%s, not recognized.',msg);
button=questdlg(msg,'Input arguments','Ignore','Stop','Ignore');
if strcmp(button,'Stop'), n=-1; return, end
end
end
%------- operator B -----------------------------
if isempty(Operator_B)
if ischar(Operator_A)
Operator_Form=2; % or Operator_Form=3, or Operator_Form=5;
else
Operator_Form=8;
end
else
if ischar(Operator_B)
if ischar(Operator_A), Operator_Form=1; else, Operator_Form=6; end
elseif ischar(Operator_A)
Operator_Form=4;
else
Operator_Form=7;
end
end
if n<2, return, end
%------- number of eigs to be computed ----------
if isempty(nselect), nselect=min(n,nselect0); end
%------------------------------------------------
%------- Analyse Options ------------------------
%------------------------------------------------
fopts = [];
if ~isempty(options), fopts = fieldnames(options); end
%------- preconditioner -------------------------
Precond_L=findfield(options,fopts,'pr',[]);
[L,ok]=findfield(options,fopts,'l_',Precond_L);
if ok & ~isempty(Precond_L),
msg =sprintf('A preconditioner is defined in');
msg =[msg,sprintf('\n''Precond'', but also in ''L_precond''.')];
msg=[msg,sprintf('\nWhat is the correct one?')];
button=questdlg(msg,'Preconditioner','L_Precond','Precond','L_Precond');
if strcmp(button,'L_Precond'),
Precond_L = L;
end
else
Precond_L = L;
end
if ~isempty(Precond_L)
Precond_U=findfield(options,fopts,'u_',[]);
Precond_P=findfield(options,fopts,'p_',[]);
end
Precond_Params=[]; Precond_Params{2}='';
Params=findfield(options,fopts,'par',[]);
[l,k]=size(Params);
if k>0,
if iscell(Params), Precond_Params(3:k+2)=Params;
else, Precond_Params{3}=Params; end
end
TP=findfield(options,fopts,'ty',TP);
n=SetPrecond(n,TP); if n<2, return, end
%------- max, min dimension search subspace ------
jmin=min(n,findfield(options,fopts,'jmi',jmin));
jmax=min(n,findfield(options,fopts,'jma',jmax));
if jmax < 0
if jmin<0, jmin=min(n,nselect+p0); end
jmax=min(n,jmin+p1);
else
if jmin<0, jmin=max(1,jmax-p1); end
end
maxit=findfield(options,fopts,'ma',maxit);
%------- initial search subspace ----------------
V=findfield(options,fopts,'v',[]);
[m,d]=size(V);
if m~=n
if m>n, V = V(1:n,:); end
if m<n, V = [V;0.001*rand(n-m-1,d)]; end
end
V=orth(V); [m,d]=size(V);
if d==0, nr=0; while nr==0, V=eval(V0); nr=norm(V); V=V/nr; end, end
%------- Check definition B, Compute AV, BV -----
[AV,BV,n]=CheckDimMV(V); if n<2, return, end
%------- Other options --------------------------
tol=findfield(options,fopts,'to',tol);
kappa = findfield(options,fopts,'sca',kappa);
kappa = abs(kappa(1,1)); if kappa==0, kappa=1; end
PAIRS = findfield(options,fopts,'pai',PAIRS,[0,1]);
SCHUR = findfield(options,fopts,'sch',SCHUR,[0,1,0.5]);
DISP = findfield(options,fopts,'di',DISP,[0,1]);
JDV = findfield(options,fopts,'av',JDV,[0,1]);
track = max(abs(findfield(options,fopts,'tr',track,[0,track,inf])),0);
NSIGMA = findfield(options,fopts,'ns',NSIGMA,[0,1]);
FIX = max(abs(findfield(options,fopts,'fix',0,[0,FIX,inf])),0);
CHORDALDISTANCE = findfield(options,fopts,'ch',CHORD,[0,1]);
[TS0,ok] = findfield(options,fopts,'te',TS);
if ok & ischar(TS0)
if strncmpi(TS0,'st',2), TS=0; %% 'standard'
elseif strncmpi(TS0,'ha',2), TS=1; %% 'harmonic'
elseif strncmpi(TS0,'se',2), TS=2; %% 'searchspace'
elseif strncmpi(TS0,'bv',2), TS=3;
elseif strncmpi(TS0,'av',2), TS=4;
end
else
TS=max(0,min(4,round(TS0(1,1))));
end
%------- set targets ----------------
if isempty(Sigma)
if TS==1, Sigma=[0,1]; else, Sigma = 'LM'; end
elseif ischar(Sigma)
switch Sigma
case {'LM','LR','SR','BE','SM'}
if ~ok, TS=3; end
end
else
[k,l]=size(Sigma);
if l==1, Sigma=[Sigma,ones(k,1)]; l=2; end
Sigma=ScaleEig(Sigma);
end
if ischar(Sigma) & TS<2
msg1=sprintf(' The choice sigma = ''%s'' does not match the\n',Sigma);
msg2=sprintf(' selected test subspace. Specify a numerical\n');
msg3=sprintf(' value for sigma (e.g. sigma = '); msg4='';
switch Sigma
case {'LM','LR'}
msg4=sprintf('[1,0]');
case {'SM','SR','BE'}
msg4=sprintf(' [0,1]');
end
msg5=sprintf('),\n or continue with ''TestSpace''=''B*V''.');
msg=[msg1,msg2,msg3,msg4,msg5];
button=questdlg(msg,'Targets and test subspaces','Continue','Stop','Continue');
if strcmp(button,'Continue'), TS=3; else, n=-1; return, end
end
%------- linear solver --------------------------
lsolver = findfield(options,fopts,'lso',lsolver);
method=strvcat('exact','olsen','iluexact','gmres','cgstab','bicgstab');
j=strmatch(lower(lsolver),method);
if isempty(j),
msg=['The linear solver ''',lsolver,''' is not included.'];
msg=[msg,sprintf('\nIs GMRES ok?')];
button=questdlg(msg,'Linear solver','Yes','No','Yes');
if strcmp(button,'Yes'), j=4; ls_maxit=5; else, n=-1; return, end
end
if j==1, lsolver='exact'; Precond_Form = 0;
elseif j==2 | j==3, lsolver='olsen';
elseif j==4, lsolver='gmres'; ls_maxit=5;
else, lsolver='cgstab'; ls_tol=1.0e-10;
end
ls_maxit= findfield(options,fopts,'ls_m',ls_maxit);
ls_tol = findfield(options,fopts,'ls_t',ls_tol);
ell = findfield(options,fopts,'ls_e',ell);
par=[ls_tol,ls_maxit,ell];
%----- Display the parameters that are used ----------------
if DISP
fprintf('\n'),fprintf('PROBLEM\n')
switch Operator_Form
case {1,4,6,7}
fprintf('%13s: %s\n','A',StrOp(Operator_A));
fprintf('%13s: %s\n','B',StrOp(Operator_B));
case 2
fprintf('%13s: ''%s'' ([Av,Bv] = %s(v))\n','A,B',Operator_A,Operator_A);
case 3
fprintf('%13s: ''%s''\n','A,B',Operator_A);
fprintf('%15s(Av = %s(v,''A''), Bv = %s(v,''B''))\n',...
'',Operator_A,Operator_A);
case {5,8}
fprintf('%13s: %s\n','A',StrOp(Operator_A));
fprintf('%13s: %s\n','B','Identity (B*v = v)');
end
fprintf('%13s: %i\n','dimension',n);
fprintf('%13s: %i\n\n','nselect',nselect);
if length(jj)>0 & (ischar(Operator_A) | ischar(Operator_B))
msgj=sprintf(', %i',jj); msgo='';
if ischar(Operator_A), msgo=sprintf(' ''%s''',Operator_A); end
if ischar(Operator_B), msgo=sprintf('%s ''%s''.',msgo,Operator_B); end
fprintf(' The JDQZ input arguments, number%s, are\n',msgj)
fprintf(' taken as input parameters 3:%i for%s.\n\n',length(jj)+2,msgo);
end
fprintf('TARGET\n')
if ischar(Sigma)
fprintf('%13s: ''%s''\n','sigma',Sigma)
else
fprintf('%13s: %s\n','sigma',mydisp(Sigma(1,:)))
for j=2:size(Sigma,1),
fprintf('%13s: %s\n','',mydisp(Sigma(j,:)))
end
end
fprintf('\nOPTIONS\n')
fprintf('%13s: %g\n','Schur',SCHUR)
fprintf('%13s: %g\n','Tol',tol)
fprintf('%13s: %i\n','Disp',DISP)
fprintf('%13s: %i\n','jmin',jmin)
fprintf('%13s: %i\n','jmax',jmax)
fprintf('%13s: %i\n','MaxIt',maxit)
fprintf('%13s: %s\n','v0',StrOp(V))
fprintf('%13s: %i\n','Pairs',PAIRS)
fprintf('%13s: %i\n','AvoidStag',JDV)
fprintf('%13s: %i\n','NSigma',NSIGMA)
fprintf('%13s: %g\n','Track',track)
fprintf('%13s: %g\n','FixShift',FIX)
fprintf('%13s: %i\n','Chord',CHORDALDISTANCE)
fprintf('%13s: ''%s''\n','LSolver',lsolver)
str=sprintf('%g ',ls_tol);
fprintf('%13s: [ %s]\n','LS_Tol',str)
fprintf('%13s: %i\n','LS_MaxIt',ls_maxit)
if strcmp(lsolver,'cgstab')
fprintf('%13s: %i\n','LS_ell',ell)
end
DisplayPreconditioner(n); fprintf('\n')
switch TS
case 0, str='Standard, W = alpha''*A*V + beta''*B*V';
case 1, str='Harmonic, W = beta*A*V - alpha*B*V';
case 2, str='SearchSpace, W = V';
case 3, str='Petrov, W = B*V';
case 4, str='Petrov, W = A*V';
end
fprintf('%13s: %s\n','TestSpace',str); fprintf('\n\n');
end
return
%------------------------------------------------------------------------
function msg=StrOp(Op)
if ischar(Op)
msg=sprintf('''%s''',Op);
elseif issparse(Op), [n,k]=size(Op);
msg=sprintf('[%ix%i sparse]',n,k);
else, [n,k]=size(Op);
msg=sprintf('[%ix%i double]',n,k);
end
return
%------------------------------------------------------------------------
function DisplayPreconditioner(n)
global Precond_Form Precond_Type ...
Precond_L Precond_U Precond_P
FP=Precond_Form;
switch Precond_Form
case 0,
fprintf('%13s: %s\n','Precond','No preconditioner');
case {1,2,5}
fprintf('%13s: %s','Precond',StrOp(Precond_L));
if FP==2, fprintf(' (M\\v = %s(v,''preconditioner''))',Precond_L); end
fprintf('\n')
case {3,4,6,7}
fprintf('%13s: %s\n','L precond',StrOp(Precond_L));
fprintf('%13s: %s\n','U precond',StrOp(Precond_U));
if FP==7, fprintf('%13s: %s\n','P precond',StrOp(Precond_P)); end
if FP==4,fprintf('%15s(M\\v = %s(%s(v,''L''),''U''))\n',...
'',Precond_L,Precond_L); end
end
if FP
switch Precond_Type
case 0, str='explicit left';
case 1, str='explicit right';
case 2, str='implicit';
end
fprintf('%15sTo be used as %s preconditioner.\n','',str)
end
return
%------------------------------------------------------------------------
function possibilities
fprintf('\n')
fprintf('PROBLEM\n')
fprintf(' A: [ square matrix | string ]\n');
fprintf(' B: [ square matrix {identity} | string ]\n');
fprintf(' nselect: [ positive integer {5} ]\n\n');
fprintf('TARGET\n')
fprintf(' sigma: [ vector of scalars | \n');
fprintf(' pair of vectors of scalars |\n');
fprintf(' {''LM''} | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n');
fprintf('OPTIONS\n');
fprintf(' Schur: [ yes | {no} ]\n');
fprintf(' Tol: [ positive scalar {1e-8} ]\n');
fprintf(' Disp: [ yes | {no} ]\n');
fprintf(' jmin: [ positive integer {nselect+5} ]\n');
fprintf(' jmax: [ positive integer {jmin+5} ]\n');
fprintf(' MaxIt: [ positive integer {200} ]\n');
fprintf(' v0: ');
fprintf('[ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n');
fprintf(' TestSpace: ');
fprintf('[ Standard | {Harmonic} | SearchSpace | BV | AV ]\n');
fprintf(' Pairs: [ yes | {no} ] \n');
fprintf(' AvoidStag: [ yes | {no} ]\n');
fprintf(' Track: [ {yes} | no non-negative scalar {1e-4} ]\n');
fprintf(' NSigma: [ yes | {no} ]\n');
fprintf(' FixShift: [ yes | {no} | non-negative scalar {1e+3} ]\n');
fprintf(' Chord: [ {yes} | no ]\n');
fprintf(' Scale: [ positive scalar {1} ]\n');
fprintf(' LSolver: [ {gmres} | bicgstab ]\n');
fprintf(' LS_Tol: [ row of positive scalar {[0.7,0.49]} ]\n');
fprintf(' LS_MaxIt: [ positive integer {5} ]\n');
fprintf(' LS_ell: [ positive integer {4} ]\n');
fprintf(' Precond: ');
fprintf('[ n by n matrix {identity} | n by 2n matrix | string ]\n');
fprintf(' L_Precond: same as ''Precond''\n');
fprintf(' U_Precond: [ n by n matrix {identity} | string ]\n');
fprintf(' P_Precond: [ n by n matrix {identity} ]\n');
fprintf(' Type_Precond: [ {left} | right | implicit ]\n');
fprintf('\n')
return
%------------------------------------------------------------------------
function x = boolean(x,gamma,string)
%Y = BOOLEAN(X,GAMMA,STRING)
% GAMMA(1) is the default.
% If GAMMA is not specified, GAMMA = 0.
% STRING is a cell of accepted strings.
% If STRING is not specified STRING = {'n' 'y'}
% STRING{I} and GAMMA(I) are accepted expressions for X
% If X=GAMMA(I) then Y=X. If the first L characters
% of X matches those of STRING{I}, then Y=GAMMA(I+1).
% Here L=SIZE({STRING{1},2).
% For other values of X, Y=GAMMA(1);
if nargin < 2, gamma=[0,0,1]; end
if nargin < 3, string={'n' 'y'}; end
if ischar(x)
l=size(string{1},2);
i=min(find(strncmpi(x,string,l)));
if isempty(i), i=0; end, x=gamma(i+1);
elseif max((gamma-x)==0)
elseif gamma(end) == inf
else, x=gamma(1);
end
return
%------------------------------------------------------------------------
function [a,ok]=findfield(options,fopts,str,default,gamma,stri)
% Searches the fieldnames in FOPTS for the string STR.
% The field is detected if only the first part of the fieldname
% matches the string STR. The search is case insensitive.
% If the field is detected, then OK=1 and A is the fieldvalue.
% Otherwise OK=0 and A=DEFAULT
l=size(str,2); j=min(find(strncmpi(str,fopts,l)));
if ~isempty(j)
a=getfield(options,char(fopts(j,:))); ok=1;
if nargin == 5, a = boolean(a,[default,gamma]);
elseif nargin == 6, a = boolean(a,[default,gamma],stri); end
elseif nargin>3
a=default; ok=0;
else
a=[]; ok=0;
end
return
%%%======================================================================
function n=CheckMatrix(A,gamma)
if ischar(A), n=-1;
if exist(A) ~=2
msg=sprintf(' Can not find the M-file ''%s.m'' ',A);
errordlg(msg,'MATRIX'),n=-2;
end
if n==-1 & gamma, eval('n=feval(A,[],''dimension'');','n=-1;'), end
else, [n,n] = size(A);
if any(size(A) ~= n)
msg=sprintf(' The operator must be a square matrix or a string. ');
errordlg(msg,'MATRIX'),n=-3;
end
end
return
%------------------------------------------------------------------------
function [Av,Bv,n]=CheckDimMV(v)
% [Av,Bv]=CheckDimMV(v)
% Av=A*v, Bv=B*v Checks correctness operator definitions
global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params
[n,k]=size(v);
if k>1, V=v(:,2:k); v=v(:,1); end
Bv=v;
switch Operator_Form
case 1 % both Operator_A and B are strings
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
Bv=feval(Operator_B,Operator_Params{:});
case 2 %%% or Operator_Form=3 or Operator_Form=5???
Operator_Params{1}=v;
eval('[Av,Bv]=feval(Operator_A,Operator_Params{:});','Operator_Form=3;')
if Operator_Form==3,
ok=1; Operator_Params{2}='A';
eval('Av=feval(Operator_A,Operator_Params{:});','ok=0;')
if ok,
Operator_Params{2}='B';
eval('Bv=feval(Operator_A,Operator_Params{:});','ok=0;'),
end
if ~ok,
Operator_Form=5; Operator_Params{2}='';
Av=feval(Operator_A,Operator_Params{:});
end
end
case 3
Operator_Params{1}=v;
Operator_Params{2}='A';
Av=feval(Operator_A,Operator_Params{:});
Operator_Params{2}='B';
Bv=feval(Operator_A,Operator_Params{:});
case 4
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
Bv=Operator_B*v;
case 5
Operator_Params{1}=v;
Av=feval(Operator_A,Operator_Params{:});
case 6
Av=Operator_A*v;
Operator_Params{1}=v;
Bv=feval(Operator_B,Operator_Params{:});
case 7
Av=Operator_A*v;
Bv=Operator_B*v;
case 8
Av=Operator_A*v;
end
Operator_MVs = 1;
ok_A=min(size(Av)==size(v));
ok_B=min(size(Bv)==size(v));
if ok_A & ok_B
if k>1,
ok=1; eval('[AV,BV]=MV(V);','ok=0;')
if ok
Av=[Av,AV]; Bv=[Bv,BV];
else
for j=2:k, [Av(:,j),Bv(:,j)]=MV(V(:,j-1)); end
end
end
return
end
if ~ok_A
Operator=Operator_A;
elseif ~ok_B
Operator=Operator_B;
end
msg=sprintf(' %s does not produce a vector of size %d',Operator,n)
errordlg(msg,'MATRIX'), n=-1;
return
%------------------------------------------------------------------------
function n=SetPrecond(n,TP)
% finds out how the preconditioners are defined (Precond_Form)
% and checks consistency of the definitions.
%
% If M is the preconditioner then P*M=L*U. Defaults: L=U=P=I.
%
% Precond_Form
% 0: no L
% 1: L M-file, no U, L ~= A
% 2: L M-file, no U, L == A
% 3: L M-file, U M-file, L ~= A, U ~= A, L ~=U
% 4: L M-file, U M-file, L == U
% 5: L matrix, no U
% 6: L matrix, U matrix no P
% 7: L matrix, U matrix, P matrix
%
% Precond_Type
% 0: Explicit left
% 1: Explicit right
% 2: Implicit
%
global Operator_A ...
Precond_Form Precond_Solves ...
Precond_Type ...
Precond_L Precond_U Precond_P Precond_Params
Precond_Type = 0;
if ischar(TP)
TP=lower(TP(1,1));
switch TP
case 'l'
Precond_Type = 0;
case 'r'
Precond_Type = 1;
case 'i'
Precond_Type = 2;
end
else
Precond_Type=max(0,min(fix(TP),2));
end
Precond_Solves = 0;
% Set type preconditioner
Precond_Form=0;
if isempty(Precond_L), return, end
if ~isempty(Precond_U) & ischar(Precond_L)~=ischar(Precond_U)
msg=sprintf(' L and U should both be strings or matrices');
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
if ~isempty(Precond_P) & (ischar(Precond_P) | ischar(Precond_L))
msg=sprintf(' P can be specified only if P, L and U are matrices');
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
tp=1+4*~ischar(Precond_L)+2*~isempty(Precond_U)+~isempty(Precond_P);
if tp==1, tp = tp + strcmp(Precond_L,Operator_A); end
if tp==3, tp = tp + strcmp(Precond_L,Precond_U); end
if tp==3 & strcmp(Precond_U,Operator_A)
msg=sprintf(' If L and A use the same M-file,')
msg=[msg,sprintf('\n then so should U.')];
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
if tp>5, tp=tp-1; end, Precond_Form=tp;
% Check consistency definitions
if tp<5 & exist(Precond_L) ~=2
msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_L);
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
ok=1;
if tp == 2
Precond_Params{1}=zeros(n,1);
Precond_Params{2}='preconditioner';
eval('v=feval(Operator_A,Precond_Params{:});','ok=0;')
if ~ok
msg='Preconditioner and matrix use the same M-file';
msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)];
msg=[msg,'Therefore the preconditioner is called as'];
msg=[msg,sprintf('\n\n\tw=%s(v,''preconditioner'')\n\n',Precond_L)];
msg=[msg,sprintf('Put this "switch" in ''%s.m''.',Precond_L)];
end
end
if tp == 4 | ~ok
ok1=1;
Precond_Params{1}=zeros(n,1);
Precond_Params{2}='L';
eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;')
Precond_Params{2}='U';
eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;')
if ok1
Precond_Form = 4; Precond_U = Precond_L; ok=1;
else
if tp == 4
msg='L and U use the same M-file';
msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)];
msg=[msg,'Therefore L and U are called'];
msg=[msg,sprintf(' as\n\n\tw=%s(v,''L'')',Precond_L)];
msg=[msg,sprintf(' \n\tw=%s(v,''U'')\n\n',Precond_L)];
msg=[msg,sprintf('Check the dimensions and/or\n')];
msg=[msg,sprintf('put this "switch" in ''%s.m''.',Precond_L)];
end
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
end
if tp==1 | tp==3
Precond_Params{1}=zeros(n,1); Precond_Params{2}='';
eval('v=feval(Precond_L,Precond_Params{:});','ok=0')
if ~ok
msg=sprintf('''%s'' should produce %i-vectors',Precond_L,n);
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
end
if tp==3
if exist(Precond_U) ~=2
msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_U);
errordlg(msg,'PRECONDITIONER'), n=-1; return
else
Precond_Params{1}=zeros(n,1); Precond_Params{2}='';
eval('v=feval(Precond_U,Precond_Params{:});','ok=0')
if ~ok
msg=sprintf('''%s'' should produce %i-vectors',Precond_U,n);
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
end
end
if tp==5
if min([n,2*n]==size(Precond_L))
Precond_U=Precond_L(:,n+1:2*n); Precond_L=Precond_L(:,1:n);
Precond_Form=6;
elseif min([n,3*n]==size(Precond_L))
Precond_U=Precond_L(:,n+1:2*n); Precond_P=Precond_L(:,2*n+1:3*n);
Precond_L=Precond_L(:,1:n); Precond_Form=7;
elseif ~min([n,n]==size(Precond_L))
msg=sprintf('The preconditioning matrix\n');
msg2=sprintf('should be %iX%i or %ix%i ([L,U])\n',n,n,n,2*n);
msg3=sprintf('or %ix%i ([L,U,P])\n',n,3*n);
errordlg([msg,msg2,msg3],'PRECONDITIONER'), n=-1; return
end
end
if tp==6 & ~min([n,n]==size(Precond_L) & [n,n]==size(Precond_U))
msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1;
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
if tp==7 & ~min([n,n]==size(Precond_L) & ...
[n,n]==size(Precond_U) & [n,n]==size(Precond_P))
msg=sprintf('L, U, and P should all be %iX%i.',n,n); n=-1;
errordlg(msg,'PRECONDITIONER'), n=-1; return
end
return
%%%======================================================================
%%%========= DISPLAY FUNCTIONS ===========================================
%%%======================================================================
function Result(Sigm,Target,S,T,tol)
if nargin == 1
fprintf('\n\n %20s\n','Eigenvalues')
for j=1:size(Sigm,1),
fprintf('%2i %s\n',j,mydisp(Sigm(j,:),5))
end
return
end
fprintf('\n\n%17s %25s%18s\n','Targets','Eigenvalues','RelErr/Cond')
for j=1:size(S,1),
l=Target(j,1); s=S(j,:); t=T(j,:); lm=mydisp(s/t,5);
if l>0
fprintf('%2i %8s ''%s'' %9s %23s',j,'',Sigm(l,:),'',lm)
else
fprintf('%2i %23s %23s',j,mydisp(Target(j,2:3),5),lm)
end
re=1-tol/abs(t);
if re>0, re=(1+tol/abs(s))/re; re=min(re-1,1); else, re=1; end
if re>0.999, fprintf(' 1\n'), else, fprintf(' %5.0e\n',re), end
end
return
%------------------------------------------------------------------------
function s=mydisp(lambda,d)
if nargin <2, d=4; end
if size(lambda,2)==2,
if lambda(:,2)==0, s='Inf'; return, end
lambda=lambda(:,1)/lambda(:,2);
end
a=real(lambda); b=imag(lambda);
if max(a,b)==inf, s='Inf'; return, end
e=0;
if abs(a)>0; e= floor(log10(abs(a))); end
if abs(b)>0; e= max(e,floor(log10(abs(b)))); end
p=10^d; q=p/(10^e); a=round(a*q)/p; b=round(b*q)/p;
st=['%',num2str(d+2),'.',num2str(d),'f'];
ab=abs(b)==0;
if ab, str=[''' ']; else, str=['''(']; end
if a>=0, str=[str,'+']; a=abs(a); end, str=[str,st];
if ab, str=[str,'e']; else
if b>=0, str=[str,'+']; b=abs(b); end,
str=[str,st,'i)e']; end
if e>=0, str=[str,'+']; else, str=[str,'-']; e=-e; end
if e<10, str=[str,'0%i''']; else, str=[str,'%i''']; end
if ab, s=eval(sprintf(str,a,e));
else, s=eval(sprintf(str,a,b,e)); end
return
%%%======================================================================
function ShowEig(theta,target,k)
if ischar(target)
fprintf('\n target=''%s'', ',target)
else
fprintf('\n target=%s, ',mydisp(target,5))
end
fprintf('lambda_%i=%s\n',k,mydisp(theta,5));
return
%%%======================================================================
function texttest(s,nr,gamma)
if nargin<3, gamma=100*eps; end
if nr > gamma
% if nr>100*eps
fprintf('\n %35s is: %9.3g\t',s,nr)
end
return
%%%======================================================================
|
github
|
pvarin/DynamicVAE-master
|
lnst.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/lnst.m
| 866 |
utf_8
|
fd307c356d0eb128b0d57c9df000197e
|
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
function lnst(hs,he)
ls=get(he,'value');
switch ls
case 1
set(hs,'LineStyle','-','marker','x','color','b');
case 2
set(hs,'LineStyle','-','marker','o','color','r');
case 3
set(hs,'LineStyle','none','marker','o','color','b');
case 4
set(hs,'LineStyle','-','marker','none','color','g');
case 5
set(hs,'LineStyle','--','marker','d','color','b');
end
drawnow;
|
github
|
pvarin/DynamicVAE-master
|
scatter12n.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/scatter12n.m
| 1,309 |
utf_8
|
5a079c0bf3db6d26fd87f0cb3297c45b
|
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
function scatter12n(name,data,labels)
ld=length(data(1,:));
if ld==2
hf=figure;
set(hf,'name',name,'NumberTitle','off');
%if handles.islb
scatter(data(:,1),data(:,2),5,labels);
% else
% scatter(data(:,1),data(:,2),5);
% end
title(name);
else
if ld==1
hf=figure;
set(hf,'name',name,'NumberTitle','off');
%if handles.islb
scatter(data(:,1),zeros(length(data(:,1)),1),5,labels);
% else
% scatter(data(:,1),zeros(length(data(:,1)),1),5);
% end
title(name);
else
%if handles.islb
scattern(name,data,labels);
% else
% scattern('Result of dimensionality reduction',data);
% end
end
end
|
github
|
pvarin/DynamicVAE-master
|
not_calculated.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/not_calculated.m
| 7,602 |
utf_8
|
9f98d51f0c8207bd788383e580814903
|
function varargout = not_calculated(varargin)
% NOT_CALCULATED M-file for not_calculated.fig
% NOT_CALCULATED by itself, creates a new NOT_CALCULATED or raises the
% existing singleton*.
%
% H = NOT_CALCULATED returns the handle to a new NOT_CALCULATED or the handle to
% the existing singleton*.
%
% NOT_CALCULATED('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in NOT_CALCULATED.M with the given input arguments.
%
% NOT_CALCULATED('Property','Value',...) creates a new NOT_CALCULATED or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before not_calculated_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to not_calculated_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help not_calculated
% Last Modified by GUIDE v2.5 30-Jul-2008 11:02:27
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @not_calculated_OpeningFcn, ...
'gui_OutputFcn', @not_calculated_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before not_calculated is made visible.
function not_calculated_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to not_calculated (see VARARGIN)
% Choose default command line output for not_calculated
handles.output = 'Yes';
% Update handles structure
guidata(hObject, handles);
% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties. See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
for index = 1:2:(nargin-3),
if nargin-3==index, break, end
switch lower(varargin{index})
case 'title'
set(hObject, 'Name', varargin{index+1});
case 'string'
set(handles.text1, 'String', varargin{index+1});
end
end
end
% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
ScreenUnits=get(0,'Units');
set(0,'Units','pixels');
ScreenSize=get(0,'ScreenSize');
set(0,'Units',ScreenUnits);
FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
GCBFOldUnits = get(gcbf,'Units');
set(gcbf,'Units','pixels');
GCBFPos = get(gcbf,'Position');
set(gcbf,'Units',GCBFOldUnits);
FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
(GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);
% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat
IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;
Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);
set(handles.axes1, ...
'Visible', 'off', ...
'YDir' , 'reverse' , ...
'XLim' , get(Img,'XData'), ...
'YLim' , get(Img,'YData') ...
);
% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')
% UIWAIT makes not_calculated wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = not_calculated_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% The figure can be deleted now
delete(handles.figure1);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
% The GUI is still in UIWAIT, us UIRESUME
uiresume(handles.figure1);
else
% The GUI is no longer waiting, just close it
delete(handles.figure1);
end
% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
% User said no by hitting escape
handles.output = 'No';
% Update handles structure
guidata(hObject, handles);
uiresume(handles.figure1);
end
if isequal(get(hObject,'CurrentKey'),'return')
uiresume(handles.figure1);
end
|
github
|
pvarin/DynamicVAE-master
|
choose_method.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/choose_method.m
| 5,336 |
utf_8
|
a50c15d7c51725e6e88bb12bf5be57a3
|
function varargout = choose_method(varargin)
% CHOOSE_METHOD M-file for choose_method.fig
% CHOOSE_METHOD, by itself, creates a new CHOOSE_METHOD or raises the existing
% singleton*.
%
% H = CHOOSE_METHOD returns the handle to a new CHOOSE_METHOD or the handle to
% the existing singleton*.
%
% CHOOSE_METHOD('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHOOSE_METHOD.M with the given input arguments.
%
% CHOOSE_METHOD('Property','Value',...) creates a new CHOOSE_METHOD or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before choose_method_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to choose_method_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help choose_method
% Last Modified by GUIDE v2.5 25-Jul-2008 10:40:42
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @choose_method_OpeningFcn, ...
'gui_OutputFcn', @choose_method_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before choose_method is made visible.
function choose_method_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to choose_method (see VARARGIN)
% Choose default command line output for choose_method
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes choose_method wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = choose_method_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
vl=get(hObject,'Value');
switch vl
case 1
str='CorrDim';
case 2
str='NearNbDim';
case 3
str='GMST';
case 4
str='PackingNumbers';
case 5
str='EigValue';
case 6
str='MLE';
end
set(handles.str,'string',str);
drawnow;
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function str_Callback(hObject, eventdata, handles)
% hObject handle to str (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of str as text
% str2double(get(hObject,'String')) returns contents of str as a double
% --- Executes during object creation, after setting all properties.
function str_CreateFcn(hObject, eventdata, handles)
% hObject handle to str (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);
|
github
|
pvarin/DynamicVAE-master
|
load_data_1_var.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/load_data_1_var.m
| 4,776 |
utf_8
|
213540e0f2d0e24db85ee4c6184178c8
|
function varargout = load_data_1_var(varargin)
% LOAD_DATA_1_VAR M-file for load_data_1_var.fig
% LOAD_DATA_1_VAR, by itself, creates a new LOAD_DATA_1_VAR or raises the existing
% singleton*.
%
% H = LOAD_DATA_1_VAR returns the handle to a new LOAD_DATA_1_VAR or the handle to
% the existing singleton*.
%
% LOAD_DATA_1_VAR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LOAD_DATA_1_VAR.M with the given input arguments.
%
% LOAD_DATA_1_VAR('Property','Value',...) creates a new LOAD_DATA_1_VAR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before load_data_1_var_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to load_data_1_var_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help load_data_1_var
% Last Modified by GUIDE v2.5 23-Jul-2008 17:31:19
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @load_data_1_var_OpeningFcn, ...
'gui_OutputFcn', @load_data_1_var_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before load_data_1_var is made visible.
function load_data_1_var_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to load_data_1_var (see VARARGIN)
% Choose default command line output for load_data_1_var
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes load_data_1_var wait for user response (see UIRESUME)
uiwait(handles.figure1);
% uiwait;
% --- Outputs from this function are returned to the command line.
function varargout = load_data_1_var_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function cn_Callback(hObject, eventdata, handles)
% hObject handle to cn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of cn as text
% str2double(get(hObject,'String')) returns contents of cn as a double
% --- Executes during object creation, after setting all properties.
function cn_CreateFcn(hObject, eventdata, handles)
% hObject handle to cn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);
% --------------------------------------------------------------------
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
if get(handles.i,'value')
set(handles.cn,'Enable','on');
set(handles.cnt,'ForegroundColor',[0 0 0]);
else
set(handles.cn,'Enable','off');
set(handles.cnt,'ForegroundColor',[0.4 0.4 0.4]);
end
|
github
|
pvarin/DynamicVAE-master
|
plotn.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/plotn.m
| 3,947 |
utf_8
|
ba3674531d91bc0b2ca405e0a9d0bc3a
|
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
function plotn(name,data)
% plot if dimensionality>=3
% format: plotn(name,data)
% name - text that will be dispayed as name of figure
% data - multidimentional data, row - is one datapoint
bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961];
bgc1=[1 1 1];
bgc1=bgc;
% if length(varargin)==1
% labels=varargin{1};
% islb=true;
% else
islb=false;
% end
hf=figure;
set(hf,'name',name,'NumberTitle','off');
set(hf,'units','normalized');
set(hf,'position',[0.1 0.1 0.7 0.75]);
set(hf,'color',bgc);
ha=axes;
set(ha,'units','normalized');
set(ha,'position',[0.1 0.1 0.8 0.7]);
% if islb
% hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha);
% else
hs=plot3(data(:,1),data(:,2),data(:,3),'x-','parent',ha);
% end
set(hs,'UserData',data); % memorize data in userdata of plot
% title as text contol:
xc=0.5;
yc=0.94;
dx=0.8;
dy=0.04;
uicontrol('Style', 'text',...
'parent',hf,...
'String', name,...
'units','normalized',...
'fontunits','normalized',...
'HorizontalAlignment','center',...
'Position', [xc-dx/2 yc dx dy],...
'backgroundcolor',bgc1);
% dimensionality text
xc=0.5;
yc=0.9;
dx=0.2;
dy=0.04;
uicontrol('Style', 'text',...
'parent',hf,...
'String', ['dimensionality=' num2str(length(data(1,:)))],...
'units','normalized',...
'fontunits','normalized',...
'Position', [xc-dx/2 yc dx dy],...
'backgroundcolor',bgc1);
% edits:
xc=0.5;
yc=0.86;
dy=0.04;
dytx=0.03;
x0=0.03;
dxg=0.03;
xt=x0;
for cc=1:3
switch cc
case 1
ls='X';
case 2
ls='Y';
case 3
ls='Z';
end
dx1=0.07;
uicontrol('Style', 'text',...
'parent',hf,...
'String', [ls ' ' 'data:'],...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dytx/2 dx1 dytx],...
'backgroundcolor',bgc1);
xt=xt+dx1+0.005;
dx1=0.07;
he=uicontrol('Style', 'edit',...
'parent',hf,...
'String', num2str(cc),...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dy/2 dx1 dy],...
'backgroundcolor',[1 1 1]);
set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']);
xt=xt+dx1+0.005;
dx1=0.065;
uicontrol('Style', 'text',...
'parent',hf,...
'String', 'column',...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dytx/2 dx1 dytx],...
'backgroundcolor',bgc1);
xt=xt+dx1+0.005;
xt=xt+dxg;
end
dx1=0.1;
uicontrol('Style', 'text',...
'parent',hf,...
'String', 'line style:',...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dytx/2 dx1 dytx],...
'backgroundcolor',bgc1);
xt=xt+dx1+0.005;
dx1=0.07;
he=uicontrol('Style', 'popupmenu',...
'parent',hf,...
'String', '1|2|3|4|5',...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dy/2 dx1 dy],...
'backgroundcolor',[1 1 1]);
set(he,'callback',['lnst(' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']);
xlabel(ha,'X');
ylabel(ha,'Y');
zlabel(ha,'Z');
set(hf,'Toolbar','figure');
|
github
|
pvarin/DynamicVAE-master
|
scattern.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/scattern.m
| 3,514 |
utf_8
|
aca2d60a4f80079c67204845b2499143
|
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
function scattern(name,data,varargin)
% scatter plot if dimensionality>=3
% format: scattern(name,data)
% name - text that will be dispayed as name of figure
% data - multidimentional data, row - is one datapoint
% scattern(name,data,labels) - if labels spacified, used for color of points
bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961];
bgc1=[1 1 1];
bgc1=bgc;
if length(varargin)==1
labels=varargin{1};
islb=true;
else
islb=false;
end
hf=figure;
set(hf,'name',name,'NumberTitle','off');
set(hf,'units','normalized');
set(hf,'position',[0.1 0.1 0.7 0.75]);
set(hf,'color',bgc);
ha=axes;
set(ha,'units','normalized');
set(ha,'position',[0.1 0.1 0.8 0.7]);
if islb && size(data, 1) == numel(labels)
hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha);
else
hs=scatter3(data(:,1),data(:,2),data(:,3),5,'parent',ha);
end
if size(data, 1) ~= numel(labels)
warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.');
end
set(hs,'UserData',data); % memorize data in userdata of plot
% title as text contol:
xc=0.5;
yc=0.94;
dx=0.8;
dy=0.04;
uicontrol('Style', 'text',...
'parent',hf,...
'String', name,...
'units','normalized',...
'fontunits','normalized',...
'HorizontalAlignment','center',...
'Position', [xc-dx/2 yc dx dy],...
'backgroundcolor',bgc1);
% dimensionality text
xc=0.5;
yc=0.9;
dx=0.2;
dy=0.04;
uicontrol('Style', 'text',...
'parent',hf,...
'String', ['dimensionality=' num2str(length(data(1,:)))],...
'units','normalized',...
'fontunits','normalized',...
'Position', [xc-dx/2 yc dx dy],...
'backgroundcolor',bgc1);
% edits:
xc=0.5;
yc=0.86;
dy=0.04;
dytx=0.03;
x0=0.12;
dxg=0.05;
xt=x0;
for cc=1:3
switch cc
case 1
ls='X';
case 2
ls='Y';
case 3
ls='Z';
end
dx1=0.07;
uicontrol('Style', 'text',...
'parent',hf,...
'String', [ls ' ' 'data:'],...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dytx/2 dx1 dytx],...
'backgroundcolor',bgc1);
xt=xt+dx1+0.005;
dx1=0.07;
he=uicontrol('Style', 'edit',...
'parent',hf,...
'String', num2str(cc),...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dy/2 dx1 dy],...
'backgroundcolor',[1 1 1]);
set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']);
xt=xt+dx1+0.005;
dx1=0.065;
uicontrol('Style', 'text',...
'parent',hf,...
'String', 'column',...
'units','normalized',...
'fontunits','normalized',...
'Position', [xt yc-dytx/2 dx1 dytx],...
'backgroundcolor',bgc1);
xt=xt+dx1+0.005;
xt=xt+dxg;
end
xlabel(ha,'X');
ylabel(ha,'Y');
zlabel(ha,'Z');
set(hf,'Toolbar','figure');
|
github
|
pvarin/DynamicVAE-master
|
no_history.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/no_history.m
| 7,508 |
utf_8
|
d5c85b897eeca97b3e37ea41551de2b1
|
function varargout = no_history(varargin)
% NO_HISTORY M-file for no_history.fig
% NO_HISTORY by itself, creates a new NO_HISTORY or raises the
% existing singleton*.
%
% H = NO_HISTORY returns the handle to a new NO_HISTORY or the handle to
% the existing singleton*.
%
% NO_HISTORY('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in NO_HISTORY.M with the given input arguments.
%
% NO_HISTORY('Property','Value',...) creates a new NO_HISTORY or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before no_history_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to no_history_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help no_history
% Last Modified by GUIDE v2.5 16-Sep-2008 15:57:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @no_history_OpeningFcn, ...
'gui_OutputFcn', @no_history_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before no_history is made visible.
function no_history_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to no_history (see VARARGIN)
% Choose default command line output for no_history
handles.output = 'Yes';
% Update handles structure
guidata(hObject, handles);
% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties. See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
for index = 1:2:(nargin-3),
if nargin-3==index, break, end
switch lower(varargin{index})
case 'title'
set(hObject, 'Name', varargin{index+1});
case 'string'
set(handles.text1, 'String', varargin{index+1});
end
end
end
% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
ScreenUnits=get(0,'Units');
set(0,'Units','pixels');
ScreenSize=get(0,'ScreenSize');
set(0,'Units',ScreenUnits);
FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
GCBFOldUnits = get(gcbf,'Units');
set(gcbf,'Units','pixels');
GCBFPos = get(gcbf,'Position');
set(gcbf,'Units',GCBFOldUnits);
FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
(GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);
% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat
IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;
Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);
set(handles.axes1, ...
'Visible', 'off', ...
'YDir' , 'reverse' , ...
'XLim' , get(Img,'XData'), ...
'YLim' , get(Img,'YData') ...
);
% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')
% UIWAIT makes no_history wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = no_history_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% The figure can be deleted now
delete(handles.figure1);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
% The GUI is still in UIWAIT, us UIRESUME
uiresume(handles.figure1);
else
% The GUI is no longer waiting, just close it
delete(handles.figure1);
end
% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
% User said no by hitting escape
handles.output = 'No';
% Update handles structure
guidata(hObject, handles);
uiresume(handles.figure1);
end
if isequal(get(hObject,'CurrentKey'),'return')
uiresume(handles.figure1);
end
|
github
|
pvarin/DynamicVAE-master
|
load_data_vars.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/load_data_vars.m
| 7,727 |
utf_8
|
a89e86bdd4785b42127825a4c304fb5e
|
function varargout = load_data_vars(varargin)
% LOAD_DATA_VARS M-file for load_data_vars.fig
% LOAD_DATA_VARS, by itself, creates a new LOAD_DATA_VARS or raises the existing
% singleton*.
%
% H = LOAD_DATA_VARS returns the handle to a new LOAD_DATA_VARS or the handle to
% the existing singleton*.
%
% LOAD_DATA_VARS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LOAD_DATA_VARS.M with the given input arguments.
%
% LOAD_DATA_VARS('Property','Value',...) creates a new LOAD_DATA_VARS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before load_data_vars_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to load_data_vars_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help load_data_vars
% Last Modified by GUIDE v2.5 23-Jul-2008 18:19:22
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @load_data_vars_OpeningFcn, ...
'gui_OutputFcn', @load_data_vars_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before load_data_vars is made visible.
function load_data_vars_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to load_data_vars (see VARARGIN)
% Choose default command line output for load_data_vars
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
vn=varargin{1}; % variable names
str='';
for vnc=1:length(vn)
str=[str vn{vnc}];
if vnc~=length(vn)
str=[str ' '];
end
end
set(handles.lv,'string',str);
set(handles.d,'string',vn{1});
set(handles.ivn,'string',vn{2});
% UIWAIT makes load_data_vars wait for user response (see UIRESUME)
uiwait(handles.figure1);
%uiwait;
% --- Outputs from this function are returned to the command line.
function varargout = load_data_vars_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function lv_Callback(hObject, eventdata, handles)
% hObject handle to lv (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of lv as text
% str2double(get(hObject,'String')) returns contents of lv as a double
% --- Executes during object creation, after setting all properties.
function lv_CreateFcn(hObject, eventdata, handles)
% hObject handle to lv (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function d_Callback(hObject, eventdata, handles)
% hObject handle to d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of d as text
% str2double(get(hObject,'String')) returns contents of d as a double
% --- Executes during object creation, after setting all properties.
function d_CreateFcn(hObject, eventdata, handles)
% hObject handle to d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ivn_Callback(hObject, eventdata, handles)
% hObject handle to ivn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ivn as text
% str2double(get(hObject,'String')) returns contents of ivn as a double
% --- Executes during object creation, after setting all properties.
function ivn_CreateFcn(hObject, eventdata, handles)
% hObject handle to ivn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function icn_Callback(hObject, eventdata, handles)
% hObject handle to icn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of icn as text
% str2double(get(hObject,'String')) returns contents of icn as a double
% --- Executes during object creation, after setting all properties.
function icn_CreateFcn(hObject, eventdata, handles)
% hObject handle to icn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);
% --------------------------------------------------------------------
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
if get(handles.iv,'value')
set(handles.ivn,'Enable','on');
else
set(handles.ivn,'Enable','off');
end
if get(handles.ic,'value')
set(handles.icn,'Enable','on');
else
set(handles.icn,'Enable','off');
end
|
github
|
pvarin/DynamicVAE-master
|
mapping_parameters.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/mapping_parameters.m
| 23,373 |
utf_8
|
59c32ad869cef7d4887bd7f6bd777624
|
function varargout = mapping_parameters(varargin)
% MAPPING_PARAMETERS M-file for mapping_parameters.fig
% MAPPING_PARAMETERS, by itself, creates a new MAPPING_PARAMETERS or raises the existing
% singleton*.
%
% H = MAPPING_PARAMETERS returns the handle to a new MAPPING_PARAMETERS or the handle to
% the existing singleton*.
%
% MAPPING_PARAMETERS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MAPPING_PARAMETERS.M with the given input arguments.
%
% MAPPING_PARAMETERS('Property','Value',...) creates a new MAPPING_PARAMETERS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before mapping_parameters_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to mapping_parameters_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Last Modified by GUIDE v2.5 28-Jul-2008 16:23:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mapping_parameters_OpeningFcn, ...
'gui_OutputFcn', @mapping_parameters_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before mapping_parameters is made visible.
function mapping_parameters_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to mapping_parameters (see VARARGIN)
% Choose default command line output for mapping_parameters
handles.output = hObject;
no_dims=varargin{1};
handles.islb=varargin{2};
if length(no_dims)~=0
set(handles.nd,'string',num2str(round(no_dims)));
else
set(handles.nd,'string','2');
end
case1; % case one is default for start
% Update handles structure
guidata(hObject, handles);
% handles
% UIWAIT makes mapping_parameters wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = mapping_parameters_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% figure1: 218.0023
% sm: 240.0021
% na: 239.0021
% nat: 238.0021
% uipanel_tp: 235.0021
% prp: 234.0021
% prpt: 233.0021
% kpd: 232.0021
% kpdt: 231.0021
% kpR: 230.0021
% kpRt: 229.0021
% kgs: 228.0021
% kgst: 227.0021
% uipanel_k: 223.0022
% uipanel_ft: 220.0022
% sig: 53.0027
% sigt: 52.0027
% uipanel_ei: 49.0027
% prc: 48.0027
% prct: 47.0027
% k: 46.0028
% kt: 45.0028
% mi: 44.0028
% mit: 43.0029
% nd: 42.0029
% text3: 41.0034
% wl: 40.0029
% text1: 39.0033
% listbox1: 219.0023
% tl: 237.0021
% tg: 236.0021
% kp: 226.0022
% kg: 225.0022
% kl: 224.0022
% ftn: 222.0022
% fty: 221.0022
% eij: 51.0027
% eim: 50.0027
% output: 218.0023
% islb:
% PCA
% LDA
% MDS
% SimplePCA
% ProbPCA
% FactorAnalysis
% Isomap
% LandmarkIsomap
% LLE
% Laplacian
% HessianLLE
% LTSA
% MVU
% CCA
% LandmarkMVU
% FastMVU
% DiffusionMaps
% KernelPCA
% GDA
% SNE
% SymSNE
% t-SNE
% LPP
% NPE
% LLTSA
% SPE
% Autoencoder
% LLC
% ManifoldChart
% CFA
% GPLVM
switch get(hObject,'Value')
case 1 % PCA
% no parameters;
case1;
case 2 % LDA
% no parameters;
case1;
if handles.islb
set(handles.wl,'visible','off');
set(handles.sm,'Enable','on');
else
set(handles.wl,'visible','on');
set(handles.sm,'Enable','off');
end
case 3 % MDS
% no parameters;
case1;
case 4 % SimplePCA
% no parameters;
case1;
case 5 % ProbPCA
case1; % hide all contols first
set(handles.mi,'Visible','on');
set(handles.mit,'Visible','on');
case 6 % FactorAnalysis
% no parameters;
case1;
case 7 % Isomap
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
case 8 % LandmarkIsomap
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.prc,'Visible','on');
set(handles.prct,'Visible','on');
case 9 % LLE
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 10 % Laplacian
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.sig,'Visible','on');
set(handles.sigt,'Visible','on');
set(handles.uipanel_ei,'Visible','on');
case 11 % HessianLLE
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 12 % LTSA
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 13 % MVU
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 14 % CCA
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 15 % LandmarkMVU
case1; % hide all contols first
set(handles.k,'Visible','on','string',5);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
case 16 % FastMVU
case1; % hide all contols first
set(handles.k,'Visible','on','string',5);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
set(handles.uipanel_ft,'Visible','on');
case 17 % DiffusionMaps
case1; % hide all contols first
set(handles.t,'Visible','on');
set(handles.tt,'Visible','on');
set(handles.sig,'Visible','on');
set(handles.sigt,'Visible','on');
case 18 % KernelPCA
case1; % hide all contols first
set(handles.uipanel_k,'Visible','on');
update_kernel_uipanel;
case 19 % GDA
case1; % hide all contols first
if handles.islb
set(handles.wl,'visible','off');
set(handles.sm,'Enable','on');
set(handles.uipanel_k,'Visible','on');
update_kernel_uipanel;
else
set(handles.wl,'visible','on');
set(handles.sm,'Enable','off');
end
case 20 % SNE
case1; % hide all contols first
set(handles.prp,'Visible','on');
set(handles.prpt,'Visible','on');
case 21 % SymSNE
case1; % hide all contols first
set(handles.prp,'Visible','on');
set(handles.prpt,'Visible','on');
case 22 % t-SNE
case1; % hide all contols first
set(handles.prp,'Visible','on');
set(handles.prpt,'Visible','on');
case 23 % LPP
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.sig,'Visible','on');
set(handles.sigt,'Visible','on');
set(handles.uipanel_ei,'Visible','on');
case 24 % NPE
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 25 % LLTSA
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.uipanel_ei,'Visible','on');
case 26 % SPE
case1; % hide all contols first
set(handles.uipanel_tp,'Visible','on');
update_type_uipanel;
set(handles.k,'Enable','on');
adaptive_callback;
case 27 % Autoencoder
% no parameters;
case1;
case 28 % LLC
case1; % hide all contols first
set(handles.k,'Visible','on','string',12);
set(handles.kt,'Visible','on');
set(handles.ka,'Visible','on');
adaptive_callback;
set(handles.na,'Visible','on');
set(handles.nat,'Visible','on');
set(handles.mi,'Visible','on');
set(handles.mit,'Visible','on');
set(handles.uipanel_ei,'Visible','on');
case 29 % ManifoldChart
case1; % hide all contols first
set(handles.na,'Visible','on');
set(handles.nat,'Visible','on');
set(handles.mi,'Visible','on');
set(handles.mit,'Visible','on');
set(handles.uipanel_ei,'Visible','on');
case 30 % CFA
case1; % hide all contols first
set(handles.na,'Visible','on');
set(handles.nat,'Visible','on');
set(handles.mi,'Visible','on');
set(handles.mit,'Visible','on');
case 31 % GPLVM
case1; % hide all contols first
set(handles.sig,'Visible','on');
set(handles.sigt,'Visible','on');
case 32 % NCA
case1;
case 33 % MCML
case1;
end
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function nd_Callback(hObject, eventdata, handles)
% hObject handle to nd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of nd as text
% str2double(get(hObject,'String')) returns contents of nd as a double
% --- Executes during object creation, after setting all properties.
function nd_CreateFcn(hObject, eventdata, handles)
% hObject handle to nd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function mi_Callback(hObject, eventdata, handles)
% hObject handle to mi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of mi as text
% str2double(get(hObject,'String')) returns contents of mi as a double
% --- Executes during object creation, after setting all properties.
function mi_CreateFcn(hObject, eventdata, handles)
% hObject handle to mi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function k_Callback(hObject, eventdata, handles)
% hObject handle to k (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of k as text
% str2double(get(hObject,'String')) returns contents of k as a double
% --- Executes during object creation, after setting all properties.
function k_CreateFcn(hObject, eventdata, handles)
% hObject handle to k (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function prc_Callback(hObject, eventdata, handles)
% hObject handle to prc (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of prc as text
% str2double(get(hObject,'String')) returns contents of prc as a double
% --- Executes during object creation, after setting all properties.
function prc_CreateFcn(hObject, eventdata, handles)
% hObject handle to prc (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function sig_Callback(hObject, eventdata, handles)
% hObject handle to sig (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of sig as text
% str2double(get(hObject,'String')) returns contents of sig as a double
% --- Executes during object creation, after setting all properties.
function sig_CreateFcn(hObject, eventdata, handles)
% hObject handle to sig (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function kgs_Callback(hObject, eventdata, handles)
% hObject handle to kgs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of kgs as text
% str2double(get(hObject,'String')) returns contents of kgs as a double
% --- Executes during object creation, after setting all properties.
function kgs_CreateFcn(hObject, eventdata, handles)
% hObject handle to kgs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function kpR_Callback(hObject, eventdata, handles)
% hObject handle to kpR (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of kpR as text
% str2double(get(hObject,'String')) returns contents of kpR as a double
% --- Executes during object creation, after setting all properties.
function kpR_CreateFcn(hObject, eventdata, handles)
% hObject handle to kpR (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function kpd_Callback(hObject, eventdata, handles)
% hObject handle to kpd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of kpd as text
% str2double(get(hObject,'String')) returns contents of kpd as a double
% --- Executes during object creation, after setting all properties.
function kpd_CreateFcn(hObject, eventdata, handles)
% hObject handle to kpd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function prp_Callback(hObject, eventdata, handles)
% hObject handle to prp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of prp as text
% str2double(get(hObject,'String')) returns contents of prp as a double
% --- Executes during object creation, after setting all properties.
function prp_CreateFcn(hObject, eventdata, handles)
% hObject handle to prp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function na_Callback(hObject, eventdata, handles)
% hObject handle to na (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of na as text
% str2double(get(hObject,'String')) returns contents of na as a double
% --- Executes during object creation, after setting all properties.
function na_CreateFcn(hObject, eventdata, handles)
% hObject handle to na (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in sm.
function sm_Callback(hObject, eventdata, handles)
set(handles.sm,'Enable','off');
drawnow;
uiresume(handles.figure1);
function t_Callback(hObject, eventdata, handles)
% hObject handle to t (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of t as text
% str2double(get(hObject,'String')) returns contents of t as a double
% --- Executes during object creation, after setting all properties.
function t_CreateFcn(hObject, eventdata, handles)
% hObject handle to t (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function uipanel_k_SelectionChangeFcn(hObject, eventdata, handles)
update_kernel_uipanel;
% --------------------------------------------------------------------
function uipanel_tp_SelectionChangeFcn(hObject, eventdata, handles)
update_type_uipanel;
% --- Executes on button press in ka.
function ka_Callback(hObject, eventdata, handles)
adaptive_callback;
|
github
|
pvarin/DynamicVAE-master
|
load_xls.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/load_xls.m
| 4,845 |
utf_8
|
98f040ec0685b024ddf99d454fea770d
|
function varargout = load_xls(varargin)
% LOAD_XLS M-file for load_xls.fig
% LOAD_XLS, by itself, creates a new LOAD_XLS or raises the existing
% singleton*.
%
% H = LOAD_XLS returns the handle to a new LOAD_XLS or the handle to
% the existing singleton*.
%
% LOAD_XLS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LOAD_XLS.M with the given input arguments.
%
% LOAD_XLS('Property','Value',...) creates a new LOAD_XLS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before load_xls_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to load_xls_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help load_xls
% Last Modified by GUIDE v2.5 11-Sep-2008 10:53:04
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @load_xls_OpeningFcn, ...
'gui_OutputFcn', @load_xls_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before load_xls is made visible.
function load_xls_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to load_xls (see VARARGIN)
% Choose default command line output for load_xls
handles.output = hObject;
nmc=varargin{1}; % number of columns
% Update handles structure
guidata(hObject, handles);
set(handles.noc,'string',num2str(nmc));
set(handles.col,'string',num2str(nmc));
cl=[0.4 0.4 0.4];
set(handles.coltxt,'ForegroundColor',cl);
set(handles.col,'Enable','off');
% UIWAIT makes load_xls wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = load_xls_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function col_Callback(hObject, eventdata, handles)
% hObject handle to col (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of col as text
% str2double(get(hObject,'String')) returns contents of col as a double
% --- Executes during object creation, after setting all properties.
function col_CreateFcn(hObject, eventdata, handles)
% hObject handle to col (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);
% --- Executes when selected object is changed in uipanel1.
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
if get(handles.uc,'value')
cl=[0 0 0];
set(handles.coltxt,'ForegroundColor',cl);
set(handles.col,'Enable','on');
else
cl=[0.4 0.4 0.4];
set(handles.coltxt,'ForegroundColor',cl);
set(handles.col,'Enable','off');
end
|
github
|
pvarin/DynamicVAE-master
|
drtool.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/drtool.m
| 52,422 |
utf_8
|
c15180ca46e1dcb99c001125b7429b14
|
function varargout = drtool(varargin)
% DRTOOL M-file for drtool.fig
% DRTOOL, by itself, creates a new DRTOOL or raises the existing
% singleton*.
%
% H = DRTOOL returns the handle to a new DRTOOL or the handle to
% the existing singleton*.
%
% DRTOOL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DRTOOL.M with the given input arguments.
%
% DRTOOL('Property','Value',...) creates a new DRTOOL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before drtool_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to drtool_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help drtool
% Last Modified by GUIDE v2.5 16-Sep-2008 12:18:29
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @drtool_OpeningFcn, ...
'gui_OutputFcn', @drtool_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before drtool is made visible.
function drtool_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to drtool (see VARARGIN)
% Choose default command line output for drtool
handles.output = hObject;
set(handles.edr,'UserData',[]); % demention not estimated at begining
% here data will be stored:
handles.X=[];
handles.labels=[];
handles.islb=false; % if labels provided
handles.isl=false; % if data loaded
handles.mcd=false; % if mapping was calculated
handles.mX=[]; % mapped X
handles.m1={}; % m-code from part1
handles.m2={}; % m-code from part2
handles.m21={}; % addition with no_dims
handles.m3={}; % m-code from part3
handles.a2=false; % if code part with no_dims was writed
handles.mstf={}; % save to file part
handles.isxls=[]; % if data loaded as xls-file (will be used before save history)
%handles.ndr=[]; % rounded number of dimention from intrinsic_dim, need for m-file
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes drtool wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = drtool_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in ld.
function ld_Callback(hObject, eventdata, handles)
handles.a2=false;
set(handles.ld,'Enable','off');
drawnow;
% load data lead to clear mapped data
handles.mcd=false; % if mapping was calculated
handles.mX=[]; % mapped X
set(handles.cd,'Visible','off');
try
hs=load_data;
catch
set(handles.ld,'Enable','on');
return
end
hands_l_d=guidata(hs);
if (~get(hands_l_d.file,'value'))&&(~get(hands_l_d.xls,'value'))
%if not from file and not from xls-file
handles.isxls=[];
set(hands_l_d.ok,'Enable','off');
drawnow;
if get(hands_l_d.sw,'value')
dataname='swiss';
end
if get(hands_l_d.hl,'value')
dataname='helix';
end
if get(hands_l_d.tp,'value')
dataname='twinpeaks';
end
if get(hands_l_d.cl,'value')
dataname='3d_clusters';
end
if get(hands_l_d.is,'value')
dataname='intersect';
end
n=str2num(get(hands_l_d.ndp,'string'));
noise=str2num(get(hands_l_d.nl,'string'));
[X, labels] = generate_data(dataname, n,noise);
handles.X=X;
handles.labels=labels;
handles.islb=true;
handles.isl=true;
set(handles.dld,'visible','on');
% m-file memorizing:
% clear all previose history because new original dataset generated:
handles.m1={};
handles.m2={};
handles.m3={};
handles.mstf={};
handles.m1={ '% generate data';
['n = ' num2str(n) '; % number of datapoints' ];
['noise = ' num2str(noise) '; % noise level' ];
['[X, labels] = generate_data(''' dataname ''', n,noise); % generate ' dataname ' data']};
delete(hands_l_d.figure1);
drawnow;
else
if get(hands_l_d.file,'value')
% here if need to load data from file
handles.isxls=false;
delete(hands_l_d.figure1);
drawnow;
S = uiimport;
if length(S)==0
handles.X=[];
handles.labels=[];
handles.islb=false;
handles.isl=false;
set(handles.dld,'visible','off');
handles.m1={};
handles.m2={};
handles.m3={};
handles.mstf={};
else
vn=fieldnames(S);
if length(vn)==1
X = getfield(S, vn{1});
hs1=load_data_1_var;
hld1=guidata(hs1);
if get(hld1.i,'value')
cn=str2num(get(hld1.cn,'string'));
lX=length(X(1,:));
ncn1=1:lX;
ncni=find(ncn1~=cn);
ncn=ncn1(ncni);
handles.X=X(:,ncn);
handles.isl=true;
set(handles.dld,'visible','on');
labels=X(:,cn);
handles.labels=labels;
handles.islb=true;
else
% one variable without labels
handles.X=X;
handles.isl=true;
set(handles.dld,'visible','on');
handles.labels=[];
handles.islb=false;
end
delete(hld1.figure1);
else
hss=load_data_vars(vn);
hlds=guidata(hss);
Xn=get(hlds.d,'string');
X = getfield(S, Xn);
if get(hlds.ni,'value') % not include
handles.labels=[];
handles.islb=false;
handles.X=X;
handles.isl=true;
set(handles.dld,'visible','on');
end
if get(hlds.iv,'value') % include from variable
ivn=get(hlds.ivn,'String');
labels = getfield(S, ivn);
handles.labels=labels;
handles.islb=true;
handles.X=X;
handles.isl=true;
set(handles.dld,'visible','on');
end
if get(hlds.ic,'value') % include from column
cn=str2num(get(hlds.icn,'String'));
lX=length(X(1,:));
ncn1=1:lX;
ncni=find(ncn1~=cn);
ncn=ncn1(ncni);
handles.X=X(:,ncn);
handles.isl=true;
set(handles.dld,'visible','on');
labels=X(:,cn);
handles.labels=labels;
handles.islb=true;
end
delete(hlds.figure1);
end
% history:
% clear:
handles.m1={};
handles.m2={};
handles.m3={};
handles.mstf={};
if handles.islb
handles.m1={'load(''X.mat''); % load data';
'load(''labels.mat''); % load labels';};
else
handles.m1={'load(''X.mat''); % load data'};
end
end
else
% here if load from xls file
handles.isxls=true;
delete(hands_l_d.figure1);
drawnow;
[FileName,PathName] = uigetfile({'*.xls';'*.xlsx'},'Select the xls-file');
if (FileName==0)
% do nothing if click cancel
else
X = xlsread([PathName FileName]); % load fom xls numbers only
handles.m1={};
handles.m2={};
handles.m3={};
handles.mstf={};
hstmp=load_xls(length(X(1,:)));
drawnow;
hands_l_x=guidata(hstmp);
if get(hands_l_x.wl,'value')
% if not use labels
handles.labels=[];
handles.islb=false;
handles.X=X;
handles.isl=true;
% history:
handles.m1={['PathName = ''' PathName '''; % path to xls-file'];
['FileName = ''' FileName '''; % file name of xls-file'];
'X = xlsread([PathName FileName]); % load xls file'};
set(handles.dld,'visible','on');
else
% if use labels
cn=str2num(get(hands_l_x.col,'String'));
lX=length(X(1,:));
ncn1=1:lX;
ncni=find(ncn1~=cn);
ncn=ncn1(ncni);
handles.X=X(:,ncn);
handles.isl=true;
set(handles.dld,'visible','on');
labels=X(:,cn);
handles.labels=labels;
handles.islb=true;
% history:
handles.m1={['PathName = ''' PathName '''; % path to xls-file'];
['FileName = ''' FileName '''; % file name of xls-file'];
'X = xlsread([PathName FileName]); % load xls file';
['cn = ' num2str(cn) '; % column number where labels are placed'];
'lX=length(X(1,:)); % total number of column';
'ncn1=1:lX;';
'ncni=find(ncn1~=cn); % indexes of data columns';
'ncn=ncn1(ncni); % data columns';
'labels=X(:,cn); % get labels';
'X=X(:,ncn); % get data'};
end
delete(hands_l_x.figure1);
drawnow;
end
end
end
set(handles.edr,'String','');
set(handles.cd,'visible','off');
handles.mcd=false;
guidata(handles.figure1, handles);
set(handles.ld,'Enable','on');
drawnow;
% --- Executes on button press in sp.
function sp_Callback(hObject, eventdata, handles)
if handles.isl
ld=length(handles.X(1,:));
if ld==2
hf=figure;
set(hf,'name','Original dataset','NumberTitle','off');
if handles.islb
scatter(handles.X(:,1),handles.X(:,2),5,handles.labels);
else
scatter(handles.X(:,1),handles.X(:,2),5);
end
title('Original dataset');
else
if handles.islb
scattern('Original dataset',handles.X,handles.labels);
else
scattern('Original dataset',handles.X);
end
end
else
% 'not loaded'
not_loaded;
end
% --- Executes on button press in p.
function p_Callback(hObject, eventdata, handles)
if handles.isl
ld=length(handles.X(1,:));
if ld==2
hf=figure;
set(hf,'name','Original dataset','NumberTitle','off');
% if handles.islb
% plot(handles.X(:,1),handles.X(:,2),5,handles.labels);
% else
plot(handles.X(:,1),handles.X(:,2),'.r');
% end
title('Original dataset');
else
% if handles.islb
% scattern('Original dataset',handles.X,handles.labels);
% else
plotn('Original dataset',handles.X);
% end
end
else
% 'not loaded'
not_loaded;
end
% --- Executes on button press in ed.
function ed_Callback(hObject, eventdata, handles)
handles.a2=false;
if handles.isl
try
s=choose_method;
catch
return
end
hs1=guidata(s);
set(hs1.ok,'Enable','off');
drawnow;
method=get(hs1.str,'string');
no_dims = intrinsic_dim(handles.X, method);
% estimate dimention lead to clear calculated data:
handles.mcd=false; % if mapping was calculated
handles.mX=[]; % mapped X
set(handles.cd,'Visible','off');
% history:
handles.m2={};
handles.m3={};
handles.mstf={};
% get detailed method name from listbox:
lstbs=get(hs1.listbox1,'string');
lstv=get(hs1.listbox1,'value');
mthds=lstbs{lstv};
handles.m2={['method_ed = ''' method '''; % (' mthds ') method of estimation of dimensionality'];
['no_dims = intrinsic_dim(X, method_ed); % estimate intrinsic dimensionality']};
delete(hs1.figure1);
drawnow;
set(handles.edr,'string',num2str(no_dims));
set(handles.edr,'UserData',no_dims); % memorize pricise value in userdata
guidata(handles.figure1, handles);
else
% 'not loaded'
not_loaded;
end
function edr_Callback(hObject, eventdata, handles)
% hObject handle to edr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edr as text
% str2double(get(hObject,'String')) returns contents of edr as a double
% --- Executes during object creation, after setting all properties.
function edr_CreateFcn(hObject, eventdata, handles)
% hObject handle to edr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cm.
function cm_Callback(hObject, eventdata, handles)
if handles.isl
handles.m3={}; % eraise priviose history
handles.mstf={};
no_dims=get(handles.edr,'UserData');
no_dims_old=no_dims;
try
s=mapping_parameters(no_dims,handles.islb);
catch
return
end
hs1=guidata(s);
%mappedA = compute_mapping(A, type, no_dims, parameters, eig_impl)
no_dims=str2num(get(hs1.nd,'string'));
%if (~handles.a2)||(round(no_dims_old)~=no_dims) % if was not added or if changed
handles.a2=true;
if ~isempty(no_dims_old)
if round(no_dims_old)~=no_dims
% if demetion was changed
handles.m21={' ';
['no_dims = ' num2str(no_dims) '; % supposed number of dimensions'];
' '};
else
handles.m21={' ';
['no_dims = round(no_dims); % round number of dimensions to have integer number'];
' '};
end
else
handles.m21={' ';
['no_dims = ' num2str(no_dims) '; % supposed number of dimensions'];
' '};
end
if isempty(handles.m2)
handles.m21={' ';
['no_dims = ' num2str(no_dims) '; % supposed number of dimensions'];
' '};
end
%handles.m2=vertcat(handles.m2,m2t);
%end
mappedA=[];
try
noparam=false; % if no parameters
mthd=''; % method when no parameters
switch get(hs1.listbox1,'Value')
case 1 % PCA
% no parameters;
mappedA = compute_mapping(handles.X, 'PCA', no_dims);
noparam=true;
mthd='PCA';
case 2 % LDA
% no parameters;
% correct lables only to column-vector:
lb=handles.labels;
slb=size(lb);
if min(slb)>1
warning('slb must be vector');
end
if slb(1)<slb(2)
lb=lb';
end
if handles.islb
mappedA = compute_mapping([lb handles.X], 'LDA', no_dims); % set labels through first column
if slb(1)<slb(2)
handles.m3={['labels=labels''; % labels must be a vector-column '];
['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']};
else
handles.m3={['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']};
end
else
% imposible because data without labels
warning('it is imposible to be here');
end
case 3 % MDS
% no parameters;
mappedA = compute_mapping(handles.X, 'MDS', no_dims);
noparam=true;
mthd='MDS';
case 4 % SimplePCA
% no parameters;
mappedA = compute_mapping(handles.X, 'SimplePCA', no_dims);
noparam=true;
mthd='SimplePCA';
case 5 % ProbPCA
mi=str2num(get(hs1.mi,'string'));
mappedA = compute_mapping(handles.X, 'ProbPCA', no_dims, mi);
handles.m3={['mi = ' num2str(mi) '; % max iterations'];
['mappedX = compute_mapping(X, ''ProbPCA'', no_dims, mi);']};
case 6 % FactorAnalysis
% no parameters;
mappedA = compute_mapping(handles.X, 'FactorAnalysis', no_dims);
noparam=true;
mthd='FactorAnalysis';
case 7 % Isomap
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
mappedA = compute_mapping(handles.X, 'Isomap', no_dims, k);
m3t={['mappedX = compute_mapping(X, ''Isomap'', no_dims, k);']};
handles.m3=vertcat(handles.m3,m3t);
case 8 % LandmarkIsomap
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
prc=str2num(get(hs1.prc,'string'));
m3t={['prc = ' num2str(prc) '; % percentage']};
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'LandmarkIsomap', no_dims, k, prc);
m3t={['mappedX = compute_mapping(X, ''LandmarkIsomap'', no_dims, k, prc);']};
handles.m3=vertcat(handles.m3,m3t);
case 9 % LLE
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
[mappedA, mapping] = compute_mapping(handles.X, 'LLE', no_dims, k, eim);
m3t={['[mappedX, mapping] = compute_mapping(X, ''LLE'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 10 % Laplacian
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
sig=str2num(get(hs1.sig,'string'));
m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']};
handles.m3=vertcat(handles.m3,m3t);
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'Laplacian', no_dims, k, sig, eim);
m3t={['mappedX = compute_mapping(X, ''Laplacian'', no_dims, k, sig, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 11 % HessianLLE
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'HessianLLE', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''HessianLLE'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 12 % LTSA
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'LTSA', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''LTSA'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 13 % MVU
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'MVU', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''MVU'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 14 % CCA
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'CCA', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''CCA'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 15 % LandmarkMVU
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
mappedA = compute_mapping(handles.X, 'LandmarkMVU', no_dims, k);
m3t={['mappedX = compute_mapping(X, ''LandmarkMVU'', no_dims, k);']};
handles.m3=vertcat(handles.m3,m3t);
case 16 % FastMVU
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
ft=get(hs1.fty,'value');
if ft
m3t={['ft = true; % finetune']};
else
m3t={['ft = false; % finetune']};
end
handles.m3=vertcat(handles.m3,m3t);
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'FastMVU', no_dims, k, ft, eim);
m3t={['mappedX = compute_mapping(X, ''FastMVU'', no_dims, k, ft, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 17 % DiffusionMaps
t=str2num(get(hs1.t,'string'));
handles.m3={['t = ' num2str(t) ';']};
sig=str2num(get(hs1.sig,'string'));
m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']};
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'DiffusionMaps', no_dims, t, sig);
m3t={['mappedX = compute_mapping(X, ''DiffusionMaps'', no_dims, t, sig);']};
handles.m3=vertcat(handles.m3,m3t);
case 18 % KernelPCA
kernel='gauss';
if get(hs1.kl,'value')
kernel='linear';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel);
handles.m3={['kernel = ''linear'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']};
end
if get(hs1.kg,'value')
s=str2num(get(hs1.kgs,'string'));
handles.m3={['s = ' num2str(s) '; % variance']};
kernel='gauss';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s);
m3t={['kernel = ''gauss'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']};
handles.m3=vertcat(handles.m3,m3t);
end
if get(hs1.kp,'value')
R=str2num(get(hs1.kpR,'string'));
handles.m3={['R = ' num2str(R) '; % additional value']};
d=str2num(get(hs1.kpd,'string'));
m3t={['d = ' num2str(d) '; % power number']};
handles.m3=vertcat(handles.m3,m3t);
kernel='poly';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d);
m3t={['kernel = ''poly'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']};
handles.m3=vertcat(handles.m3,m3t);
end
case 19 % GDA
% correct lables only to column-vector:
lb=handles.labels;
slb=size(lb);
if min(slb)>1
warning('slb must be vector');
end
if slb(1)<slb(2)
lb=lb';
end
if slb(1)<slb(2)
m3t={['labels=labels''; % labels must be a vector-column ']};
else
m3t={};
end
if handles.islb
kernel='gauss';
if get(hs1.kl,'value')
kernel='linear';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel);
handles.m3={['kernel = ''linear'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']};
handles.m3=vertcat(m3t,handles.m3);
end
if get(hs1.kg,'value')
s=str2num(get(hs1.kgs,'string'));
handles.m3={['s = ' num2str(s) '; % variance']};
handles.m3=vertcat(m3t,handles.m3);
kernel='gauss';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s);
m3t={['kernel = ''gauss'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']};
handles.m3=vertcat(handles.m3,m3t);
end
if get(hs1.kp,'value')
R=str2num(get(hs1.kpR,'string'));
handles.m3={['R = ' num2str(R) '; % additional value']};
handles.m3=vertcat(m3t,handles.m3);
d=str2num(get(hs1.kpd,'string'));
m3t={['d = ' num2str(d) '; % power number']};
handles.m3=vertcat(handles.m3,m3t);
kernel='poly';
mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d);
m3t={['kernel = ''poly'';'];
['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']};
handles.m3=vertcat(handles.m3,m3t);
end
else
% imposible because data without labels
warning('it is imposible to be here');
end
case 20 % SNE
prp=str2num(get(hs1.prp,'string'));
handles.m3={['prp = ' num2str(prp) '; % perplexity']};
mappedA = compute_mapping(handles.X, 'SNE', no_dims, prp);
m3t={['mappedX = compute_mapping(X, ''SNE'', no_dims, prp);']};
handles.m3=vertcat(handles.m3,m3t);
case 21 % SymSNE
prp=str2num(get(hs1.prp,'string'));
handles.m3={['prp = ' num2str(prp) '; % perplexity']};
mappedA = compute_mapping(handles.X, 'SymSNE', no_dims, prp);
m3t={['mappedX = compute_mapping(X, ''SymSNE'', no_dims, prp);']};
handles.m3=vertcat(handles.m3,m3t);
case 22 % t-SNE
prp=str2num(get(hs1.prp,'string'));
handles.m3={['prp = ' num2str(prp) '; % perplexity']};
mappedA = compute_mapping(handles.X, 't-SNE', no_dims, prp);
m3t={['mappedX = compute_mapping(X, ''t-SNE'', no_dims, prp);']};
handles.m3=vertcat(handles.m3,m3t);
case 23 % LPP
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
sig=str2num(get(hs1.sig,'string'));
m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']};
handles.m3=vertcat(handles.m3,m3t);
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'LPP', no_dims, k, sig, eim);
m3t={['mappedX = compute_mapping(X, ''LPP'', no_dims, k, sig, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 24 % NPE
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'NPE', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''NPE'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 25 % LLTSA
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'LLTSA', no_dims, k, eim);
m3t={['mappedX = compute_mapping(X, ''LLTSA'', no_dims, k, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 26 % SPE
tp='Global';
if get(hs1.tg,'value')
tp='Global';
mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp);
handles.m3={'tp = ''Global''; % type of stress function that minimized';
['mappedX = compute_mapping(X, ''SPE'', no_dims, tp);']};
end
if get(hs1.tl,'value')
tp='Local';
k=str2num(get(hs1.k,'string'));
mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp, k);
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph'];
'tp = ''Local''; % type of stress function that minimized';
['mappedX = compute_mapping(X, ''SPE'', no_dims, tp, k);']};
end
case 27 % AutoEncoder
% no parameters;
mappedA = compute_mapping(handles.X, 'Autoencoder', no_dims);
noparam=true;
mthd='Autoencoder';
case 28 % LLC
% no parameters;
mappedA = compute_mapping(handles.X, 'LLC', no_dims);
noparam=true;
mthd='LLC';
case 29 % LLC
if get(hs1.ka,'value')
k='adaptive';
handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']};
else
k=str2num(get(hs1.k,'string'));
handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']};
end
na=str2num(get(hs1.na,'string'));
m3t={['na = ' num2str(na) '; % number of factor analyzers']};
handles.m3=vertcat(handles.m3,m3t);
mi=str2num(get(hs1.mi,'string'));
m3t={['mi = ' num2str(mi) '; % max iterations']};
handles.m3=vertcat(handles.m3,m3t);
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
mappedA = compute_mapping(handles.X, 'LLC', no_dims, k, na, mi, eim);
m3t={['mappedX = compute_mapping(X, ''LLC'', no_dims, k, na, mi, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 30 % ManifoldChart
na=str2num(get(hs1.na,'string'));
handles.m3={['na = ' num2str(na) '; % number of factor analyzers']};
mi=str2num(get(hs1.mi,'string'));
m3t={['mi = ' num2str(mi) '; % max iterations']};
handles.m3=vertcat(handles.m3,m3t);
if get(hs1.eim,'value')
eim='Matlab';
m3t={'eim = ''Matlab''; % eigenanalysis implementation'};
else
eim='JDQR';
m3t={'eim = ''JDQR''; % eigenanalysis implementation'};
end
mappedA = compute_mapping(handles.X, 'ManifoldChart', no_dims, na, mi, eim);
m3t={['mappedX = compute_mapping(X, ''ManifoldChart'', no_dims, na, mi, eim);']};
handles.m3=vertcat(handles.m3,m3t);
case 31 % CFA
na=str2num(get(hs1.na,'string'));
handles.m3={['na = ' num2str(na) '; % number of factor analyzers']};
mi=str2num(get(hs1.mi,'string'));
m3t={['mi = ' num2str(mi) '; % max iterations']};
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'CFA', no_dims, na, mi);
m3t={['mappedX = compute_mapping(X, ''CFA'', no_dims, na, mi);']};
handles.m3=vertcat(handles.m3,m3t);
case 32 % GPLVM
sig=str2num(get(hs1.sig,'string'));
m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']};
handles.m3=vertcat(handles.m3,m3t);
mappedA = compute_mapping(handles.X, 'GPLVM', no_dims, sig);
m3t={['mappedX = compute_mapping(X, ''GPLVM'', no_dims, sig);']};
handles.m3=vertcat(handles.m3,m3t);
case 33 % NCA
mappedA = compute_mapping(handles.X, 'NCA', no_dims);
m3t={'mappedX = compute_mapping(X, ''NCA'', no_dims);'};
handles.m3=vertcat(handles.m3,m3t);
case 34 % MCML
mappedA = compute_mapping(handles.X, 'MCML', no_dims);
m3t={'mappedX = compute_mapping(X, ''MCML'', no_dims);'};
handles.m3=vertcat(handles.m3,m3t);
end
if noparam
handles.m3={['mappedX = compute_mapping(X, ''' mthd ''', no_dims); % compute mapping using ' mthd ' method']};
end
catch
set(handles.cd,'visible','off');
handles.mcd=false;
warning('mapping was not calculated');
handles.m3={};
handles.mstf={};
guidata(handles.figure1, handles);
delete(hs1.figure1);
drawnow;
rethrow(lasterror);
return
end
if length(mappedA)~=0
set(handles.cd,'visible','on');
handles.mX=mappedA;
handles.mcd=true;
else
set(handles.cd,'visible','off');
handles.mcd=false;
warning('mapping was not calculated');
handles.m3={};
handles.mstf={};
end
guidata(handles.figure1, handles);
delete(hs1.figure1);
drawnow;
else
% 'not loaded'
not_loaded;
end
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
if handles.mcd
ld=length(handles.mX(1,:));
if ld==2
hf=figure;
set(hf,'name','Result of dimensionality reduction','NumberTitle','off');
if handles.islb && size(handles.mX, 1) == numel(handles.labels)
scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels);
else
scatter(handles.mX(:,1),handles.mX(:,2),5);
end
title('Result of dimensionality reduction');
if size(handles.mX, 1) ~= numel(handles.labels)
warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.');
end
else
if ld==1
hf=figure;
set(hf,'name','Result of dimensionality reduction','NumberTitle','off');
if handles.islb && size(handles.mX, 1) == numel(handles.labels)
scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels);
else
scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5);
end
title('Result of dimensionality reduction');
if size(handles.mX, 1) ~= numel(handles.labels)
warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.');
end
else
if handles.islb
scattern('Result of dimensionality reduction',handles.mX,handles.labels);
else
scattern('Result of dimensionality reduction',handles.mX);
end
end
end
else
% 'not calulated'
not_calculated;
end
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
if handles.mcd
ld=length(handles.mX(1,:));
if ld==2
hf=figure;
set(hf,'name','Result of dimensionality reduction','NumberTitle','off');
% if handles.islb
% scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels);
% else
plot(handles.mX(:,1),handles.mX(:,2),'.r');
% end
title('Result of dimensionality reduction');
else
if ld==1
hf=figure;
set(hf,'name','Result of dimensionality reduction','NumberTitle','off');
%if handles.islb
%scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels);
%else
plot(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),'.k');
%end
title('Result of dimensionality reduction');
else
%if handles.islb
% scattern('Result of dimensionality reduction',handles.mX,handles.labels);
%else
plotn('Result of dimensionality reduction',handles.mX);
%end
end
end
else
% 'not calulated'
not_calculated;
end
% --- Executes on button press in stmf.
function stmf_Callback(hObject, eventdata, handles)
[file,path] = uiputfile('*.mat','Save Mapped Data As');
if length(file)==1
if file==0
return
end
end
mX=handles.mX;
save([path file], 'mX');
% --- Executes on button press in sttf.
function sttf_Callback(hObject, eventdata, handles)
[file,path] = uiputfile('*.txt','Save Mapped Data As');
if length(file)==1
if file==0
return
end
end
mX=handles.mX;
save([path file], 'mX','-ascii', '-tabs');
% --- Executes on button press in stf.
function stf_Callback(hObject, eventdata, handles)
set(handles.stf,'Enable','off');
drawnow;
if handles.mcd
if get(handles.stmfr,'value')
[file,path] = uiputfile('*.mat','Save Mapped Data As');
if length(file)==1
if file==0
set(handles.stf,'Enable','on');
drawnow;
return
end
end
mX=handles.mX;
save([path file], 'mX');
handles.mstf={['save(''' path file ''', ''mappedX''); % save result to mat-file']};
end
if get(handles.sttfr,'value')
[file,path] = uiputfile('*.txt','Save Mapped Data As');
if length(file)==1
if file==0
set(handles.stf,'Enable','on');
drawnow;
return
end
end
mX=handles.mX;
save([path file], 'mX','-ascii', '-tabs');
handles.mstf={['save(''' path file ''', ''mappedX'',''-ascii'', ''-tabs''); % save result to txt-file']};
end
if get(handles.stxfr,'value')
[file,path] = uiputfile('*.xls','Save Mapped Data As');
if length(file)==1
if file==0
set(handles.stf,'Enable','on');
drawnow;
return
end
end
mX=handles.mX;
xlswrite([path file], mX);
handles.mstf={['xlswrite(''' path file ''', mappedX); % save result to xls-file']};
end
guidata(handles.figure1, handles);
else
% 'not calulated'
not_calculated;
end
set(handles.stf,'Enable','on');
drawnow;
% --- Executes when selected object is changed in uipanel1.
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
% hObject handle to the selected object in uipanel1
% eventdata structure with the following fields (see UIBUTTONGROUP)
% EventName: string 'SelectionChanged' (read only)
% OldValue: handle of the previously selected object or empty if none was selected
% NewValue: handle of the currently selected object
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in sh.
function sh_Callback(hObject, eventdata, handles)
set(handles.sh,'enable','off');
drawnow;
if (isempty(handles.m1))&&(isempty(handles.m2))&&(isempty(handles.m3))
no_history;
else
[file,path] = uiputfile('*.m','Save History As');
if length(file)==1
if file==0
set(handles.sh,'enable','on');
drawnow;
return
end
end
fid = fopen([path file],'w');
fprintf(fid,'%s\r\n',['% this file was generated by drtool at ' datestr(now)]);
fprintf(fid,'%s\r\n',' '); % empty line - delimeter
if ~isempty(handles.isxls)
if ~handles.isxls
% here if txt/mat file was loaded so it is need save data and labels
X=handles.X;
save([path 'X.mat'],'X');
if handles.islb
% save labells if any
labels=handles.labels;
save([path 'labels.mat'],'labels');
fprintf(fid,'%s\r\n','% Note: data and labels were saved in X.mat and labels.mat together with this m-file in the same folder');
else
fprintf(fid,'%s\r\n','% Note: data was saved in X.mat together with this m-file in the same folder');
end
end
end
fprintf(fid,'%s\r\n',' ');
fprintf(fid,'%s\r\n','% 1.');
fprintf(fid,'%s\r\n','% get data');
for mc=1:length(handles.m1)
fprintf(fid,'%s\r\n',handles.m1{mc});
end
% plot original data:
mpod={'% plot original data:'};
ld=length(handles.X(1,:));
if ld==2
mpodt={'hf=figure;';
'set(hf,''name'',''Original dataset'',''NumberTitle'',''off'');'};
mpod=vertcat(mpod,mpodt);
if handles.islb
mpodt={'scatter(X(:,1),X(:,2),5,labels);'};
else
mpodt={'plot(X(:,1),X(:,2),''x-'');'};
end
mpod=vertcat(mpod,mpodt);
mpodt={'title(''Original dataset'');'};
mpod=vertcat(mpod,mpodt);
else
if handles.islb
mpodt={'scattern(''Original dataset'',X,labels);'};
else
mpodt={'plotn(''Original dataset'',X);'};
end
mpod=vertcat(mpod,mpodt);
end
fprintf(fid,'%s\r\n',' ');
for mc=1:length(mpod)
fprintf(fid,'%s\r\n',mpod{mc});
end
fprintf(fid,'%s\r\n',' ');
if length(handles.m2)~=0
fprintf(fid,'%s\r\n',' '); % empty line - delimeter
handles.m2=vertcat(handles.m2,handles.m21);
fprintf(fid,'%s\r\n','% 2.');
fprintf(fid,'%s\r\n','% estimate intrinsic dimensionality');
for mc=1:length(handles.m2)
fprintf(fid,'%s\r\n',handles.m2{mc});
end
else
if length(handles.m3)~=0
% if was not dimetion estimation thet it is need to set it for
% part 3
for mc=1:length(handles.m21)
fprintf(fid,'%s\r\n',handles.m21{mc});
end
end
end
if length(handles.m3)~=0
fprintf(fid,'%s\r\n',' '); % empty line - delimeter
fprintf(fid,'%s\r\n','% 3.');
fprintf(fid,'%s\r\n','% compute mapping');
for mc=1:length(handles.m3)
fprintf(fid,'%s\r\n',handles.m3{mc});
end
% plot result
mpod={'% plot result of dimensionality reduction:'};
if handles.islb
mpodt={'scatter12n(''Result of dimensionality reduction'',mappedX,labels);'};
else
mpodt={'plot12n(''Result of dimensionality reduction'',mappedX);'};
end
mpod=vertcat(mpod,mpodt);
fprintf(fid,'%s\r\n',' ');
for mc=1:length(mpod)
fprintf(fid,'%s\r\n',mpod{mc});
end
fprintf(fid,'%s\r\n',' ');
end
if length(handles.mstf)~=0
fprintf(fid,'%s\r\n',' '); % empty line - delimeter
fprintf(fid,'%s\r\n',' '); % empty line - delimeter
for mc=1:length(handles.mstf)
fprintf(fid,'%s\r\n',handles.mstf{mc});
end
end
fclose(fid);
end
set(handles.sh,'enable','on');
drawnow;
|
github
|
pvarin/DynamicVAE-master
|
plot12n.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/plot12n.m
| 1,318 |
utf_8
|
d01421c22964c2a3a5ae9dd99d026708
|
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
function plot12n(name,data)
ld=length(data(1,:));
if ld==2
hf=figure;
set(hf,'name',name,'NumberTitle','off');
% if handles.islb
% scatter(data(:,1),data(:,2),5,handles.labels);
% else
plot(data(:,1),data(:,2),'.r');
% end
title(name);
else
if ld==1
hf=figure;
set(hf,'name',name,'NumberTitle','off');
%if handles.islb
%scatter(data(:,1),zeros(length(data(:,1)),1),5,handles.labels);
%else
plot(data(:,1),zeros(length(data(:,1)),1),'.k');
%end
title(name);
else
%if handles.islb
% scattern('Result of dimensionality reduction',data,handles.labels);
%else
plotn(name,data);
%end
end
end
|
github
|
pvarin/DynamicVAE-master
|
not_loaded.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/not_loaded.m
| 7,513 |
utf_8
|
749124a9066ce5eec69372e3d16cd9d1
|
function varargout = not_loaded(varargin)
% NOT_LOADED M-file for not_loaded.fig
% NOT_LOADED by itself, creates a new NOT_LOADED or raises the
% existing singleton*.
%
% H = NOT_LOADED returns the handle to a new NOT_LOADED or the handle to
% the existing singleton*.
%
% NOT_LOADED('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in NOT_LOADED.M with the given input arguments.
%
% NOT_LOADED('Property','Value',...) creates a new NOT_LOADED or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before not_loaded_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to not_loaded_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help not_loaded
% Last Modified by GUIDE v2.5 24-Jul-2008 18:38:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @not_loaded_OpeningFcn, ...
'gui_OutputFcn', @not_loaded_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before not_loaded is made visible.
function not_loaded_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to not_loaded (see VARARGIN)
% Choose default command line output for not_loaded
handles.output = 'Yes';
% Update handles structure
guidata(hObject, handles);
% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties. See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
for index = 1:2:(nargin-3),
if nargin-3==index, break, end
switch lower(varargin{index})
case 'title'
set(hObject, 'Name', varargin{index+1});
case 'string'
set(handles.text1, 'String', varargin{index+1});
end
end
end
% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
ScreenUnits=get(0,'Units');
set(0,'Units','pixels');
ScreenSize=get(0,'ScreenSize');
set(0,'Units',ScreenUnits);
FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
GCBFOldUnits = get(gcbf,'Units');
set(gcbf,'Units','pixels');
GCBFPos = get(gcbf,'Position');
set(gcbf,'Units',GCBFOldUnits);
FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
(GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);
% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat
IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;
Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);
set(handles.axes1, ...
'Visible', 'off', ...
'YDir' , 'reverse' , ...
'XLim' , get(Img,'XData'), ...
'YLim' , get(Img,'YData') ...
);
% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')
% UIWAIT makes not_loaded wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = not_loaded_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% The figure can be deleted now
delete(handles.figure1);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = get(hObject,'String');
% Update handles structure
guidata(hObject, handles);
% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
% The GUI is still in UIWAIT, us UIRESUME
uiresume(handles.figure1);
else
% The GUI is no longer waiting, just close it
delete(handles.figure1);
end
% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
% User said no by hitting escape
handles.output = 'No';
% Update handles structure
guidata(hObject, handles);
uiresume(handles.figure1);
end
if isequal(get(hObject,'CurrentKey'),'return')
uiresume(handles.figure1);
end
|
github
|
pvarin/DynamicVAE-master
|
load_data.m
|
.m
|
DynamicVAE-master/drtoolbox/gui/load_data.m
| 6,360 |
utf_8
|
e87e4a8d82078cbbec95c41a786cd407
|
function varargout = load_data(varargin)
% LOAD_DATA M-file for load_data.fig
% LOAD_DATA, by itself, creates a new LOAD_DATA or raises the existing
% singleton*.
%
% H = LOAD_DATA returns the handle to a new LOAD_DATA or the handle to
% the existing singleton*.
%
% LOAD_DATA('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LOAD_DATA.M with the given input arguments.
%
% LOAD_DATA('Property','Value',...) creates a new LOAD_DATA or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before load_data_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to load_data_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology
% Edit the above text to modify the response to help load_data
% Last Modified by GUIDE v2.5 23-Jul-2008 16:01:33
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @load_data_OpeningFcn, ...
'gui_OutputFcn', @load_data_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before load_data is made visible.
function load_data_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to load_data (see VARARGIN)
% Choose default command line output for load_data
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes load_data wait for user response (see UIRESUME)
uiwait(handles.figure1);
% uiwait;
% --- Outputs from this function are returned to the command line.
function varargout = load_data_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function ndp_Callback(hObject, eventdata, handles)
% hObject handle to ndp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ndp as text
% str2double(get(hObject,'String')) returns contents of ndp as a double
% --- Executes during object creation, after setting all properties.
function ndp_CreateFcn(hObject, eventdata, handles)
% hObject handle to ndp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function nl_Callback(hObject, eventdata, handles)
% hObject handle to nl (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of nl as text
% str2double(get(hObject,'String')) returns contents of nl as a double
% --- Executes during object creation, after setting all properties.
function nl_CreateFcn(hObject, eventdata, handles)
% hObject handle to nl (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);
% --------------------------------------------------------------------
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
if get(handles.file,'value')
cl=[0.4 0.4 0.4];
set(handles.ndpt,'ForegroundColor',cl);
set(handles.nlt,'ForegroundColor',cl);
set(handles.ndp,'Enable','off');
set(handles.nl,'Enable','off');
set(handles.ok,'String','Start wizard');
else
cl=[0 0 0];
set(handles.ndpt,'ForegroundColor',cl);
set(handles.nlt,'ForegroundColor',cl);
set(handles.ndp,'Enable','on');
set(handles.nl,'Enable','on');
set(handles.ok,'String','OK');
end
if get(handles.xls,'value')
cl=[0.4 0.4 0.4];
set(handles.ndpt,'ForegroundColor',cl);
set(handles.nlt,'ForegroundColor',cl);
set(handles.ndp,'Enable','off');
set(handles.nl,'Enable','off');
set(handles.ok,'String','Open XLS-file');
else
if ~get(handles.file,'value')
cl=[0 0 0];
set(handles.ndpt,'ForegroundColor',cl);
set(handles.nlt,'ForegroundColor',cl);
set(handles.ndp,'Enable','on');
set(handles.nl,'Enable','on');
set(handles.ok,'String','OK');
end
end
|
github
|
pvarin/DynamicVAE-master
|
directCollocation.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/directCollocation.m
| 17,680 |
utf_8
|
99bcafa9cb7f42b2b2d8ab91d91d7e26
|
function soln = directCollocation(problem)
% soln = directCollocation(problem)
%
% OptimTraj utility function
%
% This function is designed to be called by either "trapezoid" or
% "hermiteSimpson". It actually calls FMINCON to solve the trajectory
% optimization problem.
%
% Analytic gradients are supported.
%
% NOTES:
%
% If analytic gradients are used, then the sparsity pattern is returned
% in the struct: soln.info.sparsityPattern. View it using spy().
%
%To make code more readable
G = problem.guess;
B = problem.bounds;
F = problem.func;
Opt = problem.options;
nGrid = length(F.weights);
flagGradObj = strcmp(Opt.nlpOpt.GradObj,'on');
flagGradCst = strcmp(Opt.nlpOpt.GradConstr,'on');
% Print out notice about analytic gradients
if Opt.verbose > 0
if flagGradObj
fprintf(' - using analytic gradients of objective function\n');
end
if flagGradCst
fprintf(' - using analytic gradients of constraint function\n');
end
fprintf('\n');
end
% Interpolate the guess at the grid-points for transcription:
guess.tSpan = G.time([1,end]);
guess.time = linspace(guess.tSpan(1), guess.tSpan(2), nGrid);
guess.state = interp1(G.time', G.state', guess.time')';
guess.control = interp1(G.time', G.control', guess.time')';
[zGuess, pack] = packDecVar(guess.time, guess.state, guess.control);
if flagGradCst || flagGradObj
gradInfo = grad_computeInfo(pack);
end
% Unpack all bounds:
tLow = linspace(B.initialTime.low, B.finalTime.low, nGrid);
xLow = [B.initialState.low, B.state.low*ones(1,nGrid-2), B.finalState.low];
uLow = B.control.low*ones(1,nGrid);
zLow = packDecVar(tLow,xLow,uLow);
tUpp = linspace(B.initialTime.upp, B.finalTime.upp, nGrid);
xUpp = [B.initialState.upp, B.state.upp*ones(1,nGrid-2), B.finalState.upp];
uUpp = B.control.upp*ones(1,nGrid);
zUpp = packDecVar(tUpp,xUpp,uUpp);
%%%% Set up problem for fmincon:
if flagGradObj
P.objective = @(z)( ...
myObjGrad(z, pack, F.pathObj, F.bndObj, F.weights, gradInfo) ); %Analytic gradients
[~, objGradInit] = P.objective(zGuess);
sparsityPattern.objective = (objGradInit~=0)'; % Only used for visualization!
else
P.objective = @(z)( ...
myObjective(z, pack, F.pathObj, F.bndObj, F.weights) ); %Numerical gradients
end
if flagGradCst
P.nonlcon = @(z)( ...
myCstGrad(z, pack, F.dynamics, F.pathCst, F.bndCst, F.defectCst, gradInfo) ); %Analytic gradients
[~,~,cstIneqInit,cstEqInit] = P.nonlcon(zGuess);
sparsityPattern.equalityConstraint = (cstEqInit~=0)'; % Only used for visualization!
sparsityPattern.inequalityConstraint = (cstIneqInit~=0)'; % Only used for visualization!
else
P.nonlcon = @(z)( ...
myConstraint(z, pack, F.dynamics, F.pathCst, F.bndCst, F.defectCst) ); %Numerical gradients
end
P.x0 = zGuess;
P.lb = zLow;
P.ub = zUpp;
P.Aineq = []; P.bineq = [];
P.Aeq = []; P.beq = [];
P.options = Opt.nlpOpt;
P.solver = 'fmincon';
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
[tSoln,xSoln,uSoln] = unPackDecVar(zSoln,pack);
nlpTime = toc;
%%%% Store the results:
soln.grid.time = tSoln;
soln.grid.state = xSoln;
soln.grid.control = uSoln;
soln.interp.state = @(t)( interp1(tSoln',xSoln',t','linear',nan)' );
soln.interp.control = @(t)( interp1(tSoln',uSoln',t','linear',nan)' );
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
if flagGradCst || flagGradObj % Then return sparsity pattern for visualization
if flagGradObj
[~, objGradInit] = P.objective(zSoln);
sparsityPattern.objective = (objGradInit~=0)';
end
if flagGradCst
[~,~,cstIneqInit,cstEqInit] = P.nonlcon(zSoln);
sparsityPattern.equalityConstraint = (cstEqInit~=0)';
sparsityPattern.inequalityConstraint = (cstIneqInit~=0)';
end
soln.info.sparsityPattern = sparsityPattern;
end
soln.problem = problem; % Return the fully detailed problem struct
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [z,pack] = packDecVar(t,x,u)
%
% This function collapses the time (t), state (x)
% and control (u) matricies into a single vector
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
% OUTPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
tSpan = [t(1); t(end)];
xCol = reshape(x, nState*nTime, 1);
uCol = reshape(u, nControl*nTime, 1);
indz = reshape(2+(1:numel(u)+numel(x)),nState+nControl,nTime);
% index of time, state, control variables in the decVar vector
tIdx = 1:2;
xIdx = indz(1:nState,:);
uIdx = indz(nState+(1:nControl),:);
% decision variables
% variables are indexed so that the defects gradients appear as a banded
% matrix
z = zeros(2+numel(indz),1);
z(tIdx(:),1) = tSpan;
z(xIdx(:),1) = xCol;
z(uIdx(:),1) = uCol;
pack.nTime = nTime;
pack.nState = nState;
pack.nControl = nControl;
pack.tIdx = tIdx;
pack.xIdx = xIdx;
pack.uIdx = uIdx;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [t,x,u] = unPackDecVar(z,pack)
%
% This function unpacks the decision variables for
% trajectory optimization into the time (t),
% state (x), and control (u) matricies
%
% INPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
t = linspace(z(1),z(2),nTime);
x = z(pack.xIdx);
u = z(pack.uIdx);
% make sure x and u are returned as vectors, [nState,nTime] and
% [nControl,nTime]
x = reshape(x,nState,nTime);
u = reshape(u,nControl,nTime);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function cost = myObjective(z,pack,pathObj,bndObj,weights)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
[t,x,u] = unPackDecVar(z,pack);
% Compute the cost integral along trajectory
if isempty(pathObj)
integralCost = 0;
else
dt = (t(end)-t(1))/(pack.nTime-1);
integrand = pathObj(t,x,u); %Calculate the integrand of the cost function
integralCost = dt*integrand*weights; %Trapazoidal integration
end
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
bndCost = bndObj(t0,x0,tF,xF);
end
cost = bndCost + integralCost;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [c, ceq] = myConstraint(z,pack,dynFun, pathCst, bndCst, defectCst)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynFun = user-defined dynamics function
% pathCst = user-defined constraints along the path
% endCst = user-defined constraints at the boundaries
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
[t,x,u] = unPackDecVar(z,pack);
%%%% Compute defects along the trajectory:
dt = (t(end)-t(1))/(length(t)-1);
f = dynFun(t,x,u);
defects = defectCst(dt,x,f);
%%%% Call user-defined constraints and pack up:
[c, ceq] = collectConstraints(t,x,u,defects, pathCst, bndCst);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% Additional Sub-Functions for Gradients %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function gradInfo = grad_computeInfo(pack)
%
% This function computes the matrix dimensions and indicies that are used
% to map the gradients from the user functions to the gradients needed by
% fmincon. The key difference is that the gradients in the user functions
% are with respect to their input (t,x,u) or (t0,x0,tF,xF), while the
% gradients for fmincon are with respect to all decision variables.
%
% INPUTS:
% nDeVar = number of decision variables
% pack = details about packing and unpacking the decision variables
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% gradInfo = details about how to transform gradients
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
nDecVar = 2 + nState*nTime + nControl*nTime;
zIdx = 1:nDecVar;
gradInfo.nDecVar = nDecVar;
[tIdx, xIdx, uIdx] = unPackDecVar(zIdx,pack);
gradInfo.tIdx = tIdx([1,end]);
gradInfo.xuIdx = [xIdx;uIdx];
%%%% Compute gradients of time:
% alpha = (0..N-1)/(N-1)
% t = alpha*tUpp + (1-alpha)*tLow
alpha = (0:(nTime-1))/(nTime-1);
gradInfo.alpha = [1-alpha; alpha];
if (gradInfo.tIdx(1)~=1 || gradInfo.tIdx(end)~=2)
error('The first two decision variables must be the initial and final time')
end
gradInfo.dtGrad = [-1; 1]/(nTime-1);
%%%% Compute gradients of state
gradInfo.xGrad = zeros(nState,nTime,nDecVar);
for iTime=1:nTime
for iState=1:nState
gradInfo.xGrad(iState,iTime,xIdx(iState,iTime)) = 1;
end
end
%%%% For unpacking the boundary constraints and objective:
gradInfo.bndIdxMap = [tIdx(1); xIdx(:,1); tIdx(end); xIdx(:,end)];
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,defects, defectsGrad, pathCst, bndCst, gradInfo)
% [c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,defects, defectsGrad, pathCst, bndCst, gradInfo)
%
% OptimTraj utility function.
%
% Collects the defects, calls user-defined constraints, and then packs
% everything up into a form that is good for fmincon. Additionally, it
% reshapes and packs up the gradients of these constraints.
%
% INPUTS:
% t = time vector
% x = state matrix
% u = control matrix
% defects = defects matrix
% pathCst = user-defined path constraint function
% bndCst = user-defined boundary constraint function
%
% OUTPUTS:
% c = inequality constraint for fmincon
% ceq = equality constraint for fmincon
%
ceq_dyn = reshape(defects,numel(defects),1);
ceq_dynGrad = grad_flattenPathCst(defectsGrad);
%%%% Compute the user-defined constraints:
if isempty(pathCst)
c_path = [];
ceq_path = [];
c_pathGrad = [];
ceq_pathGrad = [];
else
[c_pathRaw, ceq_pathRaw, c_pathGradRaw, ceq_pathGradRaw] = pathCst(t,x,u);
c_path = reshape(c_pathRaw,numel(c_pathRaw),1);
ceq_path = reshape(ceq_pathRaw,numel(ceq_pathRaw),1);
c_pathGrad = grad_flattenPathCst(grad_reshapeContinuous(c_pathGradRaw,gradInfo));
ceq_pathGrad = grad_flattenPathCst(grad_reshapeContinuous(ceq_pathGradRaw,gradInfo));
end
if isempty(bndCst)
c_bnd = [];
ceq_bnd = [];
c_bndGrad = [];
ceq_bndGrad = [];
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
[c_bnd, ceq_bnd, c_bndGradRaw, ceq_bndGradRaw] = bndCst(t0,x0,tF,xF);
c_bndGrad = grad_reshapeBoundary(c_bndGradRaw,gradInfo);
ceq_bndGrad = grad_reshapeBoundary(ceq_bndGradRaw,gradInfo);
end
%%%% Pack everything up:
c = [c_path;c_bnd];
ceq = [ceq_dyn; ceq_path; ceq_bnd];
cGrad = [c_pathGrad;c_bndGrad]';
ceqGrad = [ceq_dynGrad; ceq_pathGrad; ceq_bndGrad]';
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function C = grad_flattenPathCst(CC)
%
% This function takes a path constraint and reshapes the first two
% dimensions so that it can be passed to fmincon
%
if isempty(CC)
C = [];
else
[n1,n2,n3] = size(CC);
C = reshape(CC,n1*n2,n3);
end
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function CC = grad_reshapeBoundary(C,gradInfo)
%
% This function takes a boundary constraint or objective from the user
% and expands it to match the full set of decision variables
%
CC = zeros(size(C,1),gradInfo.nDecVar);
CC(:,gradInfo.bndIdxMap) = C;
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function grad = grad_reshapeContinuous(gradRaw,gradInfo)
% grad = grad_reshapeContinuous(gradRaw,gradInfo)
%
% OptimTraj utility function.
%
% This function converts the raw gradients from the user function into
% gradients with respect to the decision variables.
%
% INPUTS:
% stateRaw = [nOutput,nInput,nTime]
%
% OUTPUTS:
% grad = [nOutput,nTime,nDecVar]
%
if isempty(gradRaw)
grad = [];
else
[nOutput, ~, nTime] = size(gradRaw);
grad = zeros(nOutput,nTime,gradInfo.nDecVar);
% First, loop through and deal with time.
timeGrad = gradRaw(:,1,:); timeGrad = permute(timeGrad,[1,3,2]);
for iOutput=1:nOutput
A = ([1;1]*timeGrad(iOutput,:)).*gradInfo.alpha;
grad(iOutput,:,gradInfo.tIdx) = permute(A,[3,2,1]);
end
% Now deal with state and control:
for iOutput=1:nOutput
for iTime=1:nTime
B = gradRaw(iOutput,2:end,iTime);
grad(iOutput,iTime,gradInfo.xuIdx(:,iTime)) = permute(B,[3,1,2]);
end
end
end
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [cost, costGrad] = myObjGrad(z,pack,pathObj,bndObj,weights,gradInfo)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
%Unpack the decision variables:
[t,x,u] = unPackDecVar(z,pack);
% Time step for integration:
dt = (t(end)-t(1))/(length(t)-1);
dtGrad = gradInfo.dtGrad;
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
nDecVar = length(z);
% Compute the cost integral along the trajectory
if isempty(pathObj)
integralCost = 0;
integralCostGrad = zeros(nState+nControl,1);
else
% Objective function integrand and gradients:
[obj, objGradRaw] = pathObj(t,x,u);
nInput = size(objGradRaw,1);
objGradRaw = reshape(objGradRaw,1,nInput,nTime);
objGrad = grad_reshapeContinuous(objGradRaw,gradInfo);
% integral objective function
unScaledIntegral = obj*weights;
integralCost = dt*unScaledIntegral;
% Gradient of integral objective function
dtGradTerm = zeros(1,nDecVar);
dtGradTerm(1) = dtGrad(1)*unScaledIntegral;
dtGradTerm(2) = dtGrad(2)*unScaledIntegral;
objGrad = reshape(objGrad,nTime,nDecVar);
integralCostGrad = ...
dtGradTerm + ...
dt*sum(objGrad.*(weights*ones(1,nDecVar)),1);
end
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
bndCostGrad = zeros(1,nDecVar);
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
[bndCost, bndCostGradRaw] = bndObj(t0,x0,tF,xF);
bndCostGrad = grad_reshapeBoundary(bndCostGradRaw,gradInfo);
end
% Cost function
cost = bndCost + integralCost;
% Gradients
costGrad = bndCostGrad + integralCostGrad;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [c, ceq, cGrad, ceqGrad] = myCstGrad(z,pack,dynFun, pathCst, bndCst, defectCst, gradInfo)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynFun = user-defined dynamics function
% pathCst = user-defined constraints along the path
% endCst = user-defined constraints at the boundaries
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
%Unpack the decision variables:
[t,x,u] = unPackDecVar(z,pack);
% Time step for integration:
dt = (t(end)-t(1))/(length(t)-1);
dtGrad = gradInfo.dtGrad;
% Gradient of the state with respect to decision variables
xGrad = gradInfo.xGrad;
%%%% Compute defects along the trajectory:
[f, fGradRaw] = dynFun(t,x,u);
fGrad = grad_reshapeContinuous(fGradRaw,gradInfo);
[defects, defectsGrad] = defectCst(dt,x,f,...
dtGrad, xGrad, fGrad);
% Compute gradients of the user-defined constraints and then pack up:
[c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,...
defects, defectsGrad, pathCst, bndCst, gradInfo);
end
|
github
|
pvarin/DynamicVAE-master
|
chebyshev.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/chebyshev.m
| 10,613 |
utf_8
|
d197906d586572ca06c189288281ded9
|
function soln = chebyshev(problem)
% soln = chebyshev(problem)
%
% This function transcribes a trajectory optimization problem Chebyshev
% orthogonal polynomials for basis functions. This is an orthogonal
% collocation method, where the entire trajectory is represented as a
% single polynomial. It is for problems where the solution can be
% gaurenteed to be smooth to the same degree as the order of the underlying
% polynomial (nColPts-1).
%
% The technique is described in detail in the paper:
%
% " A Chebyshev Technique for Solving Nonlinear Optimal Control Problems"
% ISSS Trans. Automatic Control, 1988
% by: Jacques Vlassenbroeck and Rene Van Dooren
%
% My implementation for computation of the differentiation matrix,
% quadrature rules, and interpolation are based on the following:
%
% "Barycentric Lagrange Interpolation"
% Siam Review, 2004
% Publisher: Society for Industrial and Applied Mathematics
% by: Jean-Paul Berrut and Lloyd N. Trefethen
%
% "Approximation Theory and Approximation Practice"
% Textbook by Lloyd N. Trefethen
%
% "Chebfun" Matlab toolbox
% Website: http://www.chebfun.org/
% by Lloyd N. Trefethen et al.
%
% For details on the input and output, see the help file for optimTraj.m
%
% Method specific parameters:
%
% problem.options.method = 'chebyshev'
% problem.options.chebyshev = struct with method parameters:
% .nColPts = number of collocation points
%
%To make code more readable
G = problem.guess;
B = problem.bounds;
F = problem.func;
Opt = problem.options;
nColPts = Opt.chebyshev.nColPts; %Number of grid points for transcription
% Print out some solver info if desired:
if Opt.verbose > 0
disp(' -> Transcription via Chebyshev orthogonal collocation');
fprintf(' nColPts = %d \n', nColPts);
end
% Compute the parameters for the ORTHogonal polynomial, in this case the
% Chebyshev polynomial roots, quadrature weights, interpolation weights,
% and the differentiation matrix.
try
[orth.xx, orth.ww, orth.vv] = chebpts(nColPts);
catch ME
error('Missing dependency: chebfun (http://www.chebfun.org/) ');
end
orth.D = getDifferentiationMatrix(orth.xx,orth.vv);
% Interpolate the guess at the chebyshev-points for transcription:
guess.tSpan = G.time([1,end]);
guess.time = chebpts(nColPts,guess.tSpan)';
guess.state = interp1(G.time', G.state', guess.time')';
guess.control = interp1(G.time', G.control', guess.time')';
[zGuess, pack] = packDecVar(guess.time, guess.state, guess.control);
% Unpack all bounds:
dummyMatrix = zeros(1,nColPts-2); %This just needs to be the right size
tLow = [B.initialTime.low, dummyMatrix, B.finalTime.low];
xLow = [B.initialState.low, B.state.low*ones(1,nColPts-2), B.finalState.low];
uLow = B.control.low*ones(1,nColPts);
zLow = packDecVar(tLow,xLow,uLow);
tUpp = [B.initialTime.upp, dummyMatrix, B.finalTime.upp];
xUpp = [B.initialState.upp, B.state.upp*ones(1,nColPts-2), B.finalState.upp];
uUpp = B.control.upp*ones(1,nColPts);
zUpp = packDecVar(tUpp,xUpp,uUpp);
%%%% Set up problem for fmincon:
P.objective = @(z)( ...
myObjective(z, pack, F.pathObj, F.bndObj, orth) );
P.nonlcon = @(z)( ...
myConstraint(z, pack, F.dynamics, F.pathCst, F.bndCst, orth) );
P.x0 = zGuess;
P.lb = zLow;
P.ub = zUpp;
P.Aineq = []; P.bineq = [];
P.Aeq = []; P.beq = [];
P.options = Opt.nlpOpt;
P.solver = 'fmincon';
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
[tSoln,xSoln,uSoln] = unPackDecVar(zSoln,pack,orth);
nlpTime = toc;
%%%% Store the results:
soln.grid.time = tSoln;
soln.grid.state = xSoln;
soln.grid.control = uSoln;
%%%% Rescale the points:
dSoln = tSoln([1,end]); %Domain of the final solution
xxSoln = orthScale(orth,dSoln);
soln.interp.state = @(t)( barycentricInterpolate(t', xSoln',xxSoln,orth.vv)' );
soln.interp.control = @(t)( barycentricInterpolate(t', uSoln',xxSoln,orth.vv)' );
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
soln.problem = problem; % Return the fully detailed problem struct
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [z,pack] = packDecVar(t,x,u)
%
% This function collapses the time (t), state (x)
% and control (u) matricies into a single vector
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
% OUTPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
tSpan = [t(1); t(end)];
xCol = reshape(x, nState*nTime, 1);
uCol = reshape(u, nControl*nTime, 1);
z = [tSpan;xCol;uCol];
pack.nTime = nTime;
pack.nState = nState;
pack.nControl = nControl;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [t,x,u,w] = unPackDecVar(z,pack,orth)
%
% This function unpacks the decision variables for
% trajectory optimization into the time (t),
% state (x), and control (u) matricies
%
% INPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
% w = [1, nTime] = weights for clenshaw-curtis quadrature
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
nx = nState*nTime;
nu = nControl*nTime;
[t, w] = orthScale(orth,[z(1),z(2)]);
t = t';
x = reshape(z((2+1):(2+nx)),nState,nTime);
u = reshape(z((2+nx+1):(2+nx+nu)),nControl,nTime);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function cost = myObjective(z,pack,pathObj,bndObj,cheb)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
[t,x,u,w] = unPackDecVar(z,pack,cheb);
% Compute the cost integral along trajectory
if isempty(pathObj)
integralCost = 0;
else
integrand = pathObj(t,x,u); %Calculate the integrand of the cost function
integralCost = dot(w,integrand); %Clenshw-curtise quadrature
end
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
bndCost = bndObj(t0,x0,tF,xF);
end
cost = bndCost + integralCost;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [c, ceq] = myConstraint(z,pack,dynFun, pathCst, bndCst, orth)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynFun = user-defined dynamics function
% pathCst = user-defined constraints along the path
% endCst = user-defined constraints at the boundaries
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
[t,x,u] = unPackDecVar(z,pack,orth);
%%%% Enforce the dynamics:
% Analytic differentiation of the trajectory at chebyshev points:
d = t([1,end]); %Domain of the trajectory
[~,~,D] = orthScale(orth,d); %Scale the differentiation matrix
dxFun = (D*(x'))'; %Differentiate trajectory
% Derivative, according to the dynamics function:
dxDyn = dynFun(t,x,u);
% Add a constraint that both versions of the derivative must match:
defects = dxFun - dxDyn;
%%%% Call user-defined constraints and pack up:
[c, ceq] = collectConstraints(t,x,u,defects, pathCst, bndCst);
end
function [x,w,D] = orthScale(orth,d)
% [x,w,D] = orthScale(orth,d)
%
% This function scales the chebyshev points to an arbitrary interval
%
% INPUTS:
% xx = chebyshev points on the domain [-1,1]
% ww = chebysehv weights on the domain [-1,1]
% d = [low, upp] = new domain
%
% OUTPUTS:
% x = chebyshev points on the new domain d
% w = chebyshev weights on the new domain d
%
shift = 0.5*(d(1) + d(2));
scale = 0.5*(d(2) - d(1));
x = scale*orth.xx + shift;
if nargout > 1
w = orth.ww*scale;
end
if nargout > 2
D = orth.D/scale;
end
end
function D = getDifferentiationMatrix(x,v,d)
% D = getDifferentiationMatrix(x,v,d)
%
%
% INPUTS:
% x = [n,1] = vector of roots of the orthogonal polynomial of interest
% v = [n,1] = vector of barycentric weights corresponding to each root
% d = [1,2] = domain of the polynomial (optional)
%
% OUTPUTS:
% D = [n,n] = differentiation matrix such that dy/dx = D*y @ points in x
%
% NOTES:
% Reference:
% 1) ChebFun (http://www.chebfun.org/)
% 2) "Barycentric Lagrange Interpolation" SIAM Review 2004
% Jean-Paul Berrut and Lloyd N. Trefethen
%
% Inputs: x and v are typically produced by a call to any of:
% chebpts, trigpts, legpts, jacpts, lagpts, hermpts, lobpts, radaupts
%
if nargin == 2
d = [-1,1];
end
n = length(x);
D = zeros(n,n);
for i=1:n
D(i,:) = (v/v(i))./(x(i)-x);
D(i,i) = 0;
D(i,i) = -sum(D(i,:));
end
D = 2*D/(d(2)-d(1));
end
function y = barycentricInterpolate(x,yk,xk,vk)
% y = barycentricInterpolate(x,yk,xk,vk)
%
% Interpolates an orthogonal polynomial using barycentric interpolation
%
% INPUTS:
% x = [nTime, 1] = vector of points to evaluate polynomial at
% yk = [nGrid, nOut] = value of the function to be interpolated at each
% grid point
% xk = [nGrid, 1] = roots of orthogonal polynomial
% vk = [nGrid, 1] = barycentric interpolation weights
%
% OUTPUTS:
% y = [nTime, nOut] = value of the function at the desired points
%
% NOTES:
% xk and yk should be produced by chebfun (help chebpts)
%
nOut = size(yk,2);
nTime = length(x);
y = zeros(nTime, nOut);
for i=1:nOut
y(:,i) = bary(x,yk(:,i),xk,vk);
end
end
|
github
|
pvarin/DynamicVAE-master
|
hermiteSimpson.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/hermiteSimpson.m
| 11,560 |
utf_8
|
690c510dbe95d1ee31b9a2c2fcda28f8
|
function soln = hermiteSimpson(problem)
% soln = hermiteSimpson(problem)
%
% This function transcribes a trajectory optimization problem using the
% Hermite-Simpson (Seperated) method for enforcing the dynamics. It can be
% found in chapter four of Bett's book:
%
% John T. Betts, 2001
% Practical Methods for Optimal Control Using Nonlinear Programming
%
% For details on the input and output, see the help file for optimTraj.m
%
% Method specific parameters:
%
% problem.options.method = 'hermiteSimpson'
% problem.options.hermiteSimpson = struct with method parameters:
% .nSegment = number of trajectory segments
%
% This transcription method is compatable with analytic gradients. To
% enable this option, set:
% problem.nlpOpt.GradObj = 'on'
% problem.nlpOpt.GradConstr = 'on'
%
% Then the user-provided functions must provide gradients. The modified
% function templates are as follows:
%
% [dx, dxGrad] = dynamics(t,x,u)
% dx = [nState, nTime] = dx/dt = derivative of state wrt time
% dxGrad = [nState, 1+nx+nu, nTime]
%
% [dObj, dObjGrad] = pathObj(t,x,u)
% dObj = [1, nTime] = integrand from the cost function
% dObjGrad = [1+nx+nu, nTime]
%
% [c, ceq, cGrad, ceqGrad] = pathCst(t,x,u)
% c = [nCst, nTime] = column vector of inequality constraints ( c <= 0 )
% ceq = [nCstEq, nTime] = column vector of equality constraints ( c == 0 )
% cGrad = [nCst, 1+nx+nu, nTime];
% ceqGrad = [nCstEq, 1+nx+nu, nTime];
%
% [obj, objGrad] = bndObj(t0,x0,tF,xF)
% obj = scalar = objective function for boundry points
% objGrad = [1+nx+1+nx, 1]
%
% [c, ceq, cGrad, ceqGrad] = bndCst(t0,x0,tF,xF)
% c = [nCst,1] = column vector of inequality constraints ( c <= 0 )
% ceq = [nCstEq,1] = column vector of equality constraints ( c == 0 )
% cGrad = [nCst, 1+nx+1+nx];
% ceqGrad = [nCstEq, 1+nx+1+nx];
%
% NOTES:
%
% If analytic gradients are used, then the sparsity pattern is returned
% in the struct: soln.info.sparsityPattern. View it using spy().
%
% Each segment needs an additional data point in the middle, thus:
nGrid = 2*problem.options.hermiteSimpson.nSegment+1;
% Print out some solver info if desired:
if problem.options.verbose > 0
fprintf(' -> Transcription via Hermite-Simpson method, nSegment = %d\n',...
problem.options.hermiteSimpson.nSegment);
end
%%%% Method-specific details to pass along to solver:
%Simpson quadrature for integration of the cost function:
problem.func.weights = (2/3)*ones(nGrid,1);
problem.func.weights(2:2:end) = 4/3;
problem.func.weights([1,end]) = 1/3;
% Hermite-Simpson calculation of defects:
problem.func.defectCst = @computeDefects;
%%%% The key line - solve the problem by direct collocation:
soln = directCollocation(problem);
% Use method-consistent interpolation
tSoln = soln.grid.time;
xSoln = soln.grid.state;
uSoln = soln.grid.control;
fSoln = problem.func.dynamics(tSoln,xSoln,uSoln);
soln.interp.state = @(t)( pwPoly3(tSoln,xSoln,fSoln,t) );
soln.interp.control = @(t)(pwPoly2(tSoln,uSoln,t));
% Interpolation for checking collocation constraint along trajectory:
% collocation constraint = (dynamics) - (derivative of state trajectory)
soln.interp.collCst = @(t)( ...
problem.func.dynamics(t, soln.interp.state(t), soln.interp.control(t))...
- pwPoly2(tSoln,fSoln,t) );
% Use multi-segment simpson quadrature to estimate the absolute local error
% along the trajectory.
absColErr = @(t)(abs(soln.interp.collCst(t)));
nSegment = problem.options.hermiteSimpson.nSegment;
nState = size(xSoln,1);
quadTol = 1e-12; %Compute quadrature to this tolerance
soln.info.error = zeros(nState,nSegment);
for i=1:nSegment
idx = 2*i + [-1,1];
soln.info.error(:,i) = rombergQuadrature(absColErr,tSoln([idx(1), idx(2)]),quadTol);
end
soln.info.maxError = max(max(soln.info.error));
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [defects, defectsGrad] = computeDefects(dt,x,f,dtGrad,xGrad,fGrad)
%
% This function computes the defects that are used to enforce the
% continuous dynamics of the system along the trajectory.
%
% INPUTS:
% dt = time step (scalar)
% x = [nState, nTime] = state at each grid-point along the trajectory
% f = [nState, nTime] = dynamics of the state along the trajectory
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% dtGrad = [2,1] = gradient of time step with respect to [t0; tF]
% xGrad = [nState,nTime,nDecVar] = gradient of trajectory wrt dec vars
% fGrad = [nState,nTime,nDecVar] = gradient of dynamics wrt dec vars
%
% OUTPUTS:
% defects = [nState, nTime-1] = error in dynamics along the trajectory
% defectsGrad = [nState, nTime-1, nDecVars] = gradient of defects
%
nTime = size(x,2);
nState = size(x,1);
iLow = 1:2:(nTime-1);
iMid = iLow + 1;
iUpp = iMid + 1;
xLow = x(:,iLow);
xMid = x(:,iMid);
xUpp = x(:,iUpp);
fLow = f(:,iLow);
fMid = f(:,iMid);
fUpp = f(:,iUpp);
% Mid-point constraint (Hermite)
defectMidpoint = xMid - (xUpp+xLow)/2 - dt*(fLow-fUpp)/4;
% Interval constraint (Simpson)
defectInterval = xUpp - xLow - dt*(fUpp + 4*fMid + fLow)/3;
% Pack up all defects: Arrnage for bandedness
defects = zeros(nState,nTime-1);
defects(:,iLow) = defectInterval;
defects(:,iMid) = defectMidpoint;
%%%% Gradient Calculations:
if nargout == 2
xLowGrad = xGrad(:,iLow,:);
xMidGrad = xGrad(:,iMid,:);
xUppGrad = xGrad(:,iUpp,:);
fLowGrad = fGrad(:,iLow,:);
fMidGrad = fGrad(:,iMid,:);
fUppGrad = fGrad(:,iUpp,:);
% Mid-point constraint (Hermite)
dtGradTerm = zeros(size(xMidGrad));
dtGradTerm(:,:,1) = -dtGrad(1)*(fLow-fUpp)/4;
dtGradTerm(:,:,2) = -dtGrad(2)*(fLow-fUpp)/4;
defectMidpointGrad = xMidGrad - (xUppGrad+xLowGrad)/2 + dtGradTerm + ...
- dt*(fLowGrad-fUppGrad)/4;
% Interval constraint (Simpson)
dtGradTerm = zeros(size(xUppGrad));
dtGradTerm(:,:,1) = -dtGrad(1)*(fUpp + 4*fMid + fLow)/3;
dtGradTerm(:,:,2) = -dtGrad(2)*(fUpp + 4*fMid + fLow)/3;
defectIntervalGrad = xUppGrad - xLowGrad + dtGradTerm + ...
- dt*(fUppGrad + 4*fMidGrad + fLowGrad)/3;
%Pack up the gradients of the defects:
% organize defect constraints for bandned structure
defectsGrad = zeros(nState,nTime-1,size(defectMidpointGrad,3));
defectsGrad(:,iLow,:) = defectIntervalGrad;
defectsGrad(:,iMid,:) = defectMidpointGrad;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Functions for interpolation of the control solution
%
function x = pwPoly2(tGrid,xGrid,t)
% x = pwPoly2(tGrid,xGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data,
% given the function value at the edges and midpoint of the interval of
% interest.
%
% INPUTS:
% tGrid = [1, 2*n-1] = time grid, knot idx = 1:2:end
% xGrid = [m, 2*n-1] = function at each grid point in tGrid
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
nGrid = length(tGrid);
if mod(nGrid-1,2)~=0 || nGrid < 3
error('The number of grid-points must be odd and at least 3');
end
% Figure out sizes
n = floor((length(tGrid)-1)/2);
m = size(xGrid,1);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
edges = [-inf, tGrid(1:2:end), inf];
[~, bin] = histc(t,edges);
% Loop over each quadratic segment
for i=1:n
idx = bin==(i+1);
if sum(idx) > 0
gridIdx = 2*(i-1) + [1,2,3];
x(:,idx) = quadInterp(tGrid(gridIdx),xGrid(:,gridIdx),t(idx));
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==1 | bin==(n+2);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = quadInterp(tGrid,xGrid,t)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% tGrid = [1, 3] = time grid
% xGrid = [m, 3] = function grid
% t = [1, p] = query times, spanned by tGrid
%
% OUTPUTS:
% x = [m, p] = function at query times
%
% Rescale the query points to be on the domain [-1,1]
t = 2*(t-tGrid(1))/(tGrid(3)-tGrid(1)) - 1;
% Compute the coefficients:
a = 0.5*(xGrid(:,3) + xGrid(:,1)) - xGrid(:,2);
b = 0.5*(xGrid(:,3)-xGrid(:,1));
c = xGrid(:,2);
% Evaluate the polynomial for each dimension of the function:
p = length(t);
m = size(xGrid,1);
x = zeros(m,p);
tt = t.^2;
for i=1:m
x(i,:) = a(i)*tt + b(i)*t + c(i);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Functions for interpolation of the state solution
%
function x = pwPoly3(tGrid,xGrid,fGrid,t)
% x = pwPoly3(tGrid,xGrid,fGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data,
% given the function value at the edges and midpoint of the interval of
% interest.
%
% INPUTS:
% tGrid = [1, 2*n-1] = time grid, knot idx = 1:2:end
% xGrid = [m, 2*n-1] = function at each grid point in time
% fGrid = [m, 2*n-1] = derivative at each grid point in time
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
nGrid = length(tGrid);
if mod(nGrid-1,2)~=0 || nGrid < 3
error('The number of grid-points must be odd and at least 3');
end
% Figure out sizes
n = floor((length(tGrid)-1)/2);
m = size(xGrid,1);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
edges = [-inf, tGrid(1:2:end), inf];
[~, bin] = histc(t,edges);
% Loop over each quadratic segment
for i=1:n
idx = bin==(i+1);
if sum(idx) > 0
kLow = 2*(i-1) + 1;
kMid = kLow + 1;
kUpp = kLow + 2;
h = tGrid(kUpp)-tGrid(kLow);
xLow = xGrid(:,kLow);
fLow = fGrid(:,kLow);
fMid = fGrid(:,kMid);
fUpp = fGrid(:,kUpp);
alpha = t(idx) - tGrid(kLow);
x(:,idx) = cubicInterp(h,xLow, fLow, fMid, fUpp,alpha);
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==1 | bin==(n+2);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = cubicInterp(h,xLow, fLow, fMid, fUpp,del)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% h = time step (tUpp-tLow)
% xLow = function value at tLow
% fLow = derivative at tLow
% fMid = derivative at tMid
% fUpp = derivative at tUpp
% del = query points on domain [0, h]
%
% OUTPUTS:
% x = [m, p] = function at query times
%
%%% Fix matrix dimensions for vectorized calculations
nx = length(xLow);
nt = length(del);
xLow = xLow*ones(1,nt);
fLow = fLow*ones(1,nt);
fMid = fMid*ones(1,nt);
fUpp = fUpp*ones(1,nt);
del = ones(nx,1)*del;
a = (2.*(fLow - 2.*fMid + fUpp))./(3.*h.^2);
b = -(3.*fLow - 4.*fMid + fUpp)./(2.*h);
c = fLow;
d = xLow;
x = d + del.*(c + del.*(b + del.*a));
end
|
github
|
pvarin/DynamicVAE-master
|
trapezoid.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/trapezoid.m
| 7,774 |
utf_8
|
d24e512cdcb2f48f403da6b41b881bcb
|
function soln = trapezoid(problem)
% soln = trapezoid(problem)
%
% This function transcribes a trajectory optimization problem using the
% trapezoid method for enforcing the dynamics. It can be found in chapter
% four of Bett's book:
%
% John T. Betts, 2001
% Practical Methods for Optimal Control Using Nonlinear Programming
%
% For details on the input and output, see the help file for optimTraj.m
%
% Method specific parameters:
%
% problem.options.method = 'trapezoid'
% problem.options.trapezoid = struct with method parameters:
% .nGrid = number of grid points to use for transcription
%
%
% This transcription method is compatable with analytic gradients. To
% enable this option, set:
% problem.nlpOpt.GradObj = 'on'
% problem.nlpOpt.GradConstr = 'on'
%
% Then the user-provided functions must provide gradients. The modified
% function templates are as follows:
%
% [dx, dxGrad] = dynamics(t,x,u)
% dx = [nState, nTime] = dx/dt = derivative of state wrt time
% dxGrad = [nState, 1+nx+nu, nTime]
%
% [dObj, dObjGrad] = pathObj(t,x,u)
% dObj = [1, nTime] = integrand from the cost function
% dObjGrad = [1+nx+nu, nTime]
%
% [c, ceq, cGrad, ceqGrad] = pathCst(t,x,u)
% c = [nCst, nTime] = column vector of inequality constraints ( c <= 0 )
% ceq = [nCstEq, nTime] = column vector of equality constraints ( c == 0 )
% cGrad = [nCst, 1+nx+nu, nTime];
% ceqGrad = [nCstEq, 1+nx+nu, nTime];
%
% [obj, objGrad] = bndObj(t0,x0,tF,xF)
% obj = scalar = objective function for boundry points
% objGrad = [1+nx+1+nx, 1]
%
% [c, ceq, cGrad, ceqGrad] = bndCst(t0,x0,tF,xF)
% c = [nCst,1] = column vector of inequality constraints ( c <= 0 )
% ceq = [nCstEq,1] = column vector of equality constraints ( c == 0 )
% cGrad = [nCst, 1+nx+1+nx];
% ceqGrad = [nCstEq, 1+nx+1+nx];
%
% NOTES:
%
% If analytic gradients are used, then the sparsity pattern is returned
% in the struct: soln.info.sparsityPattern. View it using spy().
%
% Print out some solver info if desired:
nGrid = problem.options.trapezoid.nGrid;
if problem.options.verbose > 0
fprintf(' -> Transcription via trapezoid method, nGrid = %d\n',nGrid);
end
%%%% Method-specific details to pass along to solver:
% Quadrature weights for trapezoid integration:
problem.func.weights = ones(nGrid,1);
problem.func.weights([1,end]) = 0.5;
% Trapazoid integration calculation of defects:
problem.func.defectCst = @computeDefects;
%%%% The key line - solve the problem by direct collocation:
soln = directCollocation(problem);
% Use piecewise linear interpolation for the control
tSoln = soln.grid.time;
xSoln = soln.grid.state;
uSoln = soln.grid.control;
soln.interp.control = @(t)( interp1(tSoln',uSoln',t')' );
% Use piecewise quadratic interpolation for the state:
fSoln = problem.func.dynamics(tSoln,xSoln,uSoln);
soln.interp.state = @(t)( bSpline2(tSoln,xSoln,fSoln,t) );
% Interpolation for checking collocation constraint along trajectory:
% collocation constraint = (dynamics) - (derivative of state trajectory)
soln.interp.collCst = @(t)( ...
problem.func.dynamics(t, soln.interp.state(t), soln.interp.control(t))...
- interp1(tSoln',fSoln',t')' );
% Use multi-segment simpson quadrature to estimate the absolute local error
% along the trajectory.
absColErr = @(t)(abs(soln.interp.collCst(t)));
nSegment = nGrid-1;
nState = size(xSoln,1);
quadTol = 1e-12; %Compute quadrature to this tolerance
soln.info.error = zeros(nState,nSegment);
for i=1:nSegment
soln.info.error(:,i) = rombergQuadrature(absColErr,tSoln([i,i+1]),quadTol);
end
soln.info.maxError = max(max(soln.info.error));
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [defects, defectsGrad] = computeDefects(dt,x,f,dtGrad,xGrad,fGrad)
%
% This function computes the defects that are used to enforce the
% continuous dynamics of the system along the trajectory.
%
% INPUTS:
% dt = time step (scalar)
% x = [nState, nTime] = state at each grid-point along the trajectory
% f = [nState, nTime] = dynamics of the state along the trajectory
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% dtGrad = [2,1] = gradient of time step with respect to [t0; tF]
% xGrad = [nState,nTime,nDecVar] = gradient of trajectory wrt dec vars
% fGrad = [nState,nTime,nDecVar] = gradient of dynamics wrt dec vars
%
% OUTPUTS:
% defects = [nState, nTime-1] = error in dynamics along the trajectory
% defectsGrad = [nState, nTime-1, nDecVars] = gradient of defects
%
nTime = size(x,2);
idxLow = 1:(nTime-1);
idxUpp = 2:nTime;
xLow = x(:,idxLow);
xUpp = x(:,idxUpp);
fLow = f(:,idxLow);
fUpp = f(:,idxUpp);
% This is the key line: (Trapazoid Rule)
defects = xUpp-xLow - 0.5*dt*(fLow+fUpp);
%%%% Gradient Calculations:
if nargout == 2
xLowGrad = xGrad(:,idxLow,:);
xUppGrad = xGrad(:,idxUpp,:);
fLowGrad = fGrad(:,idxLow,:);
fUppGrad = fGrad(:,idxUpp,:);
% Gradient of the defects: (chain rule!)
dtGradTerm = zeros(size(xUppGrad));
dtGradTerm(:,:,1) = -0.5*dtGrad(1)*(fLow+fUpp);
dtGradTerm(:,:,2) = -0.5*dtGrad(2)*(fLow+fUpp);
defectsGrad = xUppGrad - xLowGrad + dtGradTerm + ...
- 0.5*dt*(fLowGrad+fUppGrad);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = bSpline2(tGrid,xGrid,fGrid,t)
% x = bSpline2(tGrid,xGrid,fGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data.
% The quadratic interpolant is constructed such that the slope matches on
% both sides of each interval, and the function value matches on the lower
% side of the interval.
%
% INPUTS:
% tGrid = [1, n] = time grid (knot points)
% xGrid = [m, n] = function at each grid point in tGrid
% fGrid = [m, n] = derivative at each grid point in tGrid
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
[m,n] = size(xGrid);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
[~, bin] = histc(t,[-inf,tGrid,inf]);
bin = bin - 1;
% Loop over each quadratic segment
for i=1:(n-1)
idx = i==bin;
if sum(idx) > 0
h = (tGrid(i+1)-tGrid(i));
xLow = xGrid(:,i);
fLow = fGrid(:,i);
fUpp = fGrid(:,i+1);
delta = t(idx) - tGrid(i);
x(:,idx) = bSpline2Core(h,delta,xLow,fLow,fUpp);
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==0 | bin==(n+1);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = bSpline2Core(h,delta,xLow,fLow,fUpp)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% alpha = fraction of the way through the interval
% xLow = function value at lower bound
% fLow = derivative at lower bound
% fUpp = derivative at upper bound
%
% OUTPUTS:
% x = [m, p] = function at query times
%
%Fix dimensions for matrix operations...
col = ones(size(delta));
row = ones(size(xLow));
delta = row*delta;
xLow = xLow*col;
fLow = fLow*col;
fUpp = fUpp*col;
fDel = (0.5/h)*(fUpp-fLow);
x = delta.*(delta.*fDel + fLow) + xLow;
end
|
github
|
pvarin/DynamicVAE-master
|
rungeKutta.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/rungeKutta.m
| 39,686 |
utf_8
|
23640bdd822c19de616e744a6202c456
|
function soln = rungeKutta(problem)
% soln = rungeKutta(problem)
%
% This function transcribes a trajectory optimization problem using the
% multiple shooting, with 4th-order Runge Kutta integration
%
% See Bett's book for details on the method
%
% For details on the input and output, see the help file for optimTraj.m
%
% Method specific parameters:
%
% problem.options.method = 'rungeKutta'
% problem.options.rungeKutta = struct with method parameters:
% .nSegment = number of trajectory segments
% .nSubStep = number of sub-steps to use in each segment
% .adaptiveDerivativeCheck = 'off' by default. Set to 'on' to enable
% numerical checks on the analytic gradients, computed using the
% derivest package, rather than fmincon's internal checks.
% Derivest is slower, but more accurate than fmincon. Derivest
% can be downloaded from the Mathworks File Exchange, file id of
% 13490 - Adaptive Robust Numerical Differentation, John D-Errico
%
%
% NOTES:
%
% Code for computing analyic gradients of the Runge Kutta method was
% contributed by Will Wehner.
%
% If analytic gradients are used, then the sparsity pattern is returned
% in the struct: soln.info.sparsityPattern. View it using spy().
%
%
%To make code more readable
G = problem.guess;
B = problem.bounds;
F = problem.func;
Opt = problem.options;
% Figure out grid size:
nSegment = Opt.rungeKutta.nSegment;
nSubStep = Opt.rungeKutta.nSubStep;
nGridControl = 2*nSegment*nSubStep + 1;
nGridState = nSegment + 1;
% Print out some solver info if desired:
if Opt.verbose > 0
fprintf(' -> Transcription via 4th-order Runge-Kutta method \n');
fprintf(' nSegments = %d \n', nSegment);
fprintf(' nSubSteps = %d \n', nSubStep);
end
% Interpolate the guess at the transcription grid points for initial guess:
guess.tSpan = G.time([1,end]);
guess.tState = linspace(guess.tSpan(1), guess.tSpan(2), nGridState);
guess.tControl = linspace(guess.tSpan(1), guess.tSpan(2), nGridControl);
guess.state = interp1(G.time', G.state', guess.tState')';
guess.control = interp1(G.time', G.control', guess.tControl')';
[zGuess, pack] = packDecVar(guess.tSpan, guess.state, guess.control);
% Unpack all bounds:
tLow = [B.initialTime.low, B.finalTime.low];
xLow = [B.initialState.low, B.state.low*ones(1,nGridState-2), B.finalState.low];
uLow = B.control.low*ones(1,nGridControl);
zLow = packDecVar(tLow,xLow,uLow);
tUpp = [B.initialTime.upp, B.finalTime.upp];
xUpp = [B.initialState.upp, B.state.upp*ones(1,nGridState-2), B.finalState.upp];
uUpp = B.control.upp*ones(1,nGridControl);
zUpp = packDecVar(tUpp,xUpp,uUpp);
%%%% Set up problem for fmincon:
flagGradObj = strcmp(Opt.nlpOpt.GradObj,'on');
flagGradCst = strcmp(Opt.nlpOpt.GradConstr,'on');
if flagGradObj || flagGradCst
gradInfo = grad_computeInfo(pack);
end
if flagGradObj
P.objective = @(z)( ...
myObjGrad(z, pack, F.dynamics, F.pathObj, F.bndObj, gradInfo) ); %Analytic gradients
[~, objGradInit] = P.objective(zGuess);
sparsityPattern.objective = (objGradInit~=0)';
else
P.objective = @(z)( ...
myObjective(z, pack, F.dynamics, F.pathObj, F.bndObj) ); %Numerical gradients
end
if flagGradCst
P.nonlcon = @(z)( ...
myCstGrad(z, pack, F.dynamics, F.pathObj, F.pathCst, F.bndCst, gradInfo) ); %Analytic gradients
[~,~,cstIneqInit,cstEqInit] = P.nonlcon(zGuess);
sparsityPattern.equalityConstraint = (cstEqInit~=0)';
sparsityPattern.inequalityConstraint = (cstIneqInit~=0)';
else
P.nonlcon = @(z)( ...
myConstraint(z, pack, F.dynamics, F.pathObj, F.pathCst, F.bndCst) ); %Numerical gradients
end
% Check analytic gradients with DERIVEST package
if strcmp(Opt.rungeKutta.adaptiveDerivativeCheck,'on')
if exist('jacobianest','file')
runGradientCheck(zGuess, pack,F.dynamics, F.pathObj, F.bndObj, F.pathCst, F.bndCst, gradInfo);
Opt.nlpOpt.DerivativeCheck = []; %Disable built-in derivative check
else
Opt.rungeKutta.adaptiveDerivativeCheck = 'cannot find jacobianest.m';
disp('Warning: the derivest package is not on search path.');
disp(' --> Using fmincon''s built-in derivative checks.');
end
end
% Build the standard fmincon problem struct
P.x0 = zGuess;
P.lb = zLow;
P.ub = zUpp;
P.Aineq = []; P.bineq = [];
P.Aeq = []; P.beq = [];
P.solver = 'fmincon';
P.options = Opt.nlpOpt;
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
[tSpan,~,uSoln] = unPackDecVar(zSoln,pack);
nlpTime = toc;
%%%% Store the results:
[tGrid,xGrid,uGrid] = simulateSystem(zSoln, pack, F.dynamics, F.pathObj);
soln.grid.time = tGrid;
soln.grid.state = xGrid;
soln.grid.control = uGrid;
% Quadratic interpolation over each sub-step for the control:
tSoln = linspace(tSpan(1),tSpan(2),nGridControl);
soln.interp.control = @(t)( interp1(tSoln', uSoln', t','pchip')' );
% Cubic spline representation of the state over each substep:
dxGrid = F.dynamics(tGrid,xGrid,uGrid);
xSpline = pwch(tGrid, xGrid, dxGrid);
soln.interp.state = @(t)( ppval(xSpline,t) );
% General information about the optimization run
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
if flagGradCst || flagGradObj
soln.info.sparsityPattern = sparsityPattern;
end
soln.problem = problem; % Return the fully detailed problem struct
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [decVars,pack] = packDecVar(tSpan,state,control)
%
% This function collapses the time (t), state (x)
% and control (u) matricies into a single vector
%
% INPUTS:
% tSpan = [1, 2] = time bounds
% state = [nState, nGridState] = state vector at each grid point
% control = [nControl, nGridControl] = control vector at each grid point
%
% OUTPUTS:
% decVars = column vector of 2 + nState*nGridState + nControl*nGridControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nState
% .nGridState
% .nControl
% .nGridControl
%
% NOTES:
% nGridControl = 2*nSegment*nSubStep + 1;
% nGridState = nSegment + 1;
%
[nState, nGridState] = size(state);
[nControl, nGridControl] = size(control);
nSegment = nGridState - 1;
nSubStep = (nGridControl - 1)/(2*nSegment);
xCol = reshape(state, nState*nGridState, 1);
uCol = reshape(control, nControl*nGridControl, 1);
indz = 1:numel(control)+numel(state)+numel(tSpan);
% index of time in decVar
indt = 1:2;
% the z index of the first element of each state over time
indtemp = 2 + (1 : (nState + (2*nSubStep)*nControl ) : numel(control)+numel(state));
% remaining state elements at each time
indx = repmat(indtemp,nState,1) + cumsum(ones(nState,nGridState),1) - 1;
% index of control in decVar
indu = indz;
indu([indt(:);indx(:)])=[];
indu = reshape(indu,nControl,nGridControl);
% pack up decVars
decVars = zeros(numel(indz),1);
decVars(indt(:),1) = tSpan;
decVars(indx(:),1) = xCol;
decVars(indu(:),1) = uCol;
% pack structure
pack.nState = nState;
pack.nGridState = nGridState;
pack.nControl = nControl;
pack.nGridControl = nGridControl;
pack.nSegment = nGridState - 1;
pack.nSubStep = (nGridControl-1)/(2*pack.nSegment);
pack.indt = indt;
pack.indx = indx;
pack.indu = indu;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [tSpan, state, control] = unPackDecVar(decVars,pack)
%
% This function unpacks the decision variables for
% trajectory optimization into the time (t),
% state (x), and control (u) matricies
%
% INPUTS:
% decVars = column vector of 2 + nState*nGridState + nControl*nGridControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nState
% .nGridState
% .nControl
% .nGridControl
%
% OUTPUTS:
% tSpan = [1, 2] = time bounds
% state = [nState, nGridState] = state vector at each grid point
% control = [nControl, nGridControl] = control vector at each grid point
%
tSpan = [decVars(1),decVars(2)];
% state = reshape(decVars((2+1):(2+nx)), pack.nState, pack.nGridState);
% control = reshape(decVars((2+nx+1):(2+nx+nu)), pack.nControl, pack.nGridControl);
state = decVars(pack.indx);
control = decVars(pack.indu);
% make sure x and u are returned as vectors, [nState,nTime] and
% [nControl,nTime]
state = reshape(state,pack.nState,pack.nGridState);
control = reshape(control,pack.nControl,pack.nGridControl);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function cost = myObjective(decVars, pack,dynamics, pathObj, bndObj)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
% bndObj = user-defined boundary objective function
%
% OUTPUTS:
% cost = scalar cost for this set of decision variables
%
%
% All of the real work happens inside this function:
[t,x,~,~,pathCost] = simulateSystem(decVars, pack, dynamics, pathObj);
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
bndCost = bndObj(t0,x0,tF,xF);
end
cost = bndCost + pathCost;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [c, ceq] = myConstraint(decVars, pack, dynamics, pathObj, pathCst, bndCst)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
% pathCst = user-defined path-constraint function
% bndCst = user-defined boundary constraint function
%
% OUTPUTS:
% c = non-linear inequality constraint
% ceq = non-linear equatlity cosntraint
%
% NOTE:
% - path constraints are satisfied at the start and end of each sub-step
%
[t,x,u,defects] = simulateSystem(decVars, pack, dynamics, pathObj);
%%%% Call user-defined constraints and pack up:
[c, ceq] = collectConstraints(t,x,u,...
defects,...
pathCst, bndCst);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [t,x,u,defects,pathCost] = simulateSystem(decVars, pack, dynFun, pathObj)
%
% This function does the real work of the transcription method. It
% simulates the system forward in time across each segment of the
% trajectory, computes the integral of the cost function, and then matches
% up the defects between the end of each segment and the start of the next.
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
%
% OUTPUTS:
% t = [1 x nGrid] = time vector for the edges of the sub-step grid
% x = [nState x nGrid] = state vector
% u = [nControl x nGrid] = control vector
% defects = [nState x nSegment] = defect matrix
% pathCost = scalar cost for the path integral
%
% NOTES:
% - nGrid = nSegment*nSubStep+1
% - This function is usually called twice for each combination of
% decision variables: once by the objective function and once by the
% constraint function. To keep the code fast I cache the old values and
% only recompute when the inputs change.
%
%%%% CODE OPTIMIZATION %%%%
%
% Prevents the same exact code from being called twice by caching the
% solution and reusing it when appropriate.
%
global RUNGE_KUTTA_t RUNGE_KUTTA_x RUNGE_KUTTA_u
global RUNGE_KUTTA_defects RUNGE_KUTTA_pathCost
global RUNGE_KUTTA_decVars
%
usePreviousValues = false;
if ~isempty(RUNGE_KUTTA_decVars)
if length(RUNGE_KUTTA_decVars) == length(decVars)
if ~any(RUNGE_KUTTA_decVars ~= decVars)
usePreviousValues = true;
end
end
end
%
if usePreviousValues
t = RUNGE_KUTTA_t;
x = RUNGE_KUTTA_x;
u = RUNGE_KUTTA_u;
defects = RUNGE_KUTTA_defects;
pathCost = RUNGE_KUTTA_pathCost;
else
%
%
%%%% END CODE OPTIMIZATION %%%%
[tSpan, state, control] = unPackDecVar(decVars,pack);
nState = pack.nState;
nSegment = pack.nSegment;
nSubStep = pack.nSubStep;
% NOTES:
% The following bit of code is a bit confusing, mostly due to the
% need for vectorization to make things run at a reasonable speed in
% Matlab. Part of the confusion comes because the decision variables
% include the state at the beginning of each segment, but the control
% at the beginning and middle of each substep - thus there are more
% control grid-points than state grid points. The calculations are
% vectorized over segments, but not sub-steps, since the result of
% one sub-step is required for the next.
% time, state, and control at the ends of each substep
nTime = 1+nSegment*nSubStep;
t = linspace(tSpan(1), tSpan(2), nTime);
x = zeros(nState, nTime);
u = control(:,1:2:end); % Control a the endpoints of each segment
uMid = control(:,2:2:end); %Control at the mid-points of each segment
c = zeros(1, nTime-1); %Integral cost for each segment
dt = (t(end)-t(1))/(nTime-1);
idx = 1:nSubStep:(nTime-1); %Indicies for the start of each segment
x(:,[idx,end]) = state; %Fill in the states that we already know
for iSubStep = 1:nSubStep
% March forward Runge-Kutta step
t0 = t(idx);
x0 = x(:,idx);
k0 = combinedDynamics(t0, x0, u(:,idx), dynFun,pathObj);
k1 = combinedDynamics(t0+0.5*dt, x0 + 0.5*dt*k0(1:nState,:), uMid(:,idx), dynFun,pathObj);
k2 = combinedDynamics(t0+0.5*dt, x0 + 0.5*dt*k1(1:nState,:), uMid(:,idx), dynFun,pathObj);
k3 = combinedDynamics(t0+dt, x0 + dt*k2(1:nState,:), u(:,idx+1), dynFun,pathObj);
z = (dt/6)*(k0 + 2*k1 + 2*k2 + k3); %Change over the sub-step
xNext = x0 + z(1:nState,:); %Next state
c(idx) = z(end,:); %Integral of the cost function over this step
if iSubStep == nSubStep %We've reached the end of the interval
% Compute the defect vector:
defects = xNext - x(:,idx+1);
else
% Store the state for next step in time
idx = idx+1; % <-- This is important!!
x(:,idx) = xNext;
end
end
pathCost = sum(c); %Sum up the integral cost over each segment
%%%% Cache results to use on the next call to this function.
RUNGE_KUTTA_t = t;
RUNGE_KUTTA_x = x;
RUNGE_KUTTA_u = u;
RUNGE_KUTTA_defects = defects;
RUNGE_KUTTA_pathCost = pathCost;
end
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function dz = combinedDynamics(t,x,u,dynFun,pathObj)
% dz = combinedDynamics(t,x,u,dynFun,pathObj)
%
% This function packages the dynamics and the cost function together so
% that they can be integrated at the same time.
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
% dynamics(t,x,u) = dynamics function handle
% dx = [nState, nTime] = dx/dt = derivative of state wrt time
% pathObj(t,x,u) = integral cost function handle
% dObj = [1, nTime] = integrand from the cost function
%
% OUTPUTS:
% dz = [dx; dObj] = combined dynamics of state and cost
dx = dynFun(t,x,u);
if isempty(pathObj)
dc = zeros(size(t));
else
dc = pathObj(t,x,u);
end
dz = [dx;dc]; %Combine and return
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% Analytic Gradient Stuff %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function gradInfo = grad_computeInfo(pack)
%
% This function computes the matrix dimensions and indicies that are used
% to map the gradients from the user functions to the gradients needed by
% fmincon. The key difference is that the gradients in the user functions
% are with respect to their input (t,x,u) or (t0,x0,tF,xF), while the
% gradients for fmincon are with respect to all decision variables.
%
% INPUTS:
% nDeVar = number of decision variables
% pack = details about packing and unpacking the decision variables
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% gradInfo = details about how to transform gradients
%
%nTime = pack.nTime;
nState = pack.nState;
nGridState = pack.nGridState;
nControl = pack.nControl;
nGridControl = pack.nGridControl;
nDecVar = 2 + nState*nGridState + nControl*nGridControl;
zIdx = 1:nDecVar;
gradInfo.nDecVar = nDecVar;
[tIdx, xIdx, uIdx] = unPackDecVar(zIdx,pack);
gradInfo.tIdx = tIdx([1,end]);
gradInfo.xIdx = xIdx;
gradInfo.uIdx = uIdx;
nSegment = pack.nSegment;
nSubStep = pack.nSubStep;
% indices of decVars associated with u
indu = 1:2:(1+2*nSegment*nSubStep);
gradInfo.indu = uIdx(:,indu);
% indices of decVars associated with uMid
indumid = 2:2:(1+2*nSegment*nSubStep);
gradInfo.indumid = uIdx(:,indumid);
%%%% For unpacking the boundary constraints and objective:
gradInfo.bndIdxMap = [tIdx(1); xIdx(:,1); tIdx(end); xIdx(:,end)];
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [fail] = runGradientCheck(z_test, pack,dynamics, pathObj, bndObj, pathCst, bndCst, gradInfo)
%
% This function tests the analytic gradients of the objective and
% nonlinear constraints with the DERIVEST package. The finite difference
% calculations in matlab's optimization package were not sufficiently
% accurate.
%
GradientCheckTol = 1e-6; %Analytic gradients must match numerical within this bound
fail = 0;
fprintf('\n%s\n','____________________________________________________________')
fprintf('%s\n',' DerivativeCheck Information with DERIVEST Package ')
% analytic gradient
[~, dcost] = myObjGrad(z_test, pack, dynamics, pathObj, bndObj, gradInfo);
% check gradient with derivest package
deriv = gradest(@(z) myObjGrad(z, pack, dynamics, pathObj, bndObj, gradInfo),z_test);
% print largest difference in numerical and analytic gradients
fprintf('\n%s\n','Objective function derivatives:')
fprintf('%s\n','Maximum relative difference between user-supplied')
fprintf('%s %1.5e \n','and finite-difference derivatives = ',max(abs(dcost-deriv')))
if any(abs(dcost-deriv') > GradientCheckTol)
error('Objective gradient did not pass')
end
% analytic nonlinear constraints
[c, ceq,dc, dceq] = myCstGrad(z_test, pack, dynamics, pathObj, pathCst, bndCst, gradInfo);
% check nonlinear inequality constraints with 'jacobianest'
if ~isempty(c)
jac = jacobianest(@(z) myConstraint(z, pack, dynamics, pathObj, pathCst, bndCst),z_test);
% print largest difference in numerical and analytic gradients
fprintf('\n%s\n','Nonlinear inequality constraint function derivatives:')
fprintf('%s\n','Maximum relative difference between user-supplied')
fprintf('%s %1.5e \n','and finite-difference derivatives = ',max(max(abs(dc-jac'))))
if any(any(abs(dc - jac') > GradientCheckTol))
error('Nonlinear inequality constraint did not pass')
end
end
% check nonlinear equality constraints with 'jacobianest'
if ~isempty(ceq)
jac = jacobianest(@(z) myCstGradCheckEq(z, pack, dynamics, pathObj, pathCst, bndCst),z_test);
% print largest difference in numerical and analytic gradients
fprintf('\n%s\n','Nonlinear equality constraint function derivatives:')
fprintf('%s\n','Maximum relative difference between user-supplied')
fprintf('%s %1.5e \n','and finite-difference derivatives = ',max(max(abs(dceq-jac'))))
if any(any(abs(dceq - jac') > GradientCheckTol))
error('Nonlinear equality constraint did not pass')
end
end
fprintf('\n%s\n','DerivativeCheck successfully passed.')
fprintf('%s\n','____________________________________________________________')
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function ceq = myCstGradCheckEq(decVars, pack, dynamics, pathObj, pathCst, bndCst)
% This function is necessary for runGradientCheck function
% return only equality constraint (ceq) for use with jacobest.m
[t,x,u,defects] = simulateSystem(decVars, pack, dynamics, pathObj);
%%%% Call user-defined constraints and pack up:
[~, ceq] = collectConstraints(t,x,u,...
defects,...
pathCst, bndCst);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [cost, dcost] = myObjGrad(decVars, pack,dynamics, pathObj, bndObj, gradInfo)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
% bndObj = user-defined boundary objective function
% gradInfo =
%
% OUTPUTS:
% cost = scalar cost for this set of decision variables
% dcost = gradient of cost
% NOTE: gradients are only available for pathCost that depends only on
% input parameters not states.
%
%
% All of the real work happens inside this function:
[t,x,~,~,pathCost,dxdalpha,dJdalpha] = simSysGrad(decVars, pack, dynamics, pathObj, gradInfo); %#ok<ASGLU>
% dxdalpha is included in outputs to make sure subsequent calls to
% simulateSystem without change a to decVars have access to the correct value
% of dxdalpha - see simulateSystem in which dxdalpha is not calculated unless
% nargout > 5
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
bndCost = bndObj(t0,x0,tF,xF);
end
cost = pathCost + bndCost;
% calculate gradient of cost function
if nargout > 1
nState = pack.nState;
nControl = pack.nControl;
nSegment = pack.nSegment;
nSubStep = pack.nSubStep;
nDecVar = 2+nState*(1+nSegment)+nControl*(1+nSegment*nSubStep*2);
% allocate gradient of cost
dcost_pth = zeros(nDecVar,1);
dcost_bnd = zeros(nDecVar,1);
% gradient assocated with bound objective
if ~isempty(bndObj)
% bound costs and gradients w.r.t. t0, x0, tF, xF
[~, d_bnd] = bndObj(t0,x0,tF,xF);
% gradients of t0, x0, tF, xF w.r.t. decision parameters (labeled alpha)
dt0_dalpha = zeros(1,nDecVar);
dt0_dalpha(1) = 1; % t0 is always the first decVar
%
dx0_dalpha = zeros(nState,nDecVar);
dx0_dalpha(1:nState,gradInfo.xIdx(:,end)) = eye(nState);
%
dtF_dalpha = zeros(1,nDecVar);
dtF_dalpha(2) = 1; % tF is always the second decVar
%
dxF_dalpha = zeros(nState,nDecVar);
dxF_dalpha(1:nState,gradInfo.xIdx(:,end)) = eye(nState);
% gradient of bound cost
dcost_bnd(:) = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * d_bnd';
end
% gradient assocated with path objective
if ~isempty(pathObj)
dcost_pth = dJdalpha';
end
dcost = dcost_pth + dcost_bnd;
end
end
function [c, ceq, dc, dceq] = myCstGrad(decVars, pack, dynamics, pathObj, pathCst, bndCst, gradInfo)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
% pathCst = user-defined path-constraint function
% bndCst = user-defined boundary constraint function
% gradInfo =
%
% OUTPUTS:
% c = non-linear inequality constraint
% ceq = non-linear equatlity cosntraint
% dc = gradient of c w.r.t. decVars
% dceq = gradient of ceq w.r.t. decVars
%
% NOTE:
% - path constraints are satisfied at the start and end of each sub-step
%
[t,x,u,defects,pathcost,dxdalpha] = simSysGrad(decVars, pack, dynamics, pathObj, gradInfo); %#ok<ASGLU>
%%%% Call user-defined constraints and pack up:
if nargout <= 2
[c, ceq] = collectConstraints(t,x,u,...
defects,...
pathCst, bndCst);
else
[c, ceq, dc, dceq] = collectConstraintsGrad(t,x,u,...
defects,...
pathCst, bndCst, pack, gradInfo, dxdalpha);
end
end
function [c, ceq, dc, dceq] = collectConstraintsGrad(t,x,u,defects, pathCst, bndCst, pack, gradInfo, dxdalpha)
% [c, ceq, dc, dceq] = collectConstraints(t,x,u,defects, pathCst, bndCst, pack, gradInfo, dxdalpha)
%
% OptimTraj utility function.
%
% Collects the defects, calls user-defined constraints, and then packs
% everything up into a form that is good for fmincon.
%
% INPUTS:
% t = time vector (time at each substep) nTime = 1+nSegment*nSubStep
% x = state matrix (states at each time in t)
% u = control matrix (control at each time in t)
% defects = defects matrix
% pathCst = user-defined path constraint function
% bndCst = user-defined boundary constraint function
% pack =
% gradInfo =
% dxdalpha = partial derivative of state at each substep w.r.t. decVars
%
% OUTPUTS:
% c = inequality constraint for fmincon
% ceq = equality constraint for fmincon
% dc = gradient of c w.r.t. decVars
% dceq = gradient of ceq w.r.t. decVars
%
% problem dimensions
nState = pack.nState;
nControl = pack.nControl;
nSegment = pack.nSegment;
nSubStep = pack.nSubStep;
nDecVar = 2+nState*(1+nSegment)+nControl*(1+nSegment*nSubStep*2);
%%%% defect constraints
ceq_dyn = reshape(defects,numel(defects),1);
dceq_dyn = zeros(nDecVar,length(ceq_dyn));
Inx = eye(nState);
for j = 1:nSegment
rows = gradInfo.xIdx(:,j+1);
cols = (j-1)*nState+(1:nState);
dceq_dyn(:,cols) = dxdalpha{j}(:,:,end)'; % gradient w.r.t. to x_i(+)
dceq_dyn(rows,cols) = -Inx; % gradient w.r.t. to x_i
end
%%%% Compute the user-defined constraints:
%%%% path constraints
if isempty(pathCst)
c_path = [];
ceq_path = [];
dc_path = [];
dceq_path = [];
else
[c_pathRaw, ceq_pathRaw, c_pathGradRaw, ceq_pathGradRaw] = pathCst(t,x,u);
c_path = reshape(c_pathRaw,numel(c_pathRaw),1);
ceq_path = reshape(ceq_pathRaw,numel(ceq_pathRaw),1);
dc_path = zeros(nDecVar,length(c_path));
dceq_path = zeros(nDecVar,length(ceq_path));
% dt/dalpha : gradient of time w.r.t. decVars
dt_dalpha = zeros(1,nDecVar);
nTime = 1+nSegment*nSubStep;
n_time = 0:nTime-1;
% gradients of path constraints
nc = size(c_pathRaw,1); % number path constraints at each time
nceq = size(ceq_pathRaw,1);
for j = 1:(nSegment+1)
for i = 1:nSubStep
% d(t[n])/dalpha
n_time0 = n_time((j-1)*nSubStep+i);
dt_dalpha(1) = (1 - n_time0/(nTime-1));
dt_dalpha(2) = (n_time0/(nTime-1));
%
if j < nSegment+1
dxi_dalpha = dxdalpha{j}(:,:,i);
else
dxi_dalpha = zeros(nState,nDecVar);
cols = gradInfo.xIdx(:,j);
dxi_dalpha(:,cols) = eye(nState);
end
%
dui_dalpha = zeros(nControl,nDecVar);
cols = gradInfo.indu(:,(j-1)*nSubStep+i);
dui_dalpha(:,cols) = eye(nControl);
% inequality path constraints
if nc > 0
cols = (1:nc) + nc*((j-1)*nSubStep+i-1);
dc_path(:,cols) = [dt_dalpha; dxi_dalpha; dui_dalpha]' * c_pathGradRaw(:,:,nSubStep*(j-1)+i)';
end
% equality path constraints
if nceq > 0
cols = (1:nceq) + nceq*((j-1)*nSubStep+i-1);
dceq_path(:,cols) = [dt_dalpha; dxi_dalpha; dui_dalpha]' * ceq_pathGradRaw(:,:,nSubStep*(j-1)+i)';
end
% no need to continue with inner loop.
if j == nSegment+1
break;
end
end
end
end
%%%% bound constraints
if isempty(bndCst)
c_bnd = [];
ceq_bnd = [];
dc_bnd = [];
dceq_bnd = [];
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
% bound constraints and gradients w.r.t. t0, x0, tF, xF
[c_bnd, ceq_bnd, d_bnd, deq_bnd] = bndCst(t0,x0,tF,xF);
% gradients of t0, x0, tF, xF w.r.t. decision parameters (labeled alpha)
dt0_dalpha = zeros(1,nDecVar);
dt0_dalpha(1) = 1; % t0 is always the first decVar
%
dx0_dalpha = zeros(nState,nDecVar);
cols = gradInfo.xIdx(:,1);
dx0_dalpha(1:nState,cols) = eye(nState);
%
dtF_dalpha = zeros(1,nDecVar);
dtF_dalpha(2) = 1; % tF is always the second decVar
%
dxF_dalpha = zeros(nState,nDecVar);
cols = gradInfo.xIdx(:,end);
dxF_dalpha(1:nState,cols) = eye(nState);
% inequality bound constraints
dc_bnd = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * d_bnd';
% equality bound constraints
dceq_bnd = [dt0_dalpha; dx0_dalpha; dtF_dalpha; dxF_dalpha]' * deq_bnd';
end
%%%% Pack everything up:
c = [c_path;c_bnd];
ceq = [ceq_dyn; ceq_path; ceq_bnd];
dc = [dc_path, dc_bnd];
dceq = [dceq_dyn, dceq_path, dceq_bnd];
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [t,x,u,defects,pathCost,dxdalpha,dJdalpha] = simSysGrad(decVars, pack, dynFun, pathObj, gradInfo)
%
% This function does the real work of the transcription method. It
% simulates the system forward in time across each segment of the
% trajectory, computes the integral of the cost function, and then matches
% up the defects between the end of each segment and the start of the next.
%
% INPUTS:
% decVars = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynamics = user-defined dynamics function handle
% pathObj = user-defined path-objective function
%
% OUTPUTS:
% t = [1 x nGrid] = time vector for the edges of the sub-step grid
% x = [nState x nGrid] = state vector
% u = [nControl x nGrid] = control vector
% defects = [nState x nSegment] = defect matrix
% pathCost = scalar cost for the path integral
%
% NOTES:
% - nGrid = nSegment*nSubStep+1
% - This function is usually called twice for each combination of
% decision variables: once by the objective function and once by the
% constraint function. To keep the code fast I cache the old values and
% only recompute when the inputs change.
%
%%%% CODE OPTIMIZATION %%%%
%
% Prevents the same exact code from being called twice by caching the
% solution and reusing it when appropriate.
%
global RUNGE_KUTTA_t RUNGE_KUTTA_x RUNGE_KUTTA_u
global RUNGE_KUTTA_defects RUNGE_KUTTA_pathCost
global RUNGE_KUTTA_decVars RUNGE_KUTTA_dxdalpha RUNGE_KUTTA_dJdalpha
%
usePreviousValues = false;
if ~isempty(RUNGE_KUTTA_decVars)
if length(RUNGE_KUTTA_decVars) == length(decVars)
if ~any(RUNGE_KUTTA_decVars ~= decVars)
usePreviousValues = true;
end
end
end
%
if usePreviousValues
t = RUNGE_KUTTA_t;
x = RUNGE_KUTTA_x;
u = RUNGE_KUTTA_u;
defects = RUNGE_KUTTA_defects;
pathCost = RUNGE_KUTTA_pathCost;
dxdalpha = RUNGE_KUTTA_dxdalpha;
dJdalpha = RUNGE_KUTTA_dJdalpha;
else
%
%
%%%% END CODE OPTIMIZATION %%%%
[tSpan, state, control] = unPackDecVar(decVars,pack);
nState = pack.nState;
nControl = pack.nControl;
nSegment = pack.nSegment;
nSubStep = pack.nSubStep;
% NOTES:
% The following bit of code is a bit confusing, mostly due to the
% need for vectorization to make things run at a reasonable speed in
% Matlab. Part of the confusion comes because the decision variables
% include the state at the beginning of each segment, but the control
% at the beginning and middle of each substep - thus there are more
% control grid-points than state grid points. The calculations are
% vectorized over segments, but not sub-steps, since the result of
% one sub-step is required for the next.
% time, state, and control at the ends of each substep
nTime = 1+nSegment*nSubStep;
t = linspace(tSpan(1), tSpan(2), nTime);
x = zeros(nState, nTime);
u = control(:,1:2:end); % Control a the endpoints of each segment
uMid = control(:,2:2:end); %Control at the mid-points of each segment
c = zeros(1, nTime-1); %Integral cost for each segment
dt = (t(end)-t(1))/(nTime-1);
idx = 1:nSubStep:(nTime-1); %Indicies for the start of each segment
x(:,[idx,end]) = state; %Fill in the states that we already know
% VARIABLES for analytic gradient evaluations.
% size of decicion parameters (2 for time), nstate*(nSegment+1), ...
% dxdalpha = partial derivative of state w.r.t. decVars (alpha)
nalpha = 2 + nState*(1+nSegment) + nControl*(1+2*nSubStep*nSegment);
dxdalpha = cell(1,nSegment);
for i = 1:nSegment
dxdalpha{i} = zeros(nState,nalpha,nSubStep+1);
cols = gradInfo.xIdx(:,i);
dxdalpha{i}(:,cols,1) = eye(nState);
end
dTdalpha = zeros(1,nalpha); dTdalpha(1:2) = [-1,1];
dt_dalpha = zeros(1,nalpha);
n_time = 0:nTime-1;
% gradient of path cost
dJdalpha = zeros(1,nalpha);
for iSubStep = 1:nSubStep
% March forward Runge-Kutta step
t0 = t(idx);
x0 = x(:,idx);
%------------------------------------------
% Code for calculating dxdalpha (partial derivative of state w.r.t.
% the descision parameters): dxdalpha = nstate x nalpha
% assume nargout <=5 when using finite difference calculation for
% gradients in which case dxdalpha is unnecessary.
% Gradient of time w.r.t. decVars
% ------------------------------------------------------------
% dt = (tF-t0)/(nTime-1)
% t = t0 + n*dt
% t = t0 + n*(tF-t0)/(nTime-1)
% t = t0*(1-n/(nTime-1)) + tF*(n/(nTime-1))
%
% alpha = [t0, tF, x0, x1, ..., xN, u0, uM0, u1, ..., uN]
% dt/dalpha = [1 - n/(nTime-1), n/(nTime-1), 0, 0, ... 0]
% ------------------------------------------------------------
n_time0 = n_time(idx);
[k0, dk0] = combinedDynGrad(t0, x0, u(:,idx), dynFun,pathObj);
[k1, dk1] = combinedDynGrad(t0+0.5*dt, x0 + 0.5*dt*k0(1:nState,:), uMid(:,idx), dynFun,pathObj);
[k2, dk2] = combinedDynGrad(t0+0.5*dt, x0 + 0.5*dt*k1(1:nState,:), uMid(:,idx), dynFun,pathObj);
[k3, dk3] = combinedDynGrad(t0+dt, x0 + dt*k2(1:nState,:), u(:,idx+1), dynFun,pathObj);
z = (dt/6)*(k0 + 2*k1 + 2*k2 + k3); %Change over the sub-step
for j = 1:nSegment
% d(t[n])/dalpha
dt_dalpha(1) = (1 - n_time0(j)/(nTime-1));
dt_dalpha(2) = (n_time0(j)/(nTime-1));
% du[n]/dalpha
du_dalpha = zeros(nControl,nalpha);
du_dalpha(:,gradInfo.indu(:,idx(j))) = eye(nControl);
% duMid[n]/dalpha
duMid_dalpha = zeros(nControl,nalpha);
duMid_dalpha(:,gradInfo.indumid(:,idx(j))) = eye(nControl);
% du[n+1]/dalpha
du1_dalpha = zeros(nControl,nalpha);
du1_dalpha(:,gradInfo.indu(:,idx(j)+1)) = eye(nControl);
% dk0/dalpha
dk0da = dk0(:,:,j) * [dt_dalpha; dxdalpha{j}(:,:,iSubStep); du_dalpha];
% dk1/dalpha
dk1da = dk1(:,:,j) * [dt_dalpha + 0.5/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + 0.5*dt*dk0da(1:nState,:) + 0.5/(nTime-1)*k0(1:nState,j)*dTdalpha; duMid_dalpha];
% dk2/dalpha
dk2da = dk2(:,:,j) * [dt_dalpha + 0.5/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + 0.5*dt*dk1da(1:nState,:) + 0.5/(nTime-1)*k1(1:nState,j)*dTdalpha; duMid_dalpha];
% dk3/dalpha
dk3da = dk3(:,:,j) * [dt_dalpha + 1/(nTime-1)*dTdalpha; dxdalpha{j}(:,:,iSubStep) + dt*dk2da(1:nState,:) + 1/(nTime-1)*k2(1:nState,j)*dTdalpha; du1_dalpha];
dz = (dt/6)*(dk0da + 2*dk1da + 2*dk2da + dk3da)...
+ 1/(6*(nTime-1))*(k0(:,j)+2*k1(:,j)+2*k2(:,j)+k3(:,j))*dTdalpha;
% update dxdalpha
dxdalpha{j}(:,:,iSubStep+1) = dxdalpha{j}(:,:,iSubStep) + dz(1:nState,:);
% update dJdalpha
dJdalpha = dJdalpha + dz(nState+1,:);
end
xNext = x0 + z(1:nState,:); %Next state
c(idx) = z(end,:); %Integral of the cost function over this step
if iSubStep == nSubStep %We've reached the end of the interval
% Compute the defect vector:
defects = xNext - x(:,idx+1);
else
% Store the state for next step in time
idx = idx+1; % <-- This is important!!
x(:,idx) = xNext;
end
end
pathCost = sum(c); %Sum up the integral cost over each segment
%%%% Cache results to use on the next call to this function.
RUNGE_KUTTA_t = t;
RUNGE_KUTTA_x = x;
RUNGE_KUTTA_u = u;
RUNGE_KUTTA_defects = defects;
RUNGE_KUTTA_pathCost = pathCost;
RUNGE_KUTTA_dxdalpha = dxdalpha;
RUNGE_KUTTA_dJdalpha = dJdalpha;
end
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [dz, J] = combinedDynGrad(t,x,u,dynFun,pathObj)
% [dz, dJ] = combinedDynGrad(t,x,u,dynFun,pathObj)
%
% This function packages the dynamics and the cost function together so
% that they can be integrated at the same time.
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
% dynamics(t,x,u) = dynamics function handle
% dx = [nState, nTime] = dx/dt = derivative of state wrt time
% pathObj(t,x,u) = integral cost function handle
% dObj = [1, nTime] = integrand from the cost function
%
% OUTPUTS:
% dz = [dx; dObj] = combined dynamics of state and cost
% dJ = [JAC(dynamics), JAC(objective)] = combined jacobian of dynamics
% and objective w.r.t. (t,x,u)
nState = size(x,1);
nControl = size(u,1);
[dx,Jx] = dynFun(t,x,u);
if isempty(pathObj)
dc = zeros(size(t));
Jc = zeros(1,1+nState+nControl,length(t));
else
[dc,Jc] = pathObj(t,x,u);
Jc = reshape(Jc,1,1+nState+nControl,length(t));
end
dz = [dx;dc];
J = cat(1,Jx,Jc);
end
|
github
|
pvarin/DynamicVAE-master
|
getDefaultOptions.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/getDefaultOptions.m
| 8,511 |
UNKNOWN
|
b0e50d99e831c558cf728ae9bb423345
|
function problem = getDefaultOptions(problem)
% problem = getDefaultOptions(problem)
%
% This function fills in any blank entries in the problem.options struct.
% It is designed to be called from inside of optimTraj.m, and not by the
% user.
%
%%%% Top-level default options:
OPT.method = 'trapezoid';
OPT.verbose = 2;
OPT.defaultAccuracy = 'medium';
%%%% Basic setup
% ensure that options is not empty
if ~isfield(problem,'options')
problem.options.method = OPT.method;
end
opt = problem.options;
% Loop over each options struct and fill in top-level options
for i=1:length(opt)
if ~isfield(opt(i),'method')
opt(i).method = OPT.method;
elseif isempty(opt(i).method)
opt(i).method = OPT.method;
end
if ~isfield(opt(i),'verbose')
opt(i).verbose = OPT.verbose;
elseif isempty(opt(i).verbose)
opt(i).verbose = OPT.verbose;
end
if ~isfield(opt(i),'defaultAccuracy')
opt(i).defaultAccuracy = OPT.defaultAccuracy;
elseif isempty(opt(i).defaultAccuracy)
opt(i).defaultAccuracy = OPT.defaultAccuracy;
end
end
% Figure out basic problem size:
nState = size(problem.guess.state,1);
nControl = size(problem.guess.control,1);
% Loop over opt and fill in nlpOpt struct:
for i=1:length(opt)
switch opt(i).verbose
case 0
NLP_display = 'notify';
case 1
NLP_display = 'final-detailed';
case 2
NLP_display = 'iter';
case 3
NLP_display = 'iter-detailed';
otherwise
error('Invalid value for options.verbose');
end
switch opt(i).defaultAccuracy
case 'low'
OPT.nlpOpt = optimset(...
'Display',NLP_display,...
'TolFun',1e-4,...
'MaxIter',200,...
'MaxFunEvals',1e4*(nState+nControl));
case 'medium'
OPT.nlpOpt = optimset(...
'Display',NLP_display,...
'TolFun',1e-6,...
'MaxIter',400,...
'MaxFunEvals',5e4*(nState+nControl));
case 'high'
OPT.nlpOpt = optimset(...
'Display',NLP_display,...
'TolFun',1e-8,...
'MaxIter',800,...
'MaxFunEvals',1e5*(nState+nControl));
otherwise
error('Invalid value for options.defaultAccuracy')
end
if isfield(opt(i),'nlpOpt')
if isstruct(opt(i).nlpOpt) && ~isempty(opt(i).nlpOpt)
names = fieldnames(opt(i).nlpOpt);
for j=1:length(names)
if ~isfield(OPT.nlpOpt,names{j})
disp(['WARNING: options.nlpOpt.' names{j} ' is not a valid option']);
else
OPT.nlpOpt.(names{j}) = opt(i).nlpOpt.(names{j});
end
end
end
end
opt(i).nlpOpt = OPT.nlpOpt;
end
% Check ChebFun dependency:
missingChebFun = false;
for i=1:length(opt)
if strcmp(opt(i).method,'chebyshev')
try
chebpts(3); %Test call to chebfun
catch ME %#ok<NASGU>
missingChebFun = true;
opt(i).method = 'trapezoid'; %Force default method
end
end
end
if missingChebFun
warning('''chebyshev'' method requires the Chebfun toolbox');
disp(' --> Install Chebfun toolbox: (http://www.chebfun.org/)');
disp(' --> Running with default method instead (''trapezoid'')');
end
% Fill in method-specific paramters:
for i=1:length(opt)
OPT_method = opt(i).method;
switch OPT_method
case 'trapezoid'
OPT.trapezoid = defaults_trapezoid(opt(i).defaultAccuracy);
case 'hermiteSimpson'
OPT.hermiteSimpson = defaults_hermiteSimpson(opt(i).defaultAccuracy);
case 'chebyshev'
OPT.chebyshev = defaults_chebyshev(opt(i).defaultAccuracy);
case 'multiCheb'
OPT.multiCheb = defaults_multiCheb(opt(i).defaultAccuracy);
case 'rungeKutta'
OPT.rungeKutta = defaults_rungeKutta(opt(i).defaultAccuracy);
case 'gpops'
OPT.gpops = defaults_gpops(opt(i).defaultAccuracy);
otherwise
error('Invalid value for options.method');
end
if isfield(opt(i),OPT_method)
if isstruct(opt(i).(OPT_method)) && ~isempty(opt(i).(OPT_method))
names = fieldnames(opt(i).(OPT_method));
for j=1:length(names)
if ~isfield(OPT.(OPT_method),names{j})
disp(['WARNING: options.' OPT_method '.' names{j} ' is not a valid option']);
else
OPT.(OPT_method).(names{j}) = opt(i).(OPT_method).(names{j});
end
end
end
end
opt(i).(OPT_method) = OPT.(OPT_method);
end
problem.options = opt;
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Method-specific parameters %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_trapezoid = defaults_trapezoid(accuracy)
switch accuracy
case 'low'
OPT_trapezoid.nGrid = 12;
case 'medium'
OPT_trapezoid.nGrid = 30;
case 'high'
OPT_trapezoid.nGrid = 60;
otherwise
error('Invalid value for options.defaultAccuracy')
end
OPT_trapezoid.adaptiveDerivativeCheck = 'off';
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_hermiteSimpson = defaults_hermiteSimpson(accuracy)
switch accuracy
case 'low'
OPT_hermiteSimpson.nSegment = 10;
case 'medium'
OPT_hermiteSimpson.nSegment = 20;
case 'high'
OPT_hermiteSimpson.nSegment = 40;
otherwise
error('Invalid value for options.defaultAccuracy')
end
OPT_hermiteSimpson.adaptiveDerivativeCheck = 'off';
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_chebyshev = defaults_chebyshev(accuracy)
switch accuracy
case 'low'
OPT_chebyshev.nColPts = 9;
case 'medium'
OPT_chebyshev.nColPts = 13;
case 'high'
OPT_chebyshev.nColPts = 23;
otherwise
error('Invalid value for options.defaultAccuracy')
end
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_multiCheb = defaults_multiCheb(accuracy)
switch accuracy
case 'low'
OPT_multiCheb.nColPts = 6;
OPT_multiCheb.nSegment = 3;
case 'medium'
OPT_multiCheb.nColPts = 8;
OPT_multiCheb.nSegment = 6;
case 'high'
OPT_multiCheb.nColPts = 8;
OPT_multiCheb.nSegment = 12;
otherwise
error('Invalid value for options.defaultAccuracy')
end
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_rungeKutta = defaults_rungeKutta(accuracy)
switch accuracy
case 'low'
OPT_rungeKutta.nSegment = 10;
OPT_rungeKutta.nSubStep = 2;
case 'medium'
OPT_rungeKutta.nSegment = 20;
OPT_rungeKutta.nSubStep = 2;
case 'high'
OPT_rungeKutta.nSegment = 20;
OPT_rungeKutta.nSubStep = 4;
otherwise
error('Invalid value for options.defaultAccuracy')
end
OPT_rungeKutta.adaptiveDerivativeCheck = 'off';
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function OPT_gpops = defaults_gpops(accuracy)
OPT_gpops.bounds.phase.integral.lower = -inf;
OPT_gpops.bounds.phase.integral.upper = inf;
OPT_gpops.guess.phase.integral = 0;
OPT_gpops.name = 'OptimTraj_GPOPS';
OPT_gpops.auxdata = [];
OPT_gpops.nlp.solver = 'ipopt'; % {'ipopt','snopt'}
OPT_gpops.derivatives.dependencies = 'full'; %�full�, �sparse� or �sparseNaN�
OPT_gpops.derivatives.supplier = 'sparseCD'; %'sparseCD'; %'adigator'
OPT_gpops.derivatives.derivativelevel = 'first'; %'second';
OPT_gpops.mesh.method = 'hp-PattersonRao';
OPT_gpops.method = 'RPM-Integration';
OPT_gpops.mesh.phase.colpoints = 10*ones(1,10);
OPT_gpops.mesh.phase.fraction = ones(1,10)/10;
OPT_gpops.scales.method = 'none'; % { 'none' , automatic-hybridUpdate' , 'automatic-bounds';
switch accuracy
case 'low'
OPT_gpops.mesh.tolerance = 1e-2;
OPT_gpops.mesh.maxiterations = 0;
case 'medium'
OPT_gpops.mesh.tolerance = 1e-3;
OPT_gpops.mesh.maxiterations = 1;
case 'high'
OPT_gpops.mesh.tolerance = 1e-4;
OPT_gpops.mesh.maxiterations = 3;
otherwise
error('Invalid value for options.defaultAccuracy')
end
end
|
github
|
pvarin/DynamicVAE-master
|
gpopsWrapper.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/gpopsWrapper.m
| 5,777 |
utf_8
|
fb8e22a03bfa72046ab9bf5458b31b1f
|
function soln = gpopsWrapper(problem)
% soln = gpopsWrapper(problem)
%
% This function is a wrapper that converts the standard input for optimTraj
% into a call to GPOPS2, a commercially available transcription software
% for matlab. You can purchase and download it at http://www.gpops2.com/
%
% GPOPS2 implements an adaptive transcription method - it adjusts both the
% number of trajectory segments and the order of the interpolating
% polynomial in each segment. Many GPOPS features are available in OptimTraj,
% but not all. Notably, OptimTraj cannot solve multi-phase problems.
%
% Set any special GPOPS options by storing the 'setup' sturuct in the
% problem.options.gpops struct.
%
% If using SNOPT, be careful about any constant terms in your constraints.
% When using numerical gradients, SNOPT drops any constant terms in your
% constraints, which is why it has non-zero bounds. This is exactly the
% opposite of the convention that FMINCON uses, where all constraint bounds
% must be zero. If your constraints have non-zero bounds, and you would
% like to use GPOPS with SNOPT as the solver, then manually set the fields
% in problem.gpops.phase.bounds.path and problem.gpops.eventgroup to
% include these bounds, and then remove them from the constraint function.
%
% Print out some solver info if desired:
if problem.options.verbose > 0
disp('Transcription using GPOPS2');
end
% Copy the problem specification
setup = problem.options.gpops;
setup.bounds.phase.initialtime.lower = problem.bounds.initialTime.low';
setup.bounds.phase.initialtime.upper = problem.bounds.initialTime.upp';
setup.bounds.phase.finaltime.lower = problem.bounds.finalTime.low';
setup.bounds.phase.finaltime.upper = problem.bounds.finalTime.upp';
setup.bounds.phase.initialstate.lower = problem.bounds.initialState.low';
setup.bounds.phase.initialstate.upper = problem.bounds.initialState.upp';
setup.bounds.phase.finalstate.lower = problem.bounds.finalState.low';
setup.bounds.phase.finalstate.upper = problem.bounds.finalState.upp';
setup.bounds.phase.state.lower = problem.bounds.state.low';
setup.bounds.phase.state.upper = problem.bounds.state.upp';
setup.bounds.phase.control.lower = problem.bounds.control.low';
setup.bounds.phase.control.upper = problem.bounds.control.upp';
setup.guess.phase.time = problem.guess.time';
setup.guess.phase.state = problem.guess.state';
setup.guess.phase.control = problem.guess.control';
% Configure bounds on the path constraints
if ~isempty(problem.func.pathCst)
if ~isfield(setup.bounds.phase, 'path')
[cTest, ceqTest] = problem.func.pathCst(...
problem.guess.time,problem.guess.state,problem.guess.control);
nc = size(cTest,1);
nceq = size(ceqTest,1);
setup.bounds.phase.path.lower = [-inf(1,nc), zeros(1,nceq)];
setup.bounds.phase.path.upper = zeros(1,nc+nceq);
end
end
% Configure bounds on the endpoint constraints
if ~isempty(problem.func.bndCst)
if ~isfield(setup.bounds, 'eventgroup')
t0 = problem.guess.time(1); tF = problem.guess.time(end);
x0 = problem.guess.state(:,1); xF = problem.guess.state(:,end);
[cTest, ceqTest] = problem.func.bndCst(t0, x0,tF,xF);
nc = size(cTest,1);
nceq = size(ceqTest,1);
setup.bounds.eventgroup.lower = [-inf(1,nc), zeros(1,nceq)];
setup.bounds.eventgroup.upper = zeros(1,nc+nceq);
end
end
F = problem.func;
setup.functions.continuous = @(input)( gpops_continuous(input,F.dynamics,F.pathObj,F.pathCst) );
setup.functions.endpoint = @(input)( gpops_endpoint(input,F.bndObj,F.bndCst) );
%%%% KEY LINE: Solve the optimization problem with GPOPS II
output = gpops2(setup);
% Pack up the results:
soln.grid.time = output.result.solution.phase.time';
soln.grid.state = output.result.solution.phase.state';
soln.grid.control = output.result.solution.phase.control';
tSoln = output.result.interpsolution.phase.time';
xSoln = output.result.interpsolution.phase.state';
uSoln = output.result.interpsolution.phase.control';
soln.interp.state = @(t)( interp1(tSoln',xSoln',t','pchip',nan)' );
soln.interp.control = @(t)( interp1(tSoln',uSoln',t','pchip',nan)' );
soln.info.nlpTime = output.totaltime;
soln.info.objVal = output.result.objective;
soln.info.gpops.meshcounts = output.meshcounts;
soln.info.gpops.result.maxerror = output.result.maxerror;
soln.info.gpops.result.nlpinfo = output.result.nlpinfo;
soln.info.gpops.result.setup = output.result.setup;
soln.problem = problem;
soln.problem.options.nlpOpt = []; % did not use the fmincon options
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function output = gpops_endpoint(input,bndObj,bndCst)
%
% The endpoint function contains the boundary constraints and objective
% functions for the trajectory optimization problem.
%
t0 = input.phase.initialtime;
tF = input.phase.finaltime;
x0 = input.phase.initialstate';
xF = input.phase.finalstate';
if isempty(bndObj)
output.objective = input.phase.integral;
else
output.objective = input.phase.integral + bndObj(t0,x0,tF,xF);
end
if ~isempty(bndCst)
[c, ceq] = bndCst(t0,x0,tF,xF);
output.eventgroup.event = [c;ceq]';
end
end
function output = gpops_continuous(input,dynamics,pathObj,pathCst)
%
% The continuous function contains the path objective, dynamics, and path
% constraint functions.
%
t = input.phase.time';
x = input.phase.state';
u = input.phase.control';
f = dynamics(t,x,u);
c = pathObj(t,x,u);
output.dynamics = f';
output.integrand = c';
if ~isempty(pathCst)
[c, ceq] = pathCst(t,x,u);
output.path = [c;ceq]';
end
end
|
github
|
pvarin/DynamicVAE-master
|
inputValidation.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/inputValidation.m
| 4,319 |
utf_8
|
394cd18a2f88465b4d3adbfe71561f8c
|
function problem = inputValidation(problem)
%
% This function runs through the problem struct and sets any missing fields
% to the default value. If a mandatory field is missing, then it throws an
% error.
%
% INPUTS:
% problem = a partially completed problem struct
%
% OUTPUTS:
% problem = a complete problem struct, with validated fields
%
%%%% Check the function handles:
if ~isfield(problem,'func')
error('Field ''func'' cannot be ommitted from ''problem''');
else
if ~isfield(problem.func,'dynamics')
error('Field ''dynamics'' cannot be ommitted from ''problem.func'''); end
if ~isfield(problem.func,'pathObj'), problem.func.pathObj = []; end
if ~isfield(problem.func,'bndObj'), problem.func.bndObj = []; end
if ~isfield(problem.func,'pathCst'), problem.func.pathCst = []; end
if ~isfield(problem.func,'bndCst'), problem.func.bndCst = []; end
end
%%%% Check the initial guess (also compute nState and nControl):
if ~isfield(problem, 'guess')
error('Field ''guess'' cannot be ommitted from ''problem''');
else
if ~isfield(problem.guess,'time')
error('Field ''time'' cannot be ommitted from ''problem.guess'''); end
if ~isfield(problem.guess, 'state')
error('Field ''state'' cannot be ommitted from ''problem.guess'''); end
if ~isfield(problem.guess, 'control')
error('Field ''control'' cannot be ommitted from ''problem.guess'''); end
% Compute the size of the time, state, and control based on guess
[checkOne, nTime] = size(problem.guess.time);
[nState, checkTimeState] = size(problem.guess.state);
[nControl, checkTimeControl] = size(problem.guess.control);
if nTime < 2 || checkOne ~= 1
error('guess.time must have dimensions of [1, nTime], where nTime > 1');
end
if checkTimeState ~= nTime
error('guess.state must have dimensions of [nState, nTime]');
end
if checkTimeControl ~= nTime
error('guess.control must have dimensions of [nControl, nTime]');
end
end
%%%% Check the problem bounds:
if ~isfield(problem,'bounds')
problem.bounds.initialTime = [];
problem.bounds.finalTime = [];
problem.bounds.state = [];
problem.bounds.initialState = [];
problem.bounds.finalState = [];
problem.bounds.control = [];
else
if ~isfield(problem.bounds,'initialTime')
problem.bounds.initialTime = []; end
problem.bounds.initialTime = ...
checkLowUpp(problem.bounds.initialTime,1,1,'initialTime');
if ~isfield(problem.bounds,'finalTime')
problem.bounds.finalTime = []; end
problem.bounds.finalTime = ...
checkLowUpp(problem.bounds.finalTime,1,1,'finalTime');
if ~isfield(problem.bounds,'state')
problem.bounds.state = []; end
problem.bounds.state = ...
checkLowUpp(problem.bounds.state,nState,1,'state');
if ~isfield(problem.bounds,'initialState')
problem.bounds.initialState = []; end
problem.bounds.initialState = ...
checkLowUpp(problem.bounds.initialState,nState,1,'initialState');
if ~isfield(problem.bounds,'finalState')
problem.bounds.finalState = []; end
problem.bounds.finalState = ...
checkLowUpp(problem.bounds.finalState,nState,1,'finalState');
if ~isfield(problem.bounds,'control')
problem.bounds.control = []; end
problem.bounds.control = ...
checkLowUpp(problem.bounds.control,nControl,1,'control');
end
end
function input = checkLowUpp(input,nRow,nCol,name)
%
% This function checks that input has the following is true:
% size(input.low) == [nRow, nCol]
% size(input.upp) == [nRow, nCol]
if ~isfield(input,'low')
input.low = -inf(nRow,nCol);
end
if ~isfield(input,'upp')
input.upp = inf(nRow,nCol);
end
[lowRow, lowCol] = size(input.low);
if lowRow ~= nRow || lowCol ~= nCol
error(['problem.bounds.' name ...
'.low must have size = [' num2str(nRow) ', ' num2str(nCol) ']']);
end
[uppRow, uppCol] = size(input.upp);
if uppRow ~= nRow || uppCol ~= nCol
error(['problem.bounds.' name ...
'.upp must have size = [' num2str(nRow) ', ' num2str(nCol) ']']);
end
if sum(sum(input.upp-input.low < 0))
error(...
['problem.bounds.' name '.upp must be >= problem.bounds.' name '.low!']);
end
end
|
github
|
pvarin/DynamicVAE-master
|
multiCheb.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/multiCheb.m
| 21,236 |
utf_8
|
f3b52105bdd4fc219954b4149df07295
|
function soln = multiCheb(problem)
% soln = multiCheb(problem)
%
% DEPRICATED
%
%
% *************************************************************************
% This file is no longer used, and is preserved for reference only. The
% numerical methods for connecting segments are not the most stable,
% particularily for low-order polynomials. This file will later be replaced
% with HP orthogonal collocation, based on Legendre polynomials.
% *************************************************************************
%
%
% This function transcribes a trajectory optimization problem Chebyshev
% orthogonal polynomials for basis functions. This is an orthogonal
% collocation method. This method is similiar to Chebyshev, except that
% here I break the trajectory into several segments, rahter than just one.
%
% The technique is similar to the one described in detail in the paper:
%
% " A Chebyshev Technique for Solving Nonlinear Optimal Control Problems"
% ISSS Trans. Automatic Control, 1988
% by: Jacques Vlassenbroeck and Rene Van Dooren
%
% My implementation for computation of the differentiation matrix,
% quadrature rules, and interpolation are based on the following:
%
% "Barycentric Lagrange Interpolation"
% Siam Review, 2004
% Publisher: Society for Industrial and Applied Mathematics
% by: Jean-Paul Berrut and Lloyd N. Trefethen
%
% "Approximation Theory and Approximation Practice"
% Textbook by Lloyd N. Trefethen
%
% "Chebfun" Matlab toolbox
% Website: http://www.chebfun.org/
% by Lloyd N. Trefethen et al.
%
% For details on the input and output, see the help file for optimTraj.m
%
% Method specific parameters:
%
% problem.options.method = 'multiCheb'
% problem.options.multiCheb = struct with method parameters:
% .nColPts = number of collocation points in each trajectory segment
% .nSegment = number of segments to break the trajectory into
%
%
% *************************************************************************
% DEPRICATED
% *************************************************************************
%
%To make code more readable
G = problem.guess;
B = problem.bounds;
F = problem.func;
Opt = problem.options;
nColPts = Opt.multiCheb.nColPts; %Number of collocation points in each segment
nSegment = Opt.multiCheb.nSegment; %Fraction of the duration spent in each segment
% Print out some solver info if desired:
if Opt.verbose > 0
disp(' -> Transcription via Multiple-segment Chebyshev orthogonal collocation');
disp(' ');
end
% This method seems to fail if a low-order polynomial is used.
% It gives reasonable solutions for medium-high order polynomials
if nColPts < 6
disp(' WARNING: using fewer than six collocation points per interval can lead to numerical problems!');
end
% Chebyshev points and weights on the default domain
[xx,ww] = chebyshevPoints(nColPts,[-1,1]);
cheb.xx = xx;
cheb.ww = ww;
cheb.nSegment = nSegment;
cheb.nColPts = nColPts;
% Interpolate the guess at the chebyshev-points for transcription:
guess.tSpan = G.time([1,end]);
guess.time = getMultiChebTime(cheb,guess.tSpan);
guess.state = interp1(G.time', G.state', guess.time')';
guess.control = interp1(G.time', G.control', guess.time')';
[zGuess, pack] = packDecVar(guess.time, guess.state, guess.control);
% Unpack all bounds:
nGrid = nSegment*nColPts;
tLow = getMultiChebTime(cheb,[B.initialTime.low, B.finalTime.low]);
xLow = [B.initialState.low, B.state.low*ones(1,nGrid-2), B.finalState.low];
uLow = B.control.low*ones(1,nGrid);
zLow = packDecVar(tLow,xLow,uLow);
tUpp = getMultiChebTime(cheb,[B.initialTime.upp, B.finalTime.upp]);
xUpp = [B.initialState.upp, B.state.upp*ones(1,nGrid-2), B.finalState.upp];
uUpp = B.control.upp*ones(1,nGrid);
zUpp = packDecVar(tUpp,xUpp,uUpp);
%%%% Set up problem for fmincon:
P.objective = @(z)( ...
myObjective(z, pack, F.pathObj, F.bndObj, cheb) );
P.nonlcon = @(z)( ...
myConstraint(z, pack, F.dynamics, F.pathCst, F.bndCst, cheb) );
P.x0 = zGuess;
P.lb = zLow;
P.ub = zUpp;
P.Aineq = []; P.bineq = [];
P.Aeq = []; P.beq = [];
P.options = Opt.nlpOpt;
P.solver = 'fmincon';
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
nlpTime = toc;
soln = formatTrajectory(zSoln, pack, cheb);
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
soln.problem = problem; % Return the fully detailed problem struct
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%% SUB FUNCTIONS %%%%
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [z,pack] = packDecVar(t,x,u)
%
% This function collapses the time (t), state (x)
% and control (u) matricies into a single vector
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
% OUTPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
tSpan = [t(1); t(end)];
xCol = reshape(x, nState*nTime, 1);
uCol = reshape(u, nControl*nTime, 1);
z = [tSpan;xCol;uCol];
pack.nTime = nTime;
pack.nState = nState;
pack.nControl = nControl;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [t,x,u,w] = unPackDecVar(z,pack,cheb)
%
% This function unpacks the decision variables for
% trajectory optimization into the time (t),
% state (x), and control (u) matricies
%
% INPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
% w = [1, nTime] = weights for clenshaw-curtis quadrature
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
nx = nState*nTime;
nu = nControl*nTime;
[t, w] = getMultiChebTime(cheb,[z(1),z(2)]);
x = reshape(z((2+1):(2+nx)),nState,nTime);
u = reshape(z((2+nx+1):(2+nx+nu)),nControl,nTime);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [time, weights] = getMultiChebTime(cheb,tSpan)
%
% This function computes the time grid for a trajectory that is made up of
% a series of chebyshev orthogonal polynomials.
%
% INPUTS:
% cheb = struct of information about the chebyshev basis functions
% .xx = chebyshev points, on the domain [-1,1]
% .ww = chebyshev weights, on the domain [-1,1]
% .nSegment = number of trajectory segments
% tSpan = [tInitial, tFinal]
%
% OUTPUTS:
% time = [timeSegment_1, timeSegment_2, ... timeSegment_nSegment];
%
% NOTES:
% This function will return duplicate times at the boundary to each
% segment, so that the dynamics of each segment can easily be solved
% independantly. These redundant points must be removed before returning
% the output to the user.
%
% For example, time should like something like:
% time = [0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9];
%
d = [0, (tSpan(2)-tSpan(1))/cheb.nSegment]; %Domain for the scaled points
[x, w] = chebyshevScalePoints(cheb.xx,cheb.ww,d); %Scaled points
offset = linspace(tSpan(1),tSpan(2),cheb.nSegment+1); %Starting time for each segment
time = x'*ones(1,cheb.nSegment) + ones(cheb.nColPts,1)*offset(1:(end-1));
nGrid = numel(time);
time = reshape(time,1,nGrid);
weights = reshape(w'*ones(1,cheb.nSegment),1,nGrid);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [x,w] = chebyshevScalePoints(xx,ww,d)
% [x,w] = chebyshevScalePoints(xx,ww,d)
%
% This function scales the chebyshev points to an arbitrary interval
%
% INPUTS:
% xx = chebyshev points on the domain [-1,1]
% ww = chebysehv weights on the domain [-1,1]
% d = [low, upp] = new domain
%
% OUTPUTS:
% x = chebyshev points on the new domain d
% w = chebyshev weights on the new domain d
%
x = ((d(2)-d(1))*xx + sum(d))/2;
w = ww*(d(2)-d(1))/2;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function cost = myObjective(z,pack,pathObj,bndObj,cheb)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
[t,x,u,w] = unPackDecVar(z,pack,cheb);
% Compute the cost integral along trajectory
if isempty(pathObj)
integralCost = 0;
else
integrand = pathObj(t,x,u); %Calculate the integrand of the cost function
integralCost = dot(w,integrand); %Clenshw-curtise quadrature
end
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
bndCost = bndObj(t0,x0,tF,xF);
end
cost = bndCost + integralCost;
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [c, ceq] = myConstraint(z,pack,dynFun, pathCst, bndCst, cheb)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynFun = user-defined dynamics function
% pathCst = user-defined constraints along the path
% endCst = user-defined constraints at the boundaries
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
[t,x,u] = unPackDecVar(z,pack,cheb);
nSegment = cheb.nSegment;
%%%% Enforce the dynamics:
% Analytic differentiation of the trajectory at chebyshev points:
domain = [0, (t(end)-t(1))/nSegment]; %Domain for the scaled points
xTemplate = chebyshevScalePoints(cheb.xx,cheb.ww,domain); %Scaled points
D = chebyshevDifferentiationMatrix(xTemplate);
dxFun = zeros(size(x));
idx = 1:cheb.nColPts;
for i=1:nSegment %Loop over each segment of the trajectory
dxFun(:,idx) = (D*x(:,idx)')';
idx = idx + cheb.nColPts;
end
% Derivative, according to the dynamics function:
dxDyn = dynFun(t,x,u);
% Add a constraint that both versions of the derivative must match.
% This ensures that the dynamics inside of each segment are correct.
dxError = dxFun - dxDyn;
% Add an additional defect that makes the state at the end of one
% segment match the state at the beginning of the next segment.
idxLow = cheb.nColPts*(1:(nSegment-1));
idxUpp = idxLow + 1;
stitchState = x(:,idxLow)-x(:,idxUpp);
stitchControl = u(:,idxLow)-u(:,idxUpp); %Also need continuous control
defects = [...
reshape(dxError, numel(dxError),1);
reshape(stitchState, numel(stitchState),1);
reshape(stitchControl, numel(stitchControl),1)];
%%%% Call user-defined constraints and pack up:
[c, ceq] = collectConstraints(t,x,u, defects, pathCst, bndCst);
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function soln = formatTrajectory(zSoln, pack, cheb)
%
% This function formats the result of the trajectory optimization so that
% it is easy to use for plotting and analysis by the user.
%
[tSoln,xSoln,uSoln] = unPackDecVar(zSoln,pack,cheb);
nSegment = cheb.nSegment;
nColPts = cheb.nColPts;
%%%% Need to remove the duplicate data points between segments:
idxLow = nColPts*(1:(nSegment-1));
idxUpp = idxLow + 1;
tSoln(idxUpp) = [];
xSoln(:,idxLow) = 0.5*(xSoln(:,idxLow)+xSoln(:,idxUpp));
xSoln(:,idxUpp) = [];
uSoln(:,idxLow) = 0.5*(uSoln(:,idxLow)+uSoln(:,idxUpp));
uSoln(:,idxUpp) = [];
%%%% Store the results:
soln.grid.time = tSoln;
soln.grid.state = xSoln;
soln.grid.control = uSoln;
%%%% Set up interpolating of the chebyshev trajectory:
idxKnot = (nColPts-1)*(1:(nSegment-1)) + 1;
soln.interp.state = @(t)( chebyshevMultiInterpolate(xSoln,tSoln,idxKnot,t) );
soln.interp.control = @(t)( chebyshevMultiInterpolate(uSoln,tSoln,idxKnot,t) );
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [x, w] = chebyshevPoints(n,d)
%[x, w] = chebyshevPoints(n,d)
%
% This function is a light-weight version of the function: chebpts.m
% written by Lloyd Trefethen as part of his Chebyshev Polynomial matlab
% toolbox: chebyfun, which can be downloaded from:
% http://www2.maths.ox.ac.uk/chebfun/download/
%
% The algorithm for computing the quadrature weights is also from
% trefethen's toolbox, with the citation:
% Jörg Waldvogel, "Fast construction of the Fejér and Clenshaw-Curtis
% quadrature rules", BIT Numerical Mathematics 43 (1), p. 001-018 (2004).
% http://www2.maths.ox.ac.uk/chebfun/and_beyond/programme/slides/wald.pdf
%
% Slight modifications made by Matthew Kelly
% October 27, 2013
% Cornell University
%
% This function returns the n chebyshev points, over the interval d. Error
% checking has not been included on the inputs.
%
% INPUTS:
% n = [1x1] the desired number of chebyshev points
% d = [1x2] domain of the polynomial. Default = [-1,1]
%
% OUTPUTS: (2nd-kind chebyshev points and weights)
% x = [1xn] the n chebyshev points over the interval d
% w = [1xn] the n chebyshev weights for Clenshaw-Curtis quadrature
%
if n == 1, x = 0; return, end % Special case
%Compute the chebyshev points on the domain [-1,1]:
m = n-1;
x = sin(pi*(-m:2:m)/(2*m)); % Chebyshev points
%Rescale (if necessary):
if nargin~=1
x = (diff(d)*x + sum(d))/2;
end
%Check if weights are needed:
if nargout==2
w = chebyshevWeights(n)*diff(d)/2;
end
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function w = chebyshevWeights(n) % 2nd-kind Chebyshev wieghts
% Jörg Waldvogel, "Fast construction of the Fejér and Clenshaw-Curtis
% quadrature rules", BIT Numerical Mathematics 43 (1), p. 001-018 (2004).
% http://www2.maths.ox.ac.uk/chebfun/and_beyond/programme/slides/wald.pdf
if n == 1
w = 2;
else
% new
n = n-1;
u0 = 1/(n^2-1+mod(n,2)); % Boundary weights
L = 0:n-1; r = 2./(1-4*min(L,n-L).^2); % Auxiliary vectors
w = [ifft(r-u0) u0]; % C-C weights
end
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function D = chebyshevDifferentiationMatrix(x)
%
% Computes the chebyshev differentiation matrix
%
% NOTES:
%
% Example usage: Df = (D*f')';
% where f = [nState x nPoints] values at each chebyshev node
%
n = length(x);
%Get the weight vector
w = ones(1,n);
w(2:2:n) = -1;
w([1,end]) = w([1,end])/2;
%First, compute the weighting matrix:
W = (1./w)'*w;
%Next, compute the matrix with inverse of the node distance
X = zeros(n);
for i=1:n
idx = (i+1):n;
X(i,idx) = 1./(x(i)-x(idx));
end
%Use the property that this matrix is anti-symetric
X = X - X';
%Compute the i~=j case:
D = W.*X;
%Deal with the i=j case:
D = D - diag(sum(D,2));
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function Df = chebyshevDerivative(f,x)
%Df = chebyshevDerivative(f,x)
%
% FUNCTION:
% This function computes the derivative of the chebyshev interpolant
% at each of the chebyshev nodes.
%
% INPUTS:
% f = [nState x nPoints] values at each chebyshev node
% x = chebyshev points
%
% OUTPUTS:
% Df = the derivative of the chebyshev interpolant at each chebyshev node
%
% NOTES:
% The derivative at each node is computed by multiplying f by a
% differentiation matrix. This matrix is [nPoints x nPoints]. If f is a
% very large order interpolant then computing this matrix may max out the
% memory available to matlab.
%
D = chebyshevDifferentiationMatrix(x);
%Apply the differentiation matrix
Df = (D*f')';
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function y = chebyshevMultiInterpolate(yData,tData,idxKnot,t)
%
% This function is a wrapper for chebyshevInterpolate that handles the
% piece-wise chebyshev polynomial trajectory
%
% All points are considered valid, so extend edge bins:
Tbins = [-inf, tData(idxKnot), inf];
%Figure out which bins each query is in:
[~, idx] = histc(t,Tbins);
% Loop over each segment of the trajectory:
ny = size(yData,1);
nt = length(t);
gridIdx = [1, idxKnot, length(tData)];
nSegment = length(gridIdx)-1;
y = zeros(ny,nt);
for i=1:nSegment
if sum(idx==i)>0 % Then there are points to evaluate here!
y(:,(idx==i)) = chebyshevInterpolate(...
yData(:,gridIdx(i):gridIdx(i+1)),...
t(idx==i),...
tData(gridIdx([i,i+1])) );
end
end
end
%%%%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
function [y, Dy, DDy, DDDy] = chebyshevInterpolate(f,t,d)
%[y, Dy, DDy, DDDy] = chebyshevInterpolate(f,t,d)
%
% This function uses barycentric interpolation to evaluate a chebyshev
% polynomial. Technical details are taken from the book: Approximation
% Theory and Approximation Practice by Lloyd Trefethen. The core equation
% that I use can be found as Theorem 5.2 in this book, and is called
% Barycentric Interpolation.
%
% Written by Matthew Kelly
% October 27, 2013
% Updated: November 8, 2013
% Cornell University
%
% This function computes the value of the chebyshev polynomial that is
% defined by the vector f, at the inputs t. It can also be used to return
% the first and second derivatives of y with respect to t.
%
% INPUTS:
% f = [KxN] value of the chebyshev polynomial at each of the chebyshev
% points (these can be computed using chebyshevPoints.m). Each row
% represents a single set of chebyshev node values for a single
% state.
% t = [1xM] vector of inputs to be evaluated (monotonically increasing)
% d = [1x2] vector specifying the domain of the polynomial
%
% OUTPUTS:
% y = [KxM] the value of the interpolant at each point in t
% Dy = first derivative of y with respect to t
% DDy = second derivative of y with respect to t
% DDDy = third derivative of y with respect to t
%
% What is happening here, in plain english:
%
% There are several Chebyshev points (or nodes) that are spread out
% across the interval d using a special grid spacing. We will call these
% points x. For each of the points in x, there is a corresponding value
% of the chebyshev function, we'll call it f.
%
% Let's say that we want to find the value of the approximation for some
% input that is not in x. This can be done using a interpolation of the
% values in f:
% y = c(t,x).*f
%
% Note that the weighting terms are a function of both the desired input
% and the chebyshev points. It turns out that there is a more stable and
% efficient way to calculate this interpolation, which is roughly of the
% form:
% y = (k(t,x).*f)/sum(k(t,x))
%
% This code evaluates k(t,x) which it then uses to evaluate and return y.
%
%
% NOTE - The base algorithm (described above) is not defined for points in
% t that are close to the chebyshev nodes in x. If a point in t matches a
% point in x, then an additional claculation is required. If a point in t
% is very close to a gridpoint, then there is a slight loss of accuracy,
% which is more pronounced.
%
%Check to see if the t vector is on the proper domain:
idxBndFail = t<min(d) | t>max(d);
%Get the chebyshev points
[k,n] = size(f);
x = chebyshevPoints(n,d);
ONE1 = ones(k,1);
ONE2 = ones(1,length(t));
%Loop through each chebyshev node.
num = zeros(k,length(t));
den = zeros(k,length(t));
for i=1:n
val = ONE1*(1./(t-x(i)));
if mod(i,2)==1, val=-val; end;
if i==1 || i==n
num = num + 0.5*(f(:,i)*ONE2).*val;
den = den + 0.5*(val);
else
num = num + (f(:,i)*ONE2).*val;
den = den + val;
end
end
%compute the solution:
y = num./den;
%Check for any values that were too close to nodes and correct them
nanIdx = isnan(y);
if sum(sum(nanIdx))>0
nanRowIdx = max(nanIdx,[],1);
y(:,nanRowIdx) = interp1(x',f',t(nanRowIdx)')';
end
%%%% Replace any out-of-bound queries with NaN:
y(:,idxBndFail) = nan;
%%%% Derivative Calculations %%%%
if nargout == 2
Df = chebyshevDerivative(f,d);
Dy = chebyshevInterpolate(Df,t,d);
Dy(:,idxBndFail) = nan;
elseif nargout == 3
[Df, DDf] = chebyshevDerivative(f,d);
Dy = chebyshevInterpolate(Df,t,d);
DDy = chebyshevInterpolate(DDf,t,d);
Dy(:,idxBndFail) = nan;
DDy(:,idxBndFail) = nan;
elseif nargout == 4
[Df, DDf, DDDf] = chebyshevDerivative(f,d);
Dy = chebyshevInterpolate(Df,t,d);
DDy = chebyshevInterpolate(DDf,t,d);
DDDy = chebyshevInterpolate(DDDf,t,d);
Dy(:,idxBndFail) = nan;
DDy(:,idxBndFail) = nan;
DDDy(:,idxBndFail) = nan;
end
end
|
github
|
pvarin/DynamicVAE-master
|
drawCartPoleAnim.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/demo/cartPole/drawCartPoleAnim.m
| 2,133 |
utf_8
|
2334402558a3114d7f969148319c70cd
|
function drawCartPoleAnim(~,p,xLow, xUpp, yLow, yUpp)
% drawCartPoleTraj(t,p,xLow, xUpp, yLow, yUpp)
%
% INPUTS:
% t = [1,n] = time stamp for the data in p1 and p2
% p = [4,n] = [p1;p2];
%
clf; hold on;
Cart_Width = 0.15;
Cart_Height = 0.05;
p1 = p(1:2,:);
p2 = p(3:4,:);
Pole_Width = 4; %pixels
%%%% Figure out the window size:
xLow = xLow - 0.7*Cart_Width;
xUpp = xUpp + 0.7*Cart_Width;
yLow = yLow - 0.7*Cart_Height;
yUpp = yUpp + 0.7*Cart_Height;
Limits = [xLow,xUpp,yLow,yUpp];
%%%% Get color map for the figure
% map = colormap;
% tMap = linspace(t(1),t(end),size(map,1))';
%%%% Plot Rails
plot([Limits(1) Limits(2)],-0.5*Cart_Height*[1,1],'k-','LineWidth',2)
%%%% Draw the trace of the pendulum tip (continuously vary color)
% nTime = length(t);
% for i=1:(nTime-1)
% idx = i:(i+1);
% x = p2(1,idx);
% y = p2(2,idx);
% c = interp1(tMap,map,mean(t(idx)));
% plot(x,y,'Color',c);
% end
%%%% Compute the frames for plotting:
% tFrame = linspace(t(1), t(end), nFrame);
% cart = interp1(t',p1',tFrame')';
% pole = interp1(t',p2',tFrame')';
cart = p1;
pole = p2;
% for i = 1:nFrame
% Compute color:
color = [0.2,0.7,0.1]; %interp1(tMap,map,tFrame(i));
%Plot Cart
x = cart(1) - 0.5*Cart_Width;
y = -0.5*Cart_Height;
w = Cart_Width;
h = Cart_Height;
hCart = rectangle('Position',[x,y,w,h],'LineWidth',2);
set(hCart,'FaceColor',color);
set(hCart,'EdgeColor',0.8*color);
%Plot Pendulum
Rod_X = [cart(1), pole(1)];
Rod_Y = [cart(2), pole(2)];
plot(Rod_X,Rod_Y,'k-','LineWidth',Pole_Width,'Color',color)
%Plot Bob and hinge
plot(pole(1),pole(2),'k.','MarkerSize',40,'Color',color)
plot(cart(1),cart(2),'k.','MarkerSize',60,'Color',color)
% end
%These commands keep the window from automatically rescaling in funny ways.
axis(Limits);
axis('equal');
axis manual;
axis off;
end
function [xLow, xUpp, yLow, yUpp] = getBounds(p1,p2)
%
% Returns the upper and lower bound on the data in val
%
val = [p1,p2];
xLow = min(val(1,:));
xUpp = max(val(1,:));
yLow = min(val(2,:));
yUpp = max(val(2,:));
end
|
github
|
pvarin/DynamicVAE-master
|
drawCartPoleTraj.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/demo/cartPole/drawCartPoleTraj.m
| 2,226 |
utf_8
|
d998353b28a3858bf2e12e289f80f3a0
|
function drawCartPoleTraj(t,p1,p2,nFrame)
% drawCartPoleTraj(t,p1,p2,nFrame)
%
% INPUTS:
% t = [1,n] = time stamp for the data in p1 and p2
% p1 = [2,n] = [x;y] = position of center of the cart
% p2 = [2,n] = [x;y] = position of tip of the pendulum
% nFrame = scalar integer = number of "freeze" frames to display
%
clf; hold on;
Cart_Width = 0.15;
Cart_Height = 0.05;
Pole_Width = 4; %pixels
%%%% Figure out the window size:
[xLow, xUpp, yLow, yUpp] = getBounds(p1,p2);
xLow = xLow - 0.7*Cart_Width;
xUpp = xUpp + 0.7*Cart_Width;
yLow = yLow - 0.7*Cart_Height;
yUpp = yUpp + 0.7*Cart_Height;
Limits = [xLow,xUpp,yLow,yUpp];
%%%% Get color map for the figure
map = colormap;
tMap = linspace(t(1),t(end),size(map,1))';
%%%% Plot Rails
plot([Limits(1) Limits(2)],-0.5*Cart_Height*[1,1],'k-','LineWidth',2)
%%%% Draw the trace of the pendulum tip (continuously vary color)
nTime = length(t);
for i=1:(nTime-1)
idx = i:(i+1);
x = p2(1,idx);
y = p2(2,idx);
c = interp1(tMap,map,mean(t(idx)));
plot(x,y,'Color',c);
end
%%%% Compute the frames for plotting:
tFrame = linspace(t(1), t(end), nFrame);
cart = interp1(t',p1',tFrame')';
pole = interp1(t',p2',tFrame')';
for i = 1:nFrame
% Compute color:
color = interp1(tMap,map,tFrame(i));
%Plot Cart
x = cart(1,i) - 0.5*Cart_Width;
y = -0.5*Cart_Height;
w = Cart_Width;
h = Cart_Height;
hCart = rectangle('Position',[x,y,w,h],'LineWidth',2);
set(hCart,'FaceColor',color);
set(hCart,'EdgeColor',0.8*color);
%Plot Pendulum
Rod_X = [cart(1,i), pole(1,i)];
Rod_Y = [cart(2,i), pole(2,i)];
plot(Rod_X,Rod_Y,'k-','LineWidth',Pole_Width,'Color',color)
%Plot Bob and hinge
plot(pole(1,i),pole(2,i),'k.','MarkerSize',40,'Color',color)
plot(cart(1,i),cart(2,i),'k.','MarkerSize',60,'Color',color)
end
%These commands keep the window from automatically rescaling in funny ways.
axis(Limits);
axis('equal');
axis manual;
axis off;
end
function [xLow, xUpp, yLow, yUpp] = getBounds(p1,p2)
%
% Returns the upper and lower bound on the data in val
%
val = [p1,p2];
xLow = min(val(1,:));
xUpp = max(val(1,:));
yLow = min(val(2,:));
yUpp = max(val(2,:));
end
|
github
|
pvarin/DynamicVAE-master
|
Derive_Equations.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/demo/fiveLinkBiped/Derive_Equations.m
| 22,822 |
utf_8
|
db9aaefe0015ed46a21528cd1f049d49
|
function Derive_Equations()
%%%% Derive Equations - Five Link Biped Model %%%%
%
% This function derives the equations of motion, as well as some other useful
% equations (kinematics, contact forces, ...) for the five-link biped
% model.
%
%
% Nomenclature:
%
% - There are five links, which will be numbered starting with "1" for the
% stance leg tibia, increasing as the links are father from the base joint,
% and ending with "5" for the swing leg tibia.
% 1 - stance leg tibia (lower leg)
% 2 - stance leg femur (upper leg)
% 3 - torso
% 4 - swing leg femur
% 5 - swing leg tibia
%
% - This script uses absolute angles, which are represented with "q". All
% angles use positive convention, with the zero angle corresponding to a
% vertically aligned link configuration. [q] = [0] has the torso balanced
% upright, with both legs fully extended straight below it.
%
% - Derivatives with respect to time are notated by prepending a "d". For
% example the rate of change in an absolute angle is "dq" and angular
% acceleration would be "ddq"
%
% - Joint positions are given with "P", center of mass positions are "G"
%
clc; clear;
disp('Creating variables and derivatives...')
%%%% Absolute orientation (angle) of each link
q1 = sym('q1', 'real');
q2 = sym('q2','real');
q3 = sym('q3','real');
q4 = sym('q4','real');
q5 = sym('q5','real');
%%%% Absolute angular rate of each link
dq1 = sym('dq1','real');
dq2 = sym('dq2','real');
dq3 = sym('dq3','real');
dq4 = sym('dq4','real');
dq5 = sym('dq5','real');
%%%% Absolute angular acceleration of each linke
ddq1 = sym('ddq1','real');
ddq2 = sym('ddq2','real');
ddq3 = sym('ddq3','real');
ddq4 = sym('ddq4','real');
ddq5 = sym('ddq5','real');
%%%% Torques at each joint
u1 = sym('u1','real'); %Stance foot
u2 = sym('u2','real'); %Stance knee
u3 = sym('u3','real'); %Stance hip
u4 = sym('u4','real'); %Swing hip
u5 = sym('u5','real'); %Swing knee
%%%% Mass of each link
m1 = sym('m1','real');
m2 = sym('m2','real');
m3 = sym('m3','real');
m4 = sym('m4','real');
m5 = sym('m5','real');
%%%% Distance between parent joint and link center of mass
c1 = sym('c1','real');
c2 = sym('c2','real');
c3 = sym('c3','real');
c4 = sym('c4','real');
c5 = sym('c5','real');
%%%% Length of each link
l1 = sym('l1','real');
l2 = sym('l2','real');
l3 = sym('l3','real');
l4 = sym('l4','real');
l5 = sym('l5','real');
%%%% Moment of inertia of each link about its own center of mass
I1 = sym('I1','real');
I2 = sym('I2','real');
I3 = sym('I3','real');
I4 = sym('I4','real');
I5 = sym('I5','real');
g = sym('g','real'); % Gravity
Fx = sym('Fx','real'); %Horizontal contact force at stance foot
Fy = sym('Fy','real'); %Vertical contact force at stance foot
empty = sym('empty','real'); %Used for vectorization, user should pass a vector of zeros
t = sym('t','real'); %dummy continuous time
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Set up coordinate system and unit vectors %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
i = sym([1;0]); %Horizontal axis
j = sym([0;1]); %Vertical axis
e1 = cos(q1)*(j) + sin(q1)*(-i); %unit vector from P0 -> P1, (contact point to stance knee)
e2 = cos(q2)*(j) + sin(q2)*(-i); %unit vector from P1 -> P2, (stance knee to hip)
e3 = cos(q3)*(j) + sin(q3)*(-i); %unit vector from P2 -> P3, (hip to shoulders);
e4 = -cos(q4)*(j) - sin(q4)*(-i); %unit vector from P2 -> P4, (hip to swing knee);
e5 = -cos(q5)*(j) - sin(q5)*(-i); %unit vector from P4 -> P5, (swing knee to swing foot);
P0 = 0*i + 0*j; %stance foot = Contact point = origin
P1 = P0 + l1*e1; %stance knee
P2 = P1 + l2*e2; %hip
P3 = P2 + l3*e3; %shoulders
P4 = P2 + l4*e4; %swing knee
P5 = P4 + l5*e5; %swing foot
G1 = P1 - c1*e1; % CoM stance leg tibia
G2 = P2 - c2*e2; % CoM stance leg febur
G3 = P3 - c3*e3; % CoM torso
G4 = P2 + c4*e4; % CoM swing leg femur
G5 = P4 + c5*e5; % CoM swing leg tibia
G = (m1*G1 + m2*G2 + m3*G3 + m4*G4 + m5*G5)/(m1+m2+m3+m4+m5); %Center of mass for entire robot
%%%% Define a function for doing '2d' cross product: dot(a x b, k)
cross2d = @(a,b)(a(1)*b(2) - a(2)*b(1));
%%%% Weight of each link:
w1 = -m1*g*j;
w2 = -m2*g*j;
w3 = -m3*g*j;
w4 = -m4*g*j;
w5 = -m5*g*j;
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Derivatives %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
q = [q1;q2;q3;q4;q5];
dq = [dq1;dq2;dq3;dq4;dq5];
ddq = [ddq1;ddq2;ddq3;ddq4;ddq5];
u = [u1;u2;u3;u4;u5];
z = [t;q;dq;u]; % time-varying vector of inputs
% Neat trick to compute derivatives using the chain rule
derivative = @(in)( jacobian(in,[q;dq])*[dq;ddq] );
% Velocity of the swing foot (used for step constraints)
dP5 = derivative(P5);
% Compute derivatives for the CoM of each link:
dG1 = derivative(G1); ddG1 = derivative(dG1);
dG2 = derivative(G2); ddG2 = derivative(dG2);
dG3 = derivative(G3); ddG3 = derivative(dG3);
dG4 = derivative(G4); ddG4 = derivative(dG4);
dG5 = derivative(G5); ddG5 = derivative(dG5);
dG = derivative(G); ddG = derivative(dG);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Calculations: %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
singleStanceDynamics();
objectiveFunctions();
heelStrikeDynamics();
mechanicalEnergy();
contactForces();
kinematics();
disp('Done!');
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Single-Stance Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% I solve the dynamics here by carefully selecting angular momentum balance
% equations about each joint, working my way out the kinematic tree from
% the root.
function singleStanceDynamics()
disp('Deriving single stance dynamics...')
%%%% AMB - entire system @ P0
eqnTorque0 = ...
cross2d(G1-P0,w1) + ...
cross2d(G2-P0,w2) + ...
cross2d(G3-P0,w3) + ...
cross2d(G4-P0,w4) + ...
cross2d(G5-P0,w5) + ...
u1;
eqnInertia0 = ...
cross2d(G1-P0,m1*ddG1) + ddq1*I1 + ...
cross2d(G2-P0,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P0,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P0,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P0,m5*ddG5) + ddq5*I5;
%%%% AMB - swing leg, torso, stance femer @ stance knee
eqnTorque1 = ...
cross2d(G2-P1,w2) + ...
cross2d(G3-P1,w3) + ...
cross2d(G4-P1,w4) + ...
cross2d(G5-P1,w5) + ...
u2;
eqnInertia1 = ...
cross2d(G2-P1,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P1,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P1,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P1,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg, torso @ hip
eqnTorque2 = ...
cross2d(G3-P2,w3) + ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u3;
eqnInertia2 = ...
cross2d(G3-P2,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg @ hip
eqnTorque3 = ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u4;
eqnInertia3 = ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing tibia % swing knee
eqnTorque4 = ...
cross2d(G5-P4,w5) + ...
u5;
eqnInertia4 = ...
cross2d(G5-P4,m5*ddG5) + ddq5*I5 ;
%%%% Collect and solve equations:
eqns = [...
eqnTorque0 - eqnInertia0;
eqnTorque1 - eqnInertia1;
eqnTorque2 - eqnInertia2;
eqnTorque3 - eqnInertia3;
eqnTorque4 - eqnInertia4];
[MM, FF] = equationsToMatrix(eqns,ddq); % ddq = MM\ff;
%%%% Compute gradients:
[m, mi, mz, mzi, mzd] = computeGradients(MM,z,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,z,empty);
% Write function file:
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_dynSs.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'u1','u2','u3','u4','u5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g','empty'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Objective Functions %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function objectiveFunctions()
%%%% Torque-squared objective function
F = u1*u1 + u2*u2 + u3*u3 + u4*u4 + u5*u5;
[f, ~, fz, fzi, ~] = computeGradients(F,z,empty);
matlabFunction(f,fz,fzi,...
'file','autoGen_obj_torqueSquared.m',...
'vars',{'u1','u2','u3','u4','u5'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Heel-Strike Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function heelStrikeDynamics()
disp('Deriving heel-strike dynamics...')
%%%% Notes:
% xF - heelStrike(xI) --> constraint --> 0
% xF - collision(footSwap(xI));
%
% Angles before heel-strike:
q1m = sym('q1m','real');
q2m = sym('q2m','real');
q3m = sym('q3m','real');
q4m = sym('q4m','real');
q5m = sym('q5m','real');
qm = [q1m;q2m;q3m;q4m;q5m];
% Angles after heel-strike
q1p = sym('q1p','real');
q2p = sym('q2p','real');
q3p = sym('q3p','real');
q4p = sym('q4p','real');
q5p = sym('q5p','real');
qp = [q1p;q2p;q3p;q4p;q5p];
% Angular rates before heel-strike:
dq1m = sym('dq1m','real');
dq2m = sym('dq2m','real');
dq3m = sym('dq3m','real');
dq4m = sym('dq4m','real');
dq5m = sym('dq5m','real');
dqm = [dq1m;dq2m;dq3m;dq4m;dq5m];
% Angular rates after heel-strike
dq1p = sym('dq1p','real');
dq2p = sym('dq2p','real');
dq3p = sym('dq3p','real');
dq4p = sym('dq4p','real');
dq5p = sym('dq5p','real');
dqp = [dq1p;dq2p;dq3p;dq4p;dq5p];
% Compute kinematics before heel-strike:
inVars = {'q1','q2','q3','q4','q5','dq1','dq2','dq3','dq4','dq5'};
outVarsM = {'q1m','q2m','q3m','q4m','q5m','dq1m','dq2m','dq3m','dq4m','dq5m'};
% P0m = subs(P0,inVars,outVarsM);
P1m = subs(P1,inVars,outVarsM);
P2m = subs(P2,inVars,outVarsM);
% P3m = subs(P3,inVars,outVarsM);
P4m = subs(P4,inVars,outVarsM);
P5m = subs(P5,inVars,outVarsM);
dP5m = subs(dP5,inVars,outVarsM);
G1m = subs(G1,inVars,outVarsM);
G2m = subs(G2,inVars,outVarsM);
G3m = subs(G3,inVars,outVarsM);
G4m = subs(G4,inVars,outVarsM);
G5m = subs(G5,inVars,outVarsM);
dG1m = subs(dG1,inVars,outVarsM);
dG2m = subs(dG2,inVars,outVarsM);
dG3m = subs(dG3,inVars,outVarsM);
dG4m = subs(dG4,inVars,outVarsM);
dG5m = subs(dG5,inVars,outVarsM);
% Compute kinematics after heel-strike:
outVarsP = {'q1p','q2p','q3p','q4p','q5p','dq1p','dq2p','dq3p','dq4p','dq5p'};
P0p = subs(P0,inVars,outVarsP);
P1p = subs(P1,inVars,outVarsP);
P2p = subs(P2,inVars,outVarsP);
% P3p = subs(P3,inVars,outVarsP);
P4p = subs(P4,inVars,outVarsP);
% P5p = subs(P5,inVars,outVarsP);
dP5p = subs(dP5,inVars,outVarsP);
G1p = subs(G1,inVars,outVarsP);
G2p = subs(G2,inVars,outVarsP);
G3p = subs(G3,inVars,outVarsP);
G4p = subs(G4,inVars,outVarsP);
G5p = subs(G5,inVars,outVarsP);
dG1p = subs(dG1,inVars,outVarsP);
dG2p = subs(dG2,inVars,outVarsP);
dG3p = subs(dG3,inVars,outVarsP);
dG4p = subs(dG4,inVars,outVarsP);
dG5p = subs(dG5,inVars,outVarsP);
%%%% AMB - entire system @ New stance foot
eqnHs0m = ... %Before collision
cross2d(G1m-P5m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P5m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P5m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P5m,m4*dG4m) + dq4m*I4 + ...
cross2d(G5m-P5m,m5*dG5m) + dq5m*I5;
eqnHs0 = ... %After collision
cross2d(G1p-P0p,m1*dG1p) + dq1p*I1 + ...
cross2d(G2p-P0p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P0p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P0p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P0p,m5*dG5p) + dq5p*I5;
%%%% AMB - new swing leg, torso, stance femer @ stance knee
eqnHs1m = ... %Before collision
cross2d(G1m-P4m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P4m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P4m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P4m,m4*dG4m) + dq4m*I4;
eqnHs1 = ... %After collision
cross2d(G2p-P1p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P1p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P1p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P1p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg, torso @ new hip
eqnHs2m = ... %Before collision
cross2d(G3m-P2m,m3*dG3m) + dq3m*I3 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2 + ...
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1;
eqnHs2 = ... %After collision
cross2d(G3p-P2p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg @ new hip
eqnHs3m = ... %Before collision
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2;
eqnHs3 = ... %After collision
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing tibia @ new swing knee
eqnHs4m = ... %Before collision
cross2d(G1m-P1m,m1*dG1m) + dq1m*I1;
eqnHs4 = ... %After collision
cross2d(G5p-P4p,m5*dG5p) + dq5p*I5;
%%%% Collect and solve equations:
eqnHs = [...
eqnHs0m - eqnHs0;
eqnHs1m - eqnHs1;
eqnHs2m - eqnHs2;
eqnHs3m - eqnHs3;
eqnHs4m - eqnHs4];
[MM, FF] = equationsToMatrix(eqnHs,dqp);
%%%% Compute gradients:
tp = sym('tp','real'); %Initial trajectory time
tm = sym('tm','real'); %Final trajectory time
zBnd = [tp;qp;dqp;tm;qm;dqm];
[m, mi, mz, mzi, mzd] = computeGradients(MM,zBnd,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,zBnd,empty);
% Heel-strike
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_cst_heelStrike.m',...
'vars',{...
'q1p','q2p','q3p','q4p','q5p',...
'q1m','q2m','q3m','q4m','q5m',...
'dq1m','dq2m','dq3m','dq4m','dq5m',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5','empty'});
% Collision velocity of the swing foot:
cst = [-dP5p(2); dP5m(2)]; %Swing foot velocity before and after collision (negative sign is intentional, since output is constrained to be negative);
cstJac = jacobian(cst,zBnd); %Gradient
matlabFunction(cst, cstJac,...
'file','autoGen_cst_footVel.m',...
'vars',{...
'q1p','q2p','q4p','q5p',...
'q1m','q2m','q4m','q5m',...
'dq1p','dq2p','dq4p','dq5p',...
'dq1m','dq2m','dq4m','dq5m',...
'l1','l2','l4','l5'});
% Step length and height constraint:
stepLength = sym('stepLength','real');
ceq = [P5m(1)-stepLength; P5m(2)];
ceqJac = jacobian(ceq,zBnd); %Gradient
matlabFunction(ceq, ceqJac,...
'file','autoGen_cst_steplength.m',...
'vars',{...
'q1m','q2m','q4m','q5m',...
'l1','l2','l4','l5','stepLength'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Mechanical Energy %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function mechanicalEnergy()
disp('Deriving mechanical energy...')
%%%% Energy:
KineticEnergy = ...
0.5*m1*dot(dG1,dG1) + 0.5*I1*dq1^2 + ...
0.5*m2*dot(dG2,dG2) + 0.5*I2*dq2^2 + ...
0.5*m3*dot(dG3,dG3) + 0.5*I3*dq3^2 + ...
0.5*m4*dot(dG4,dG4) + 0.5*I4*dq4^2 + ...
0.5*m5*dot(dG5,dG5) + 0.5*I5*dq5^2;
PotentialEnergy = ...
m1*g*G1(2) + ...
m2*g*G2(2) + ...
m3*g*G3(2) + ...
m4*g*G4(2) + ...
m5*g*G5(2);
matlabFunction(KineticEnergy, PotentialEnergy,...
'file','autoGen_energy.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'KE','PE'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Contact Forces %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function contactForces()
%%%% Contact Forces:
eqnForce5 = w1 + w2 + w3 + w4 + w5 + Fx*i + Fy*j;
eqnInertia5 = (m1+m2+m3+m4+m5)*ddG;
[AA,bb] = equationsToMatrix(eqnForce5-eqnInertia5,[Fx;Fy]);
ContactForces = AA\bb;
matlabFunction(ContactForces(1),ContactForces(2),...
'file','autoGen_contactForce.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'ddq1','ddq2','ddq3','ddq4','ddq5',...
'm1','m2','m3','m4','m5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'Fx','Fy'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Write Kinematics Files %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function kinematics()
disp('Writing kinematics files...')
P = [P1; P2; P3; P4; P5];
Gvec = [G1; G2; G3; G4; G5];
% Used for plotting and animation
matlabFunction(P,Gvec,'file','autoGen_getPoints.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5'},...
'outputs',{'P','Gvec'});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Helper Functions %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [m, mi, mz, mzi, dim] = computeGradients(M,z,empty)
%
% This function computes the gradients of a matrix M with respect the the
% variables in z, and then returns both the matrix and its gradient as
% column vectors of their non-zero elements, along with the linear indicies
% to unpack them. It also simplifies m and mz.
%
% INPUTS:
% M = [na, nb] = symbolic matrix
% z = [nc, 1] = symbolic vector
%
% OUTPUTS:
% m = [nd, 1] = symbolic vector of non-zero elements in M
% i = [nd, 1] = linear indicies to map m --> [na,nb] matrix
% mz = [ne, 1] = symbolic vector of non-zero elements in Mz
% iz = [ne, 1] = linear indicies to map mz --> [na,nb,nc] array
% dim = [3,1] = [na,nb,nc] = dimensions of 3d version of mz
%
[na, nb] = size(M);
nc = size(z,1);
M = simplify(M);
mz2 = jacobian(M(:),z); %Compute jacobian of M, by first reshaping M to be a column vector
mz3 = reshape(mz2,na,nb,nc); %Expand back out to a three-dimensional array
mz3 = simplify(mz3);
% Extract non-zero elements to a column vector:
mi = find(M);
m = M(mi);
mzi = find(mz3);
mz = mz3(mzi); mz = mz(:); %Collapse to a column vector
dim = [na,nb,nc];
% Pad any constant terms with "empty" to permit vectorization:
m = vectorizeHack(m, z, empty);
mz = vectorizeHack(mz, z, empty);
end
function x = vectorizeHack(x, z, empty)
%
% This function searches for any elements of x that are not dependent on
% any element of z. In this case, the automatically generated code will
% fail to vectorize properly. One solution is to add an array of zeros
% (empty) to the element.
%
% x = column vector of symbolic expressions
% z = column vector of symbolic variables
% z = symbolic variable, which the user will set equal to zero.
%
% Compute dependencies
g = jacobian(x,z);
% Check for rows of x with no dependence on z
[n,m] = size(g);
idxConst = true(n,1);
for i=1:n
for j=1:m
if ~isequal(sym(0),g(i,j))
idxConst(i) = false;
break;
end
end
end
% Add empty to those enteries
x(idxConst) = x(idxConst) + empty;
end
|
github
|
pvarin/DynamicVAE-master
|
dirColGrad.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/demo/fiveLinkBiped/costOfTransport/dirColGrad.m
| 11,673 |
utf_8
|
f7fd60b58db9ceade9467b4c0c3233f9
|
function soln = dirColGrad(P, problem)
% soln = dirColGrad(P, problem)
%
% OptimTraj utility function - Direct Collocation with Gradients
%
% This function is core function that is called to run the transcription
% for both the "trapezoid" and the "hermiteSimpson" methods when they are
% running analytic gradients.
%
%
F = problem.func;
if isempty(P.objective)
P.objective = @(z)( ...
grad_objective(z, pack, F.pathObj, F.bndObj, gradInfo, weights) ); %Analytic gradients
end
if isempty(P.constraint)
P.nonlcon = @(z)( ...
myCstGrad(z, pack, F.dynamics, F.pathCst, F.bndCst, F.defectCst, gradInfo) ); %Analytic gradients
end
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
[tSoln,xSoln,uSoln] = unPackDecVar(zSoln,pack);
nlpTime = toc;
%%%% Store the results:
soln.grid.time = tSoln;
soln.grid.state = xSoln;
soln.grid.control = uSoln;
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
soln.problem = problem; % Return the fully detailed problem struct
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [z,pack] = packDecVar(t,x,u)
%
% This function collapses the time (t), state (x)
% and control (u) matricies into a single vector
%
% INPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
% OUTPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
tSpan = [t(1); t(end)];
xCol = reshape(x, nState*nTime, 1);
uCol = reshape(u, nControl*nTime, 1);
z = [tSpan;xCol;uCol];
pack.nTime = nTime;
pack.nState = nState;
pack.nControl = nControl;
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [t,x,u] = unPackDecVar(z,pack)
%
% This function unpacks the decision variables for
% trajectory optimization into the time (t),
% state (x), and control (u) matricies
%
% INPUTS:
% z = column vector of 2 + nTime*(nState+nControl) decision variables
% pack = details about how to convert z back into t,x, and u
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% t = [1, nTime] = time vector (grid points)
% x = [nState, nTime] = state vector at each grid point
% u = [nControl, nTime] = control vector at each grid point
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
nx = nState*nTime;
nu = nControl*nTime;
t = linspace(z(1),z(2),nTime);
x = reshape(z((2+1):(2+nx)),nState,nTime);
u = reshape(z((2+nx+1):(2+nx+nu)),nControl,nTime);
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function gradInfo = grad_computeInfo(pack)
%
% This function computes the matrix dimensions and indicies that are used
% to map the gradients from the user functions to the gradients needed by
% fmincon. The key difference is that the gradients in the user functions
% are with respect to their input (t,x,u) or (t0,x0,tF,xF), while the
% gradients for fmincon are with respect to all decision variables.
%
% INPUTS:
% nDeVar = number of decision variables
% pack = details about packing and unpacking the decision variables
% .nTime
% .nState
% .nControl
%
% OUTPUTS:
% gradInfo = details about how to transform gradients
%
nTime = pack.nTime;
nState = pack.nState;
nControl = pack.nControl;
nDecVar = 2 + nState*nTime + nControl*nTime;
zIdx = 1:nDecVar;
gradInfo.nDecVar = nDecVar;
[tIdx, xIdx, uIdx] = unPackDecVar(zIdx,pack);
gradInfo.tIdx = tIdx([1,end]);
gradInfo.xuIdx = [xIdx;uIdx];
%%%% Compute gradients of time:
% alpha = (0..N-1)/(N-1)
% t = alpha*tUpp + (1-alpha)*tLow
alpha = (0:(nTime-1))/(nTime-1);
gradInfo.alpha = [1-alpha; alpha];
%%%% Compute gradients of state
gradInfo.xGrad = zeros(nState,nTime,nDecVar);
for iTime=1:nTime
for iState=1:nState
gradInfo.xGrad(iState,iTime,xIdx(iState,iTime)) = 1;
end
end
%%%% For unpacking the boundary constraints and objective:
gradInfo.bndIdxMap = [tIdx(1); xIdx(:,1); tIdx(end); xIdx(:,end)];
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [dt, dtGrad] = grad_timeStep(t,gradInfo)
%
% OptimTraj utility function
%
% Computes the time step and its gradient
%
% dt = [1,1]
% dtGrad = [1,nz]
%
nTime = length(t);
dt = (t(end)-t(1))/(nTime-1);
dtGrad = zeros(1,gradInfo.nDecVar);
dtGrad(1,gradInfo.tIdx(1)) = -1/(nTime-1);
dtGrad(1,gradInfo.tIdx(2)) = 1/(nTime-1);
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,defects, defectsGrad, pathCst, bndCst, gradInfo)
% [c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,defects, defectsGrad, pathCst, bndCst, gradInfo)
%
% OptimTraj utility function.
%
% Collects the defects, calls user-defined constraints, and then packs
% everything up into a form that is good for fmincon. Additionally, it
% reshapes and packs up the gradients of these constraints.
%
% INPUTS:
% t = time vector
% x = state matrix
% u = control matrix
% defects = defects matrix
% pathCst = user-defined path constraint function
% bndCst = user-defined boundary constraint function
%
% OUTPUTS:
% c = inequality constraint for fmincon
% ceq = equality constraint for fmincon
%
ceq_dyn = reshape(defects,numel(defects),1);
ceq_dynGrad = grad_flattenPathCst(defectsGrad);
%%%% Compute the user-defined constraints:
if isempty(pathCst)
c_path = [];
ceq_path = [];
c_pathGrad = [];
ceq_pathGrad = [];
else
[c_path, ceq_path, c_pathGradRaw, ceq_pathGradRaw] = pathCst(t,x,u);
c_pathGrad = grad_flattenPathCst(grad_reshapeContinuous(c_pathGradRaw,gradInfo));
ceq_pathGrad = grad_flattenPathCst(grad_reshapeContinuous(ceq_pathGradRaw,gradInfo));
end
if isempty(bndCst)
c_bnd = [];
ceq_bnd = [];
c_bndGrad = [];
ceq_bndGrad = [];
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
[c_bnd, ceq_bnd, c_bndGradRaw, ceq_bndGradRaw] = bndCst(t0,x0,tF,xF);
c_bndGrad = grad_reshapeBoundary(c_bndGradRaw,gradInfo);
ceq_bndGrad = grad_reshapeBoundary(ceq_bndGradRaw,gradInfo);
end
%%%% Pack everything up:
c = [c_path;c_bnd];
ceq = [ceq_dyn; ceq_path; ceq_bnd];
cGrad = [c_pathGrad;c_bndGrad]';
ceqGrad = [ceq_dynGrad; ceq_pathGrad; ceq_bndGrad]';
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function C = grad_flattenPathCst(CC)
%
% This function takes a path constraint and reshapes the first two
% dimensions so that it can be passed to fmincon
%
if isempty(CC)
C = [];
else
[n1,n2,n3] = size(CC);
C = reshape(CC,n1*n2,n3);
end
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function CC = grad_reshapeBoundary(C,gradInfo)
%
% This function takes a boundary constraint or objective from the user
% and expands it to match the full set of decision variables
%
CC = zeros(size(C,1),gradInfo.nDecVar);
CC(:,gradInfo.bndIdxMap) = C;
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function grad = grad_reshapeContinuous(gradRaw,gradInfo)
% grad = grad_reshapeContinuous(gradRaw,gradInfo)
%
% OptimTraj utility function.
%
% This function converts the raw gradients from the user function into
% gradients with respect to the decision variables.
%
% INPUTS:
% stateRaw = [nOutput,nInput,nTime]
%
% OUTPUTS:
% grad = [nOutput,nTime,nDecVar]
%
if isempty(gradRaw)
grad = [];
else
[nOutput, ~, nTime] = size(gradRaw);
grad = zeros(nOutput,nTime,gradInfo.nDecVar);
% First, loop through and deal with time.
timeGrad = gradRaw(:,1,:); timeGrad = permute(timeGrad,[1,3,2]);
for iOutput=1:nOutput
A = ([1;1]*timeGrad(iOutput,:)).*gradInfo.alpha;
grad(iOutput,:,gradInfo.tIdx) = permute(A,[3,2,1]);
end
% Now deal with state and control:
for iOutput=1:nOutput
for iTime=1:nTime
B = gradRaw(iOutput,2:end,iTime);
grad(iOutput,iTime,gradInfo.xuIdx(:,iTime)) = permute(B,[3,1,2]);
end
end
end
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [cost, costGrad] = grad_objective(z,pack,pathObj,bndObj,gradInfo,weights)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
%Unpack the decision variables:
[t,x,u] = unPackDecVar(z,pack);
% Time step for integration:
[dt, dtGrad] = grad_timeStep(t, gradInfo);
nTime = length(t);
nState = size(x,1);
nControl = size(u,1);
nDecVar = length(z);
% Compute the cost integral along the trajectory
if isempty(pathObj)
integralCost = 0;
integralCostGrad = zeros(nState+nControl,1);
else
% Objective function integrand and gradients:
[obj, objGradRaw] = pathObj(t,x,u);
nInput = size(objGradRaw,1);
objGradRaw = reshape(objGradRaw,1,nInput,nTime);
objGrad = grad_reshapeContinuous(objGradRaw,gradInfo);
% Integration by quadrature:
integralCost = dt*obj*weights; % Integration
% Gradient of integral objective function
objGrad = reshape(objGrad,nTime,nDecVar);
integralCostGrad = ...
dtGrad*(obj*weights) + ...
dt*sum(objGrad.*(weights*ones(1,nDecVar)),1);
end
% Compute the cost at the boundaries of the trajectory
if isempty(bndObj)
bndCost = 0;
bndCostGrad = zeros(1,nDecVar);
else
t0 = t(1);
tF = t(end);
x0 = x(:,1);
xF = x(:,end);
[bndCost, bndCostGradRaw] = bndObj(t0,x0,tF,xF);
bndCostGrad = grad_reshapeBoundary(bndCostGradRaw,gradInfo);
end
% Cost function
cost = bndCost + integralCost;
% Gradients
costGrad = bndCostGrad + integralCostGrad;
end
%%%% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%%%
function [c, ceq, cGrad, ceqGrad] = myCstGrad(z,pack,dynFun, pathCst, bndCst, defectCst, gradInfo)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% dynFun = user-defined dynamics function
% pathCst = user-defined constraints along the path
% endCst = user-defined constraints at the boundaries
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
%Unpack the decision variables:
[t,x,u] = unPackDecVar(z,pack);
% Time step for integration:
[dt, dtGrad] = grad_timeStep(t,gradInfo);
%%%% Compute defects along the trajectory:
[f, fGradRaw] = dynFun(t,x,u);
fGrad = grad_reshapeContinuous(fGradRaw,gradInfo);
[defects, defectsGrad] = defectCst(dt,x,f,dtGrad,xGrad,fGrad,gradInfo);
% Compute gradients of the user-defined constraints and then pack up:
[c, ceq, cGrad, ceqGrad] = grad_collectConstraints(t,x,u,...
defects, defectsGrad, pathCst, bndCst, gradInfo);
end
|
github
|
pvarin/DynamicVAE-master
|
Derive_Equations.m
|
.m
|
DynamicVAE-master/MatthewPeterKelly-OptimTraj-9a33249/demo/fiveLinkBiped/costOfTransport/Derive_Equations.m
| 27,136 |
utf_8
|
2ee06d2549cae61acad48475153b4214
|
function Derive_Equations()
%%%% Derive Equations - Five Link Biped Model %%%%
%
% This function derives the equations of motion, as well as some other useful
% equations (kinematics, contact forces, ...) for the five-link biped
% model.
%
% This version of the code includes a few more complicated features for
% dealing with difficult cost functions. In particular, it adds 10 slack
% variables to compute the abs(power) term in the cost function, and the
% primary control is the derivative of torque, rather than torque itself.
% This allows for regularization by the derivative of the input.
%
%
% Nomenclature:
%
% - There are five links, which will be numbered starting with "1" for the
% stance leg tibia, increasing as the links are father from the base joint,
% and ending with "5" for the swing leg tibia.
% 1 - stance leg tibia (lower leg)
% 2 - stance leg femur (upper leg)
% 3 - torso
% 4 - swing leg femur
% 5 - swing leg tibia
%
% - This script uses absolute angles, which are represented with "q". All
% angles use positive convention, with the zero angle corresponding to a
% vertically aligned link configuration. [q] = [0] has the torso balanced
% upright, with both legs fully extended straight below it.
%
% - Derivatives with respect to time are notated by prepending a "d". For
% example the rate of change in an absolute angle is "dq" and angular
% acceleration would be "ddq"
%
% - Joint positions are given with "P", center of mass positions are "G"
%
clc; clear;
disp('Creating variables and derivatives...')
%%%% Absolute orientation (angle) of each link
q1 = sym('q1', 'real');
q2 = sym('q2','real');
q3 = sym('q3','real');
q4 = sym('q4','real');
q5 = sym('q5','real');
%%%% Absolute angular rate of each link
dq1 = sym('dq1','real');
dq2 = sym('dq2','real');
dq3 = sym('dq3','real');
dq4 = sym('dq4','real');
dq5 = sym('dq5','real');
%%%% Absolute angular acceleration of each linke
ddq1 = sym('ddq1','real');
ddq2 = sym('ddq2','real');
ddq3 = sym('ddq3','real');
ddq4 = sym('ddq4','real');
ddq5 = sym('ddq5','real');
%%%% Torques at each joint
u1 = sym('u1','real'); %Stance foot
u2 = sym('u2','real'); %Stance knee
u3 = sym('u3','real'); %Stance hip
u4 = sym('u4','real'); %Swing hip
u5 = sym('u5','real'); %Swing knee
%%%% Torques rate at each joint
du1 = sym('du1','real'); %Stance foot
du2 = sym('du2','real'); %Stance knee
du3 = sym('du3','real'); %Stance hip
du4 = sym('du4','real'); %Swing hip
du5 = sym('du5','real'); %Swing knee
%%%% Slack variables -- negative component of power
sn1 = sym('sn1','real'); %Stance foot
sn2 = sym('sn2','real'); %Stance knee
sn3 = sym('sn3','real'); %Stance hip
sn4 = sym('sn4','real'); %Swing hip
sn5 = sym('sn5','real'); %Swing knee
%%%% Slack variables -- positive component of power
sp1 = sym('sp1','real'); %Stance foot
sp2 = sym('sp2','real'); %Stance knee
sp3 = sym('sp3','real'); %Stance hip
sp4 = sym('sp4','real'); %Swing hip
sp5 = sym('sp5','real'); %Swing knee
%%%% Mass of each link
m1 = sym('m1','real');
m2 = sym('m2','real');
m3 = sym('m3','real');
m4 = sym('m4','real');
m5 = sym('m5','real');
%%%% Distance between parent joint and link center of mass
c1 = sym('c1','real');
c2 = sym('c2','real');
c3 = sym('c3','real');
c4 = sym('c4','real');
c5 = sym('c5','real');
%%%% Length of each link
l1 = sym('l1','real');
l2 = sym('l2','real');
l3 = sym('l3','real');
l4 = sym('l4','real');
l5 = sym('l5','real');
%%%% Moment of inertia of each link about its own center of mass
I1 = sym('I1','real');
I2 = sym('I2','real');
I3 = sym('I3','real');
I4 = sym('I4','real');
I5 = sym('I5','real');
g = sym('g','real'); % Gravity
Fx = sym('Fx','real'); %Horizontal contact force at stance foot
Fy = sym('Fy','real'); %Vertical contact force at stance foot
empty = sym('empty','real'); %Used for vectorization, user should pass a vector of zeros
t = sym('t','real'); %dummy continuous time
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Set up coordinate system and unit vectors %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
i = sym([1;0]); %Horizontal axis
j = sym([0;1]); %Vertical axis
e1 = cos(q1)*(j) + sin(q1)*(-i); %unit vector from P0 -> P1, (contact point to stance knee)
e2 = cos(q2)*(j) + sin(q2)*(-i); %unit vector from P1 -> P2, (stance knee to hip)
e3 = cos(q3)*(j) + sin(q3)*(-i); %unit vector from P2 -> P3, (hip to shoulders);
e4 = -cos(q4)*(j) - sin(q4)*(-i); %unit vector from P2 -> P4, (hip to swing knee);
e5 = -cos(q5)*(j) - sin(q5)*(-i); %unit vector from P4 -> P5, (swing knee to swing foot);
P0 = 0*i + 0*j; %stance foot = Contact point = origin
P1 = P0 + l1*e1; %stance knee
P2 = P1 + l2*e2; %hip
P3 = P2 + l3*e3; %shoulders
P4 = P2 + l4*e4; %swing knee
P5 = P4 + l5*e5; %swing foot
G1 = P1 - c1*e1; % CoM stance leg tibia
G2 = P2 - c2*e2; % CoM stance leg febur
G3 = P3 - c3*e3; % CoM torso
G4 = P2 + c4*e4; % CoM swing leg femur
G5 = P4 + c5*e5; % CoM swing leg tibia
G = (m1*G1 + m2*G2 + m3*G3 + m4*G4 + m5*G5)/(m1+m2+m3+m4+m5); %Center of mass for entire robot
%%%% Define a function for doing '2d' cross product: dot(a x b, k)
cross2d = @(a,b)(a(1)*b(2) - a(2)*b(1));
%%%% Weight of each link:
w1 = -m1*g*j;
w2 = -m2*g*j;
w3 = -m3*g*j;
w4 = -m4*g*j;
w5 = -m5*g*j;
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Derivatives %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
q = [q1;q2;q3;q4;q5];
dq = [dq1;dq2;dq3;dq4;dq5];
ddq = [ddq1;ddq2;ddq3;ddq4;ddq5];
u = [u1;u2;u3;u4;u5];
du = [du1;du2;du3;du4;du5];
sn = [sn1;sn2;sn3;sn4;sn5];
sp = [sp1;sp2;sp3;sp4;sp5];
z = [t;q;dq;u;du;sn;sp]; % time-varying vector of inputs
% Neat trick to compute derivatives using the chain rule
derivative = @(in)( jacobian(in,[q;dq;u])*[dq;ddq;du] );
% Velocity of the swing foot (used for step constraints)
dP5 = derivative(P5);
% Compute derivatives for the CoM of each link:
dG1 = derivative(G1); ddG1 = derivative(dG1);
dG2 = derivative(G2); ddG2 = derivative(dG2);
dG3 = derivative(G3); ddG3 = derivative(dG3);
dG4 = derivative(G4); ddG4 = derivative(dG4);
dG5 = derivative(G5); ddG5 = derivative(dG5);
dG = derivative(G); ddG = derivative(dG);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Calculations: %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
singleStanceDynamics();
objectiveFunctions();
heelStrikeDynamics();
mechanicalEnergy();
contactForces();
kinematics();
disp('Done!');
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Single-Stance Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% I solve the dynamics here by carefully selecting angular momentum balance
% equations about each joint, working my way out the kinematic tree from
% the root.
function singleStanceDynamics()
disp('Deriving single stance dynamics...')
%%%% AMB - entire system @ P0
eqnTorque0 = ...
cross2d(G1-P0,w1) + ...
cross2d(G2-P0,w2) + ...
cross2d(G3-P0,w3) + ...
cross2d(G4-P0,w4) + ...
cross2d(G5-P0,w5) + ...
u1;
eqnInertia0 = ...
cross2d(G1-P0,m1*ddG1) + ddq1*I1 + ...
cross2d(G2-P0,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P0,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P0,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P0,m5*ddG5) + ddq5*I5;
%%%% AMB - swing leg, torso, stance femer @ stance knee
eqnTorque1 = ...
cross2d(G2-P1,w2) + ...
cross2d(G3-P1,w3) + ...
cross2d(G4-P1,w4) + ...
cross2d(G5-P1,w5) + ...
u2;
eqnInertia1 = ...
cross2d(G2-P1,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P1,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P1,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P1,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg, torso @ hip
eqnTorque2 = ...
cross2d(G3-P2,w3) + ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u3;
eqnInertia2 = ...
cross2d(G3-P2,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg @ hip
eqnTorque3 = ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u4;
eqnInertia3 = ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing tibia % swing knee
eqnTorque4 = ...
cross2d(G5-P4,w5) + ...
u5;
eqnInertia4 = ...
cross2d(G5-P4,m5*ddG5) + ddq5*I5 ;
%%%% Collect and solve equations:
eqns = [...
eqnTorque0 - eqnInertia0;
eqnTorque1 - eqnInertia1;
eqnTorque2 - eqnInertia2;
eqnTorque3 - eqnInertia3;
eqnTorque4 - eqnInertia4];
[MM, FF] = equationsToMatrix(eqns,ddq); % ddq = MM\ff;
%%%% Compute gradients:
[m, mi, mz, mzi, mzd] = computeGradients(MM,z,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,z,empty);
% Write function file:
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_dynSs.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'u1','u2','u3','u4','u5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g','empty'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Objective Functions %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function objectiveFunctions()
% Joint rates:
v1 = dq1; % joint rate 1
v2 = dq2-dq1; % joint rate 2
v3 = dq3-dq2; % joint rate 3
v4 = dq4-dq3; % joint rate 4
v5 = dq5-dq4; % joint rate 5
% Compute the power used by each joint
pow1 = v1*u1; %Power used by joint 1
pow2 = v2*u2; %Power used by joint 2
pow3 = v3*u3; %Power used by joint 3
pow4 = v4*u4; %Power used by joint 4
pow5 = v5*u5; %Power used by joint 5
% Constraint on the slack variables:
slackCst = [...
pow1 - (sp1 - sn1);
pow2 - (sp2 - sn2);
pow3 - (sp3 - sn3);
pow4 - (sp4 - sn4);
pow5 - (sp5 - sn5)];
% Gradients of the constraint on slack variables:
[c, ~, cz, czi, ~] = computeGradients(slackCst,z,empty);
matlabFunction(c,cz,czi,...
'file','autoGen_cst_costOfTransport.m',...
'vars',{...
'dq1','dq2','dq3','dq4','dq5',...
'u1','u2','u3','u4','u5',...
'sn1','sn2','sn3','sn4','sn5',...
'sp1','sp2','sp3','sp4','sp5','empty'});
% abs(power) using slack variables:
gammaNeg = sym('gammaNeg','real'); %Torque-squared smoothing parameter
gammaPos = sym('gammaPos','real'); %Torque-squared smoothing parameter
absPower = gammaNeg*(sn1 + sn2 + sn3 + sn4 + sn5) + ...
gammaPos*(sp1 + sp2 + sp3 + sp4 + sp5);
% Cost of Transport:
weight = (m1+m2+m3+m4+m5)*g;
stepLength = sym('stepLength','real');
alpha = sym('alpha','real'); %Torque-squared smoothing parameter
beta = sym('beta','real'); %Torque-rate squared smoothing
F = absPower/(weight*stepLength) + ...
alpha*(u1^2 + u2^2 + u3^2 + u4^2 + u5^2) + ...
beta*(du1^2 + du2^2 + du3^2 + du4^2 + du5^2);
[f, ~, fz, fzi, ~] = computeGradients(F,z,empty);
matlabFunction(f,fz,fzi,...
'file','autoGen_obj_costOfTransport.m',...
'vars',{...
'm1','m2','m3','m4','m5',...
'u1','u2','u3','u4','u5',...
'du1','du2','du3','du4','du5',...
'sn1','sn2','sn3','sn4','sn5', ...
'sp1','sp2','sp3','sp4','sp5',...
'g','stepLength','gammaNeg','gammaPos','alpha','beta','empty'});
% Swing foot height:
stepHeight = sym('stepHeight','real');
yFoot = P5(2);
xFoot = P5(1);
yMin = stepHeight*(1 - (xFoot/stepLength)^2);
yCst = yMin - yFoot; %Must be negative
[y, ~, yz, yzi, ~] = computeGradients(yCst,z,empty);
matlabFunction(y,yz,yzi,...
'file','autoGen_cst_swingFootHeight.m',...
'vars',{...
'q1','q2','q4','q5',...
'l1','l2','l4','l5'...
'stepLength','stepHeight'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Heel-Strike Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function heelStrikeDynamics()
disp('Deriving heel-strike dynamics...')
%%%% Notes:
% xF - heelStrike(xI) --> constraint --> 0
% xF - collision(footSwap(xI));
%
% Angles before heel-strike:
q1m = sym('q1m','real');
q2m = sym('q2m','real');
q3m = sym('q3m','real');
q4m = sym('q4m','real');
q5m = sym('q5m','real');
qm = [q1m;q2m;q3m;q4m;q5m];
% Angles after heel-strike
q1p = sym('q1p','real');
q2p = sym('q2p','real');
q3p = sym('q3p','real');
q4p = sym('q4p','real');
q5p = sym('q5p','real');
qp = [q1p;q2p;q3p;q4p;q5p];
% Angular rates before heel-strike:
dq1m = sym('dq1m','real');
dq2m = sym('dq2m','real');
dq3m = sym('dq3m','real');
dq4m = sym('dq4m','real');
dq5m = sym('dq5m','real');
dqm = [dq1m;dq2m;dq3m;dq4m;dq5m];
% Angular rates after heel-strike
dq1p = sym('dq1p','real');
dq2p = sym('dq2p','real');
dq3p = sym('dq3p','real');
dq4p = sym('dq4p','real');
dq5p = sym('dq5p','real');
dqp = [dq1p;dq2p;dq3p;dq4p;dq5p];
% torque before heel-strike:
u1m = sym('u1m','real');
u2m = sym('u2m','real');
u3m = sym('u3m','real');
u4m = sym('u4m','real');
u5m = sym('u5m','real');
um = [u1m;u2m;u3m;u4m;u5m];
% torque after heel-strike
u1p = sym('u1p','real');
u2p = sym('u2p','real');
u3p = sym('u3p','real');
u4p = sym('u4p','real');
u5p = sym('u5p','real');
up = [u1p;u2p;u3p;u4p;u5p];
% Compute kinematics before heel-strike:
inVars = {'q1','q2','q3','q4','q5','dq1','dq2','dq3','dq4','dq5'};
outVarsM = {'q1m','q2m','q3m','q4m','q5m','dq1m','dq2m','dq3m','dq4m','dq5m'};
% P0m = subs(P0,inVars,outVarsM);
P1m = subs(P1,inVars,outVarsM);
P2m = subs(P2,inVars,outVarsM);
% P3m = subs(P3,inVars,outVarsM);
P4m = subs(P4,inVars,outVarsM);
P5m = subs(P5,inVars,outVarsM);
dP5m = subs(dP5,inVars,outVarsM);
G1m = subs(G1,inVars,outVarsM);
G2m = subs(G2,inVars,outVarsM);
G3m = subs(G3,inVars,outVarsM);
G4m = subs(G4,inVars,outVarsM);
G5m = subs(G5,inVars,outVarsM);
dG1m = subs(dG1,inVars,outVarsM);
dG2m = subs(dG2,inVars,outVarsM);
dG3m = subs(dG3,inVars,outVarsM);
dG4m = subs(dG4,inVars,outVarsM);
dG5m = subs(dG5,inVars,outVarsM);
% Compute kinematics after heel-strike:
outVarsP = {'q1p','q2p','q3p','q4p','q5p','dq1p','dq2p','dq3p','dq4p','dq5p'};
P0p = subs(P0,inVars,outVarsP);
P1p = subs(P1,inVars,outVarsP);
P2p = subs(P2,inVars,outVarsP);
% P3p = subs(P3,inVars,outVarsP);
P4p = subs(P4,inVars,outVarsP);
% P5p = subs(P5,inVars,outVarsP);
dP5p = subs(dP5,inVars,outVarsP);
G1p = subs(G1,inVars,outVarsP);
G2p = subs(G2,inVars,outVarsP);
G3p = subs(G3,inVars,outVarsP);
G4p = subs(G4,inVars,outVarsP);
G5p = subs(G5,inVars,outVarsP);
dG1p = subs(dG1,inVars,outVarsP);
dG2p = subs(dG2,inVars,outVarsP);
dG3p = subs(dG3,inVars,outVarsP);
dG4p = subs(dG4,inVars,outVarsP);
dG5p = subs(dG5,inVars,outVarsP);
%%%% AMB - entire system @ New stance foot
eqnHs0m = ... %Before collision
cross2d(G1m-P5m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P5m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P5m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P5m,m4*dG4m) + dq4m*I4 + ...
cross2d(G5m-P5m,m5*dG5m) + dq5m*I5;
eqnHs0 = ... %After collision
cross2d(G1p-P0p,m1*dG1p) + dq1p*I1 + ...
cross2d(G2p-P0p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P0p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P0p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P0p,m5*dG5p) + dq5p*I5;
%%%% AMB - new swing leg, torso, stance femer @ stance knee
eqnHs1m = ... %Before collision
cross2d(G1m-P4m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P4m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P4m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P4m,m4*dG4m) + dq4m*I4;
eqnHs1 = ... %After collision
cross2d(G2p-P1p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P1p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P1p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P1p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg, torso @ new hip
eqnHs2m = ... %Before collision
cross2d(G3m-P2m,m3*dG3m) + dq3m*I3 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2 + ...
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1;
eqnHs2 = ... %After collision
cross2d(G3p-P2p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg @ new hip
eqnHs3m = ... %Before collision
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2;
eqnHs3 = ... %After collision
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing tibia @ new swing knee
eqnHs4m = ... %Before collision
cross2d(G1m-P1m,m1*dG1m) + dq1m*I1;
eqnHs4 = ... %After collision
cross2d(G5p-P4p,m5*dG5p) + dq5p*I5;
%%%% Collect and solve equations:
eqnHs = [...
eqnHs0m - eqnHs0;
eqnHs1m - eqnHs1;
eqnHs2m - eqnHs2;
eqnHs3m - eqnHs3;
eqnHs4m - eqnHs4];
[MM, FF] = equationsToMatrix(eqnHs,dqp);
%%%% Compute gradients:
tp = sym('tp','real'); %Initial trajectory time
tm = sym('tm','real'); %Final trajectory time
zBnd = [tp;qp;dqp;up;tm;qm;dqm;um];
[m, mi, mz, mzi, mzd] = computeGradients(MM,zBnd,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,zBnd,empty);
% Heel-strike
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_cst_heelStrike.m',...
'vars',{...
'q1p','q2p','q3p','q4p','q5p',...
'q1m','q2m','q3m','q4m','q5m',...
'dq1m','dq2m','dq3m','dq4m','dq5m',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5','empty'});
% Collision velocity of the swing foot:
cst = [-dP5p(2); dP5m(2)]; %Swing foot velocity before and after collision (negative sign is intentional, since output is constrained to be negative);
cstJac = jacobian(cst,zBnd); %Gradient
matlabFunction(cst, cstJac,...
'file','autoGen_cst_footVel.m',...
'vars',{...
'q1p','q2p','q4p','q5p',...
'q1m','q2m','q4m','q5m',...
'dq1p','dq2p','dq4p','dq5p',...
'dq1m','dq2m','dq4m','dq5m',...
'l1','l2','l4','l5'});
% Step length and height constraint:
stepLength = sym('stepLength','real');
ceq = [P5m(1)-stepLength; P5m(2)];
ceqJac = jacobian(ceq,zBnd); %Gradient
matlabFunction(ceq, ceqJac,...
'file','autoGen_cst_steplength.m',...
'vars',{...
'q1m','q2m','q4m','q5m',...
'l1','l2','l4','l5','stepLength'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Mechanical Energy %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function mechanicalEnergy()
disp('Deriving mechanical energy...')
%%%% Energy:
KineticEnergy = ...
0.5*m1*dot(dG1,dG1) + 0.5*I1*dq1^2 + ...
0.5*m2*dot(dG2,dG2) + 0.5*I2*dq2^2 + ...
0.5*m3*dot(dG3,dG3) + 0.5*I3*dq3^2 + ...
0.5*m4*dot(dG4,dG4) + 0.5*I4*dq4^2 + ...
0.5*m5*dot(dG5,dG5) + 0.5*I5*dq5^2;
PotentialEnergy = ...
m1*g*G1(2) + ...
m2*g*G2(2) + ...
m3*g*G3(2) + ...
m4*g*G4(2) + ...
m5*g*G5(2);
matlabFunction(KineticEnergy, PotentialEnergy,...
'file','autoGen_energy.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'KE','PE'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Contact Forces %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function contactForces()
%%%% Contact Forces:
eqnForce5 = w1 + w2 + w3 + w4 + w5 + Fx*i + Fy*j;
eqnInertia5 = (m1+m2+m3+m4+m5)*ddG;
[AA,bb] = equationsToMatrix(eqnForce5-eqnInertia5,[Fx;Fy]);
ContactForces = AA\bb;
matlabFunction(ContactForces(1),ContactForces(2),...
'file','autoGen_contactForce.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'ddq1','ddq2','ddq3','ddq4','ddq5',...
'm1','m2','m3','m4','m5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'Fx','Fy'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Write Kinematics Files %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function kinematics()
disp('Writing kinematics files...')
P = [P1; P2; P3; P4; P5];
Gvec = [G1; G2; G3; G4; G5];
% Used for plotting and animation
matlabFunction(P,Gvec,'file','autoGen_getPoints.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5'},...
'outputs',{'P','Gvec'});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Helper Functions %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [m, mi, mz, mzi, dim] = computeGradients(M,z,empty)
%
% This function computes the gradients of a matrix M with respect the the
% variables in z, and then returns both the matrix and its gradient as
% column vectors of their non-zero elements, along with the linear indicies
% to unpack them. It also simplifies m and mz.
%
% INPUTS:
% M = [na, nb] = symbolic matrix
% z = [nc, 1] = symbolic vector
%
% OUTPUTS:
% m = [nd, 1] = symbolic vector of non-zero elements in M
% mi = [nd, 1] = linear indicies to map m --> [na,nb] matrix
% mz = [ne, 1] = symbolic vector of non-zero elements in Mz
% mzi = [ne, 1] = linear indicies to map mz --> [na,nb,nc] array
% dim = [3,1] = [na,nb,nc] = dimensions of 3d version of mz
%
[na, nb] = size(M);
nc = size(z,1);
M = simplify(M);
mz2 = jacobian(M(:),z); %Compute jacobian of M, by first reshaping M to be a column vector
mz3 = reshape(mz2,na,nb,nc); %Expand back out to a three-dimensional array
mz3 = simplify(mz3);
% Extract non-zero elements to a column vector:
mi = find(M);
m = M(mi);
mzi = find(mz3);
mz = mz3(mzi); mz = mz(:); %Collapse to a column vector
dim = [na,nb,nc];
% Pad any constant terms with "empty" to permit vectorization:
m = vectorizeHack(m, z, empty);
mz = vectorizeHack(mz, z, empty);
end
function x = vectorizeHack(x, z, empty)
%
% This function searches for any elements of x that are not dependent on
% any element of z. In this case, the automatically generated code will
% fail to vectorize properly. One solution is to add an array of zeros
% (empty) to the element.
%
% x = column vector of symbolic expressions
% z = column vector of symbolic variables
% z = symbolic variable, which the user will set equal to zero.
%
% Compute dependencies
g = jacobian(x,z);
% Check for rows of x with no dependence on z
[n,m] = size(g);
idxConst = true(n,1);
for i=1:n
for j=1:m
if ~isequal(sym(0),g(i,j))
idxConst(i) = false;
break;
end
end
end
% Add empty to those enteries
x(idxConst) = x(idxConst) + empty;
end
|
github
|
minitaur-users/minitaur-mainboard-code-master
|
open_log.m
|
.m
|
minitaur-mainboard-code-master/libraries/OpenLog/open_log.m
| 1,347 |
utf_8
|
66368e5a8bb5f6c5ddc3d16fdaa79511
|
%{
* Copyright (C) Ghost Robotics - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Avik De <[email protected]> and Pranav Bhounsule
%}
function s = open_log(fname)
if ~exist(fname,'file')
error('File not found: %s', fname)
end
fileID = fopen(fname);
colnames = fgetl(fileID);
fmt = fgetl(fileID);
fprintf('Opened %s\nKeys: %s\nFormat: %s\n', fname, colnames, fmt)
colnames = strsplit(colnames, ',');
data = zeros([0,length(colnames)]);
i = 0;
try
while ~feof(fileID)
alignment1 = fread(fileID,1,'uint8');
if alignment1 ~= 170
continue;
end
alignment2 = fread(fileID,1,'uint8');
if alignment2 ~= 187
continue;
end
i = i+1;
for j=1:length(fmt)
if (fmt(j)=='f')
type = 'float';
elseif (fmt(j)=='I')
type = 'uint32';
elseif (fmt(j) =='B')
type = 'uint8';
else
error('unspecfied datatype in fmt');
end
data(i,j)=fread(fileID,1,type);
end
end
fclose(fileID);
catch
disp('Finished reading');
end
% Return data in a struct
s = struct();
for cn=1:length(colnames)
% convert time to seconds
if strcmp(colnames{cn},'t')
data(:,cn) = 0.001 * data(:,cn);
end
s = setfield(s,colnames{cn},data(:,cn));
end
end
|
github
|
thomaskuestner/CNNArt-master
|
pdftops.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/pdftops.m
| 3,077 |
utf_8
|
8dff856e4b450072050d8aa571d1a08e
|
function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
% under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
path_ = 'C:\Program Files\xpdf\pdftops.exe';
else
path_ = '/usr/local/bin/pdftops';
end
if check_store_xpdf_path(path_)
return
end
% Ask the user to enter the path
while 1
if strncmp(computer,'MAC',3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.'))
end
base = uigetdir('/', 'Pdftops not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep];
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break;
end
end
if check_store_xpdf_path(path_)
return
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system(sprintf('"%s" -h', path_));
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
end
|
github
|
thomaskuestner/CNNArt-master
|
crop_borders.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/crop_borders.m
| 1,669 |
utf_8
|
725f526e7270a9b417300035d8748a9c
|
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, v] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how many pixels padding to have. Default: 0.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% v - 1x4 vector of start and end indices for first two dimensions, s.t.
% B = A(v(1):v(2),v(3):v(4),:,:).
function [A, v] = crop_borders(A, bcol, padding)
if nargin < 3
padding = 0;
end
[h, w, c, n] = size(A);
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
bcol = A(h,ceil(end/2),:,1);
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop the background, leaving one boundary pixel to avoid bleeding on resize
v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];
A = A(v(1):v(2),v(3):v(4),:,:);
end
function A = col(A)
A = A(:);
end
|
github
|
thomaskuestner/CNNArt-master
|
isolate_axes.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/isolate_axes.m
| 3,668 |
utf_8
|
e2dce471e433886fcb87f9dcb284a2cb
|
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m.
% 12/12/12 - Add support for isolating uipanels. Thanks to michael for
% suggesting it.
% 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!).
% 05/12/13 - Bug fix to axes having different units. Thanks to Remington
% Reid for reporting the issue.
function fh = isolate_axes(ah, vis)
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'});
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
ax_pos = get(ah, 'OuterPosition');
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
leg_pos = get(lh, 'OuterPosition');
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github
|
thomaskuestner/CNNArt-master
|
im2gif.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/im2gif.m
| 6,168 |
utf_8
|
01a5042cc084cddfe4ce631d33de7c8f
|
%IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
if(size(A,3) == 1)
A = repmat(A,[1 1 3 1]);
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
% if(ndims(A) == 2)
% A = repmat(A,[1 1 3]);
% end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github
|
thomaskuestner/CNNArt-master
|
read_write_entire_textfile.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/read_write_entire_textfile.m
| 924 |
utf_8
|
779e56972f5d9778c40dee98ddbd677e
|
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github
|
thomaskuestner/CNNArt-master
|
pdf2eps.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/pdf2eps.m
| 1,471 |
utf_8
|
a1f41f0c7713c73886a2323e53ed982b
|
%PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github
|
thomaskuestner/CNNArt-master
|
print2array.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/print2array.m
| 6,273 |
utf_8
|
c2feb752d8836426a74edd9357f1ff17
|
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2012
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the
% issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting
% the issue.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure
% size and erasemode settings. Makes it a bit slower, but more
% reliable. Thanks to Phil Trinh and Meelis Lootus for reporting
% the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting
% it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
function [A, bcol] = print2array(fig, res, renderer)
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
if nargin > 2 && strcmp(renderer, '-painters')
% Print to eps file
tmp_eps = [tempname '.eps'];
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"'];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
err = false;
% Set paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
try
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
% Reset paper size
set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
% Throw any error that occurred
if err
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = [px([4 3])*res 3];
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
thomaskuestner/CNNArt-master
|
append_pdfs.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/append_pdfs.m
| 2,010 |
utf_8
|
1034abde9642693c404671ff1c693a22
|
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
function append_pdfs(varargin)
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
if append
output = [tempname '.pdf'];
else
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
cmdfile = [tempname '.txt'];
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github
|
thomaskuestner/CNNArt-master
|
using_hg2.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/using_hg2.m
| 365 |
utf_8
|
6a7f56042fda1873d8225eb3ec1cc197
|
%USING_HG2 Determine if the HG2 graphics pipeline is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics pipeline is being used
% (true) or not (false).
function tf = using_hg2(fig)
try
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = false;
end
end
|
github
|
thomaskuestner/CNNArt-master
|
eps2pdf.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/eps2pdf.m
| 5,009 |
utf_8
|
5658b3d96232e138be7fd49693d88453
|
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
%IN:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed to
% already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale or
% not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% Copyright (C) Oliver Woodford 2009-2011
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
function eps2pdf(source, dest, crop, append, gray, quality)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
else
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
thomaskuestner/CNNArt-master
|
copyfig.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/copyfig.m
| 812 |
utf_8
|
b6b1fa9a9351df33ae0d42056c3df40a
|
%COPYFIG Create a copy of a figure, without changing the figure
%
% Examples:
% fh_new = copyfig(fh_old)
%
% This function will create a copy of a figure, but not change the figure,
% as copyobj sometimes does, e.g. by changing legends.
%
% IN:
% fh_old - The handle of the figure to be copied. Default: gcf.
%
% OUT:
% fh_new - The handle of the created figure.
% Copyright (C) Oliver Woodford 2012
function fh = copyfig(fh)
% Set the default
if nargin == 0
fh = gcf;
end
% Is there a legend?
if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
% Safe to copy using copyobj
fh = copyobj(fh, 0);
else
% copyobj will change the figure, so save and then load it instead
tmp_nam = [tempname '.fig'];
hgsave(fh, tmp_nam);
fh = hgload(tmp_nam);
delete(tmp_nam);
end
end
|
github
|
thomaskuestner/CNNArt-master
|
user_string.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/user_string.m
| 2,460 |
utf_8
|
e8aa836a5140410546fceccb4cca47aa
|
%USER_STRING Get/set a user specific string
%
% Examples:
% string = user_string(string_name)
% saved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% IN:
% string_name - String containing the name of the string required. The
% string is extracted from a file called (string_name).txt,
% stored in the same directory as user_string.m.
% new_string - The new string to be saved under the name given by
% string_name.
%
% OUT:
% string - The currently saved string. Default: ''.
% saved - Boolean indicating whether the save was succesful
% Copyright (C) Oliver Woodford 2011-2013
% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.
% 10/01/2013 - Access files in text, not binary mode, as latter can cause
% errors. Thanks to Christian for pointing this out.
function string = user_string(string_name, string)
if ~ischar(string_name)
error('string_name must be a string.');
end
% Create the full filename
string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']);
if nargin > 1
% Set string
if ~ischar(string)
error('new_string must be a string.');
end
% Make sure the save directory exists
dname = fileparts(string_name);
if ~exist(dname, 'dir')
% Create the directory
try
if ~mkdir(dname)
string = false;
return
end
catch
string = false;
return
end
% Make it hidden
try
fileattrib(dname, '+h');
catch
end
end
% Write the file
fid = fopen(string_name, 'wt');
if fid == -1
string = false;
return
end
try
fprintf(fid, '%s', string);
catch
fclose(fid);
string = false;
return
end
fclose(fid);
string = true;
else
% Get string
fid = fopen(string_name, 'rt');
if fid == -1
string = '';
return
end
string = fgetl(fid);
fclose(fid);
end
end
|
github
|
thomaskuestner/CNNArt-master
|
export_fig.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/export_fig.m
| 29,720 |
utf_8
|
923dcc1ad89f1381ee70abbf422b20a5
|
%EXPORT_FIG Exports figures suitable for publication
%
% Examples:
% im = export_fig
% [im alpha] = export_fig
% export_fig filename
% export_fig filename -format1 -format2
% export_fig ... -nocrop
% export_fig ... -transparent
% export_fig ... -native
% export_fig ... -m<val>
% export_fig ... -r<val>
% export_fig ... -a<val>
% export_fig ... -q<val>
% export_fig ... -p<val>
% export_fig ... -<renderer>
% export_fig ... -<colorspace>
% export_fig ... -append
% export_fig ... -bookmark
% export_fig(..., handle)
%
% This function saves a figure or single axes to one or more vector and/or
% bitmap file formats, and/or outputs a rasterized version to the
% workspace, with the following properties:
% - Figure/axes reproduced as it appears on screen
% - Cropped borders (optional)
% - Embedded fonts (vector formats)
% - Improved line and grid line styles
% - Anti-aliased graphics (bitmap formats)
% - Render images at native resolution (optional for bitmap formats)
% - Transparent background supported (pdf, eps, png)
% - Semi-transparent patch objects supported (png only)
% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
% - Variable image compression, including lossless (pdf, eps, jpg)
% - Optionally append to file (pdf, tiff)
% - Vector formats: pdf, eps
% - Bitmap formats: png, tiff, jpg, bmp, export to workspace
%
% This function is especially suited to exporting figures for use in
% publications and presentations, because of the high quality and
% portability of media produced.
%
% Note that the background color and figure dimensions are reproduced
% (the latter approximately, and ignoring cropping & magnification) in the
% output file. For transparent background (and semi-transparent patch
% objects), use the -transparent option or set the figure 'Color' property
% to 'none'. To make axes transparent set the axes 'Color' property to
% 'none'. Pdf, eps and png are the only file formats to support a
% transparent background, whilst the png format alone supports transparency
% of patch objects.
%
% The choice of renderer (opengl, zbuffer or painters) has a large impact
% on the quality of output. Whilst the default value (opengl for bitmaps,
% painters for vector formats) generally gives good results, if you aren't
% satisfied then try another renderer. Notes: 1) For vector formats (eps,
% pdf), only painters generates vector graphics. 2) For bitmaps, only
% opengl can render transparent patch objects correctly. 3) For bitmaps,
% only painters will correctly scale line dash and dot lengths when
% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
% using painters.
%
% When exporting to vector format (pdf & eps) and bitmap format using the
% painters renderer, this function requires that ghostscript is installed
% on your system. You can download this from:
% http://www.ghostscript.com
% When exporting to eps it additionally requires pdftops, from the Xpdf
% suite of functions. You can download this from:
% http://www.foolabs.com/xpdf
%
%IN:
% filename - string containing the name (optionally including full or
% relative path) of the file the figure is to be saved as. If
% a path is not specified, the figure is saved in the current
% directory. If no name and no output arguments are specified,
% the default name, 'export_fig_out', is used. If neither a
% file extension nor a format are specified, a ".png" is added
% and the figure saved in that format.
% -format1, -format2, etc. - strings containing the extensions of the
% file formats the figure is to be saved as.
% Valid options are: '-pdf', '-eps', '-png',
% '-tif', '-jpg' and '-bmp'. All combinations
% of formats are valid.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -transparent - option indicating that the figure background is to be
% made transparent (png, pdf and eps output only).
% -m<val> - option where val indicates the factor to magnify the
% on-screen figure pixel dimensions by when generating bitmap
% outputs. Default: '-m1'.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap and vector outputs at, keeping the dimensions
% of the on-screen figure. Default: '-r864' (for vector output
% only). Note that the -m option overides the -r option for
% bitmap outputs only.
% -native - option indicating that the output resolution (when outputting
% a bitmap format) should be such that the vertical resolution
% of the first suitable image found in the figure is at the
% native resolution of that image. To specify a particular
% image to use, give it the tag 'export_fig_native'. Notes:
% This overrides any value set with the -m and -r options. It
% also assumes that the image is displayed front-to-parallel
% with the screen. The output resolution is approximate and
% should not be relied upon. Anti-aliasing can have adverse
% effects on image quality (disable with the -a1 option).
% -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
% use for bitmap outputs. '-a1' means no anti-
% aliasing; '-a4' is the maximum amount (default).
% -<renderer> - option to force a particular renderer (painters, opengl
% or zbuffer) to be used over the default: opengl for
% bitmaps; painters for vector formats.
% -<colorspace> - option indicating which colorspace color figures should
% be saved in: RGB (default), CMYK or gray. CMYK is only
% supported in pdf, eps and tiff output.
% -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
% files only). Larger val, in the range 0-100, gives higher
% quality/lower compression. val > 100 gives lossless
% compression. Default: '-q95' for jpg, ghostscript prepress
% default for pdf & eps. Note: lossless compression can
% sometimes give a smaller file size than the default lossy
% compression, depending on the type of images.
% -p<val> - option to add a border of width val to eps and pdf files,
% where val is in units of the intermediate eps file. Default:
% 0 (i.e. no padding).
% -append - option indicating that if the file (pdfs only) already
% exists, the figure is to be appended as a new page, instead
% of being overwritten (default).
% -bookmark - option to indicate that a bookmark with the name of the
% figure is to be created in the output file (pdf only).
% handle - The handle of the figure, axes or uipanels (can be an array of
% handles, but the objects must be in the same figure) to be
% saved. Default: gcf.
%
%OUT:
% im - MxNxC uint8 image array of the figure.
% alpha - MxN single array of alphamatte values in range [0,1], for the
% case when the background is transparent.
%
% Some helpful examples and tips can be found at:
% https://github.com/ojwoodford/export_fig
%
% See also PRINT, SAVEAS.
% Copyright (C) Oliver Woodford 2008-2014
% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928).
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
% 20979).
% The idea of appending figures in pdfs came from Matt C in comments on the
% FEX (id: 23629)
% Thanks to Roland Martin for pointing out the colour MATLAB
% bug/feature with colorbar axes and transparent backgrounds.
% Thanks also to Andrew Matthews for describing a bug to do with the figure
% size changing in -nodisplay mode. I couldn't reproduce it, but included a
% fix anyway.
% Thanks to Tammy Threadgill for reporting a bug where an axes is not
% isolated from gui objects.
% 23/02/12: Ensure that axes limits don't change during printing
% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
% reporting it).
% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
% bookmarking of figures in pdf files.
% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
% tick marks fixed.
% 12/12/12: Add support for isolating uipanels. Thanks to michael for
% suggesting it.
% 25/09/13: Add support for changing resolution in vector formats. Thanks
% to Jan Jaap Meijer for suggesting it.
% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
% for suggesting it.
function [im, alpha] = export_fig(varargin)
% Make sure the figure is rendered correctly _now_ so that properties like
% axes limits are up-to-date.
drawnow;
% Parse the input arguments
[fig, options] = parse_args(nargout, varargin{:});
% Isolate the subplot, if it is one
cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
if cls
% Given handles of one or more axes, so isolate them from the rest
fig = isolate_axes(fig);
else
% Check we have a figure
if ~isequal(get(fig, 'Type'), 'figure');
error('Handle must be that of a figure, axes or uipanel');
end
% Get the old InvertHardcopy mode
old_mode = get(fig, 'InvertHardcopy');
end
% Hack the font units where necessary (due to a font rendering bug in
% print?). This may not work perfectly in all cases. Also it can change the
% figure layout if reverted, so use a copy.
magnify = options.magnify * options.aa_factor;
if isbitmap(options) && magnify ~= 1
fontu = findobj(fig, 'FontUnits', 'normalized');
if ~isempty(fontu)
% Some normalized font units found
if ~cls
fig = copyfig(fig);
set(fig, 'Visible', 'off');
fontu = findobj(fig, 'FontUnits', 'normalized');
cls = true;
end
set(fontu, 'FontUnits', 'points');
end
end
% MATLAB "feature": axes limits and tick marks can change when printing
Hlims = findall(fig, 'Type', 'axes');
if ~cls
% Record the old axes limit and tick modes
Xlims = make_cell(get(Hlims, 'XLimMode'));
Ylims = make_cell(get(Hlims, 'YLimMode'));
Zlims = make_cell(get(Hlims, 'ZLimMode'));
Xtick = make_cell(get(Hlims, 'XTickMode'));
Ytick = make_cell(get(Hlims, 'YTickMode'));
Ztick = make_cell(get(Hlims, 'ZTickMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
set_tick_mode(Hlims, 'X');
set_tick_mode(Hlims, 'Y');
set_tick_mode(Hlims, 'Z');
% Set to print exactly what is there
set(fig, 'InvertHardcopy', 'off');
% Set the renderer
switch options.renderer
case 1
renderer = '-opengl';
case 2
renderer = '-zbuffer';
case 3
renderer = '-painters';
otherwise
renderer = '-opengl'; % Default for bitmaps
end
% Do the bitmap formats first
if isbitmap(options)
% Get the background colour
if options.transparent && (options.png || options.alpha)
% Get out an alpha channel
% MATLAB "feature": black colorbar axes can change to white and vice versa!
hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar');
if isempty(hCB)
yCol = [];
xCol = [];
else
yCol = get(hCB, 'YColor');
xCol = get(hCB, 'XColor');
if iscell(yCol)
yCol = cell2mat(yCol);
xCol = cell2mat(xCol);
end
yCol = sum(yCol, 2);
xCol = sum(xCol, 2);
end
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
% Set the background colour to black, and set size in case it was
% changed internally
tcol = get(fig, 'Color');
set(fig, 'Color', 'k', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==0), 'YColor', [0 0 0]);
set(hCB(xCol==0), 'XColor', [0 0 0]);
% Print large version to array
B = print2array(fig, magnify, renderer);
% Downscale the image
B = downsize(single(B), options.aa_factor);
% Set background to white (and set size)
set(fig, 'Color', 'w', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==3), 'YColor', [1 1 1]);
set(hCB(xCol==3), 'XColor', [1 1 1]);
% Print large version to array
A = print2array(fig, magnify, renderer);
% Downscale the image
A = downsize(single(A), options.aa_factor);
% Set the background colour (and size) back to normal
set(fig, 'Color', tcol, 'Position', pos);
% Compute the alpha map
alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
A = alpha;
A(A==0) = 1;
A = B ./ A(:,:,[1 1 1]);
clear B
% Convert to greyscale
if options.colourspace == 2
A = rgb2grey(A);
end
A = uint8(A);
% Crop the background
if options.crop
[alpha, v] = crop_borders(alpha, 0, 1);
A = A(v(1):v(2),v(3):v(4),:);
end
if options.png
% Compute the resolution
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
% Save the png
imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
% Clear the png bit
options.png = false;
end
% Return only one channel for greyscale
if isbitmap(options)
A = check_greyscale(A);
end
if options.alpha
% Store the image
im = A;
% Clear the alpha bit
options.alpha = false;
end
% Get the non-alpha image
if isbitmap(options)
alph = alpha(:,:,ones(1, size(A, 3)));
A = uint8(single(A) .* alph + 255 * (1 - alph));
clear alph
end
if options.im
% Store the new image
im = A;
end
else
% Print large version to array
if options.transparent
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
tcol = get(fig, 'Color');
set(fig, 'Color', 'w', 'Position', pos);
A = print2array(fig, magnify, renderer);
set(fig, 'Color', tcol, 'Position', pos);
tcol = 255;
else
[A, tcol] = print2array(fig, magnify, renderer);
end
% Crop the background
if options.crop
A = crop_borders(A, tcol, 1);
end
% Downscale the image
A = downsize(A, options.aa_factor);
if options.colourspace == 2
% Convert to greyscale
A = rgb2grey(A);
else
% Return only one channel for greyscale
A = check_greyscale(A);
end
% Outputs
if options.im
im = A;
end
if options.alpha
im = A;
alpha = zeros(size(A, 1), size(A, 2), 'single');
end
end
% Save the images
if options.png
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
end
if options.bmp
imwrite(A, [options.name '.bmp']);
end
% Save jpeg with given quality
if options.jpg
quality = options.quality;
if isempty(quality)
quality = 95;
end
if quality > 100
imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
else
imwrite(A, [options.name '.jpg'], 'Quality', quality);
end
end
% Save tif images in cmyk if wanted (and possible)
if options.tif
if options.colourspace == 1 && size(A, 3) == 3
A = double(255 - A);
K = min(A, [], 3);
K_ = 255 ./ max(255 - K, 1);
C = (A(:,:,1) - K) .* K_;
M = (A(:,:,2) - K) .* K_;
Y = (A(:,:,3) - K) .* K_;
A = uint8(cat(3, C, M, Y, K));
clear C M Y K K_
end
append_mode = {'overwrite', 'append'};
imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
end
end
% Now do the vector formats
if isvector(options)
% Set the default renderer to painters
if ~options.renderer
renderer = '-painters';
end
% Generate some filenames
tmp_nam = [tempname '.eps'];
if options.pdf
pdf_nam = [options.name '.pdf'];
else
pdf_nam = [tempname '.pdf'];
end
% Generate the options for print
p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
if options.colourspace == 1
p2eArgs = [p2eArgs {'-cmyk'}];
end
if ~options.crop
p2eArgs = [p2eArgs {'-loose'}];
end
try
% Generate an eps
print2eps(tmp_nam, fig, options.bb_padding, p2eArgs{:});
% Remove the background, if desired
if options.transparent && ~isequal(get(fig, 'Color'), 'none')
eps_remove_background(tmp_nam, 1 + using_hg2(fig));
end
% Add a bookmark to the PDF if desired
if options.bookmark
fig_nam = get(fig, 'Name');
if isempty(fig_nam)
warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
end
add_bookmark(tmp_nam, fig_nam);
end
% Generate a pdf
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
catch ex
% Delete the eps
delete(tmp_nam);
rethrow(ex);
end
% Delete the eps
delete(tmp_nam);
if options.eps
try
% Generate an eps from the pdf
pdf2eps(pdf_nam, [options.name '.eps']);
catch ex
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
rethrow(ex);
end
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
end
end
if cls
% Close the created figure
close(fig);
else
% Reset the hardcopy mode
set(fig, 'InvertHardcopy', old_mode);
% Reset the axes limit and tick modes
for a = 1:numel(Hlims)
set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
end
end
end
function [fig, options] = parse_args(nout, varargin)
% Parse the input arguments
% Set the defaults
fig = get(0, 'CurrentFigure');
options = struct('name', 'export_fig_out', ...
'crop', true, ...
'transparent', false, ...
'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
'pdf', false, ...
'eps', false, ...
'png', false, ...
'tif', false, ...
'jpg', false, ...
'bmp', false, ...
'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
'append', false, ...
'im', nout == 1, ...
'alpha', nout == 2, ...
'aa_factor', 0, ...
'bb_padding', 0, ...
'magnify', [], ...
'resolution', [], ...
'bookmark', false, ...
'quality', []);
native = false; % Set resolution to native of an image
% Go through the other arguments
for a = 1:nargin-1
if all(ishandle(varargin{a}))
fig = varargin{a};
elseif ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
switch lower(varargin{a}(2:end))
case 'nocrop'
options.crop = false;
case {'trans', 'transparent'}
options.transparent = true;
case 'opengl'
options.renderer = 1;
case 'zbuffer'
options.renderer = 2;
case 'painters'
options.renderer = 3;
case 'pdf'
options.pdf = true;
case 'eps'
options.eps = true;
case 'png'
options.png = true;
case {'tif', 'tiff'}
options.tif = true;
case {'jpg', 'jpeg'}
options.jpg = true;
case 'bmp'
options.bmp = true;
case 'rgb'
options.colourspace = 0;
case 'cmyk'
options.colourspace = 1;
case {'gray', 'grey'}
options.colourspace = 2;
case {'a1', 'a2', 'a3', 'a4'}
options.aa_factor = str2double(varargin{a}(3));
case 'append'
options.append = true;
case 'bookmark'
options.bookmark = true;
case 'native'
native = true;
otherwise
val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
if ~isscalar(val)
error('option %s not recognised', varargin{a});
end
switch lower(varargin{a}(2))
case 'm'
options.magnify = val;
case 'r'
options.resolution = val;
case 'q'
options.quality = max(val, 0);
case 'p'
options.bb_padding = val;
end
end
else
[p, options.name, ext] = fileparts(varargin{a});
if ~isempty(p)
options.name = [p filesep options.name];
end
switch lower(ext)
case {'.tif', '.tiff'}
options.tif = true;
case {'.jpg', '.jpeg'}
options.jpg = true;
case '.png'
options.png = true;
case '.bmp'
options.bmp = true;
case '.eps'
options.eps = true;
case '.pdf'
options.pdf = true;
otherwise
options.name = varargin{a};
end
end
end
end
% Set default anti-aliasing now we know the renderer
if options.aa_factor == 0
options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on')) | (options.renderer == 3));
end
% Convert user dir '~' to full path
if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
end
% Compute the magnification and resolution
if isempty(options.magnify)
if isempty(options.resolution)
options.magnify = 1;
options.resolution = 864;
else
options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
end
elseif isempty(options.resolution)
options.resolution = 864;
end
% Check we have a figure handle
if isempty(fig)
error('No figure found');
end
% Set the default format
if ~isvector(options) && ~isbitmap(options)
options.png = true;
end
% Check whether transparent background is wanted (old way)
if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
options.transparent = true;
end
% If requested, set the resolution to the native vertical resolution of the
% first suitable image found
if native && isbitmap(options)
% Find a suitable image
list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native');
if isempty(list)
list = findobj(fig, 'Type', 'image', 'Visible', 'on');
end
for hIm = list(:)'
% Check height is >= 2
height = size(get(hIm, 'CData'), 1);
if height < 2
continue
end
% Account for the image filling only part of the axes, or vice
% versa
yl = get(hIm, 'YData');
if isscalar(yl)
yl = [yl(1)-0.5 yl(1)+height+0.5];
else
if ~diff(yl)
continue
end
yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
end
hAx = get(hIm, 'Parent');
yl2 = get(hAx, 'YLim');
% Find the pixel height of the axes
oldUnits = get(hAx, 'Units');
set(hAx, 'Units', 'pixels');
pos = get(hAx, 'Position');
set(hAx, 'Units', oldUnits);
if ~pos(4)
continue
end
% Found a suitable image
% Account for stretch-to-fill being disabled
pbar = get(hAx, 'PlotBoxAspectRatio');
pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
% Set the magnification to give native resolution
options.magnify = (height * diff(yl2)) / (pos * diff(yl));
break
end
end
end
function A = downsize(A, factor)
% Downsample an image
if factor == 1
% Nothing to do
return
end
try
% Faster, but requires image processing toolbox
A = imresize(A, 1/factor, 'bilinear');
catch
% No image processing toolbox - resize manually
% Lowpass filter - use Gaussian as is separable, so faster
% Compute the 1d Gaussian filter
filt = (-factor-1:factor+1) / (factor * 0.6);
filt = exp(-filt .* filt);
% Normalize the filter
filt = single(filt / sum(filt));
% Filter the image
padding = floor(numel(filt) / 2);
for a = 1:size(A, 3)
A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
end
% Subsample
A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
end
end
function A = rgb2grey(A)
A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
end
function A = check_greyscale(A)
% Check if the image is greyscale
if size(A, 3) == 3 && ...
all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
all(reshape(A(:,:,2) == A(:,:,3), [], 1))
A = A(:,:,1); % Save only one channel for 8-bit output
end
end
function eps_remove_background(fname, count)
% Remove the background of an eps file
% Open the file
fh = fopen(fname, 'r+');
if fh == -1
error('Not able to open file %s.', fname);
end
% Read the file line by line
while count
% Get the next line
l = fgets(fh);
if isequal(l, -1)
break; % Quit, no rectangle found
end
% Check if the line contains the background rectangle
if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
% Set the line to whitespace and quit
l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
fseek(fh, -numel(l), 0);
fprintf(fh, l);
% Reduce the count
count = count - 1;
end
end
% Close the file
fclose(fh);
end
function b = isvector(options)
b = options.pdf || options.eps;
end
function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
end
% Helper function
function A = make_cell(A)
if ~iscell(A)
A = {A};
end
end
function add_bookmark(fname, bookmark_text)
% Adds a bookmark to the temporary EPS file after %%EndPageSetup
% Read in the file
fh = fopen(fname, 'r');
if fh == -1
error('File %s not found.', fname);
end
try
fstrm = fread(fh, '*char')';
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
% Include standard pdfmark prolog to maximize compatibility
fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
% Add page bookmark
fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
error('Unable to open %s for writing.', fname);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
function set_tick_mode(Hlims, ax)
% Set the tick mode of linear axes to manual
% Leave log axes alone as these are tricky
M = get(Hlims, [ax 'Scale']);
if ~iscell(M)
M = {M};
end
M = cellfun(@(c) strcmp(c, 'linear'), M);
set(Hlims(M), [ax 'TickMode'], 'manual');
end
|
github
|
thomaskuestner/CNNArt-master
|
ghostscript.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/ghostscript.m
| 5,009 |
utf_8
|
e93de4034ac6e4ac154729dc2c12f725
|
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2013
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Nathan Childress for the fix to the default location on 64-bit
% Windows systems.
% 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 4/5/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
function varargout = ghostscript(cmd)
% Initialize any required system calls before calling ghostscript
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Call ghostscript
[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while 1
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep];
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'));
return
end
end
function good = check_gs_path(path_)
% Check the path is valid
shell_cmd = '';
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
good = good == 0;
end
|
github
|
thomaskuestner/CNNArt-master
|
fix_lines.m
|
.m
|
CNNArt-master/matlab/utils/export_fig/fix_lines.m
| 5,759 |
utf_8
|
3338572f35c4669b79cc3265892d35de
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
function fstrm = fix_lines(fstrm, fname2)
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Isolate line style definition section
first_sec = strfind(fstrm, '% line types:');
[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
[remaining, remaining] = strtok(remaining, '%');
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
thomaskuestner/CNNArt-master
|
fReadDICOM.m
|
.m
|
CNNArt-master/matlab/io/fReadDICOM.m
| 8,286 |
utf_8
|
f42fb2403d27a894219274abc728ca3e
|
function [dImg, SInfo, SCoord] = fReadDICOM(sFolder)
% read in DICOM files
%
% (c) Christian Wuerslin, Thomas Kuestner, 2011
% ---------------------------------------------------------------------
% iMAXSIZE = 256;
if ispc, sS='\'; else sS='/'; end;
if ~nargin, sFolder = cd; end
SFolder = dir(sFolder);
SFiles = SFolder(~[SFolder.isdir]);
% Try to find first readable DICOM file and use as reference
SFirstTag = [];
iInd = 1;
while isempty(SFirstTag) && iInd <= length(SFiles)
try
SFirstTag = dicominfo([sFolder, sS, SFiles(iInd).name]);
catch
iInd = iInd + 1;
end
end
if isempty(SFirstTag)
return
end
if(usejava('jvm') && ~feature('ShowFigureWindows'))
flagDisp = false;
else
flagDisp = true;
end
flagDisp = false; % force UI off
% Try to read the remaining files in the dir
if(isfield(SFirstTag,'ProtocolName') && strcmp(SFirstTag.ProtocolName,'FastView'))
dImg = cell(1,3);
SInfo = dImg; SCoord = dImg;
cOrient = cell(1,3);
fprintf(1, 'Parsing FastView images');
for iPre = iInd:length(SFiles)
sThisTag = dicominfo([sFolder, sS, SFiles(iPre).name]);
[~,dOrient] = min(sum(abs(reshape(sThisTag.ImageOrientationPatient, [3, 2])')));
switch dOrient
case 1 % sag
cOrient{1} = [cOrient{1}, iPre];
case 2 % cor
cOrient{2} = [cOrient{2}, iPre];
case 3 % tra
cOrient{3} = [cOrient{3}, iPre];
end
if(mod(iPre,10) == 0), fprintf('.'); end;
end
fprintf('\n');
for iJ=1:3
[dImg{iJ}, SInfo{iJ}, SCoord{iJ}] = fReadDICOMSingleOrient(SFiles(cOrient{iJ}), 1);
end
else
[dImg, SInfo, SCoord] = fReadDICOMSingleOrient(SFiles, iInd);
end
function [dImg, SInfo, SCoord] = fReadDICOMSingleOrient(SFiles, iInd)
iNDicom = 0;
SFirstTag = dicominfo([sFolder, sS, SFiles(1).name]);
dImg = zeros(SFirstTag.Height, SFirstTag.Width, length(SFiles) - iInd + 1);
if(flagDisp), hWait = showWaitbar('Loading DICOM images', 0); end;
for iI = iInd:length(SFiles)
try
% Try to read the Dicom information.
SThisTag = dicominfo([sFolder, sS, SFiles(iI).name]);
[dThisImg, iThisBinHdr] = fDicomReadFast([sFolder, sS, SFiles(iI).name], SThisTag.Height, SThisTag.Width);
dThisImg = double(dThisImg);
% if ~fTestImageCompatibility(SThisTag, SFirstTag), continue; end
iNDicom = iNDicom + 1;
if isfield(SThisTag, 'RescaleIntercept')
dThisImg = dThisImg - SThisTag.RescaleIntercept;
end
if isfield(SThisTag, 'RescaleSlope')
dThisImg = dThisImg.*SThisTag.RescaleSlope;
end
dImg(:, :, iNDicom) = dThisImg;
SInfo(iNDicom).STag = SThisTag;
SInfo(iNDicom).sFilename = SFiles(iI).name;
SInfo(iNDicom).iBinHdr = iThisBinHdr;
catch
end
if(flagDisp), hWait = showWaitbar('Loading DICOM images', iI/length(SFiles), hWait); end;
end
if(flagDisp), showWaitbar('Loading DICOM images', 'Close', hWait); end;
% Crop Images
dImg = dImg(:, :, 1:iNDicom);
% Sort images according to acquisition time
dTime = zeros(iNDicom, 1);
for iI = 1:length(dTime)
iHour = str2double(SInfo(iI).STag.AcquisitionTime(1:2));
iMin = str2double(SInfo(iI).STag.AcquisitionTime(3:4));
iSek = str2double(SInfo(iI).STag.AcquisitionTime(5:end));
dTime(iI) = iSek + 60*iMin + 3600*iHour;
end
[temp, iInd] = sort(dTime);
dImg = dImg(:,:,iInd);
SInfo = SInfo(iInd);
% Orientation
dOrient = reshape(SInfo(1).STag.ImageOrientationPatient, [3, 2])';
dPixelSpacing = SInfo(1).STag.PixelSpacing;
dPosition = zeros(length(SInfo), 3);
for iI = 1:length(SInfo)
dPosition(iI, :) = SInfo(iI).STag.ImagePositionPatient';
end
dOrientIndicator = sum(abs(dOrient));
[dVal, iInd] = min(dOrientIndicator);
switch(iInd)
case 1
SCoord.sOrientation = 'Sag';
SCoord.dLR = dPosition(:, 1);
SCoord.dAP = (dPosition(1, 2) + dOrient(1, 2).*(0:size(dImg, 2) - 1).*dPixelSpacing(1))';
[dTmp, ~, iInd] = unique(dPosition(:, 3)); % continous table movement
if(length(dTmp) == 1)
SCoord.dFH = (dPosition(1, 3) + dOrient(2, 3).*(0:size(dImg, 1) - 1).*dPixelSpacing(2))';
else % FH coordinates for each image seperately
SCoord.dFH = (repmat(dTmp,[1 size(dImg, 1)]) + repmat(dOrient(2, 3).*(0:size(dImg, 1) - 1).*dPixelSpacing(2),[length(dTmp) 1]))';
SCoord.TimCT = iInd;
end
case 2
SCoord.sOrientation = 'Cor';
SCoord.dLR = (dPosition(1, 1) + dOrient(1, 1).*(0:size(dImg, 2) - 1).*dPixelSpacing(1))';
SCoord.dAP = dPosition(:, 2);
[dTmp, ~, iInd] = unique(dPosition(:, 3)); % continous table movement
if(length(dTmp) == 1)
SCoord.dFH = (dPosition(1, 3) + dOrient(2, 3).*(0:size(dImg, 1) - 1).*dPixelSpacing(2))';
else % FH coordinates for each image seperately
SCoord.dFH = (repmat(dTmp,[1 size(dImg, 1)]) + repmat(dOrient(2, 3).*(0:size(dImg, 1) - 1).*dPixelSpacing(2),[length(dTmp) 1]))';
SCoord.TimCT = iInd;
end
case 3
SCoord.sOrientation = 'Tra';
SCoord.dLR = (dPosition(1, 1) + dOrient(1, 1).*(0:size(dImg, 2) - 1).*dPixelSpacing(1))';
SCoord.dAP = (dPosition(1, 2) + dOrient(2, 2).*(0:size(dImg, 1) - 1).*dPixelSpacing(2))';
SCoord.dFH = dPosition(:, 3);
% if SCoord.dFH(2) -SCoord.dFH(1) < 1
% dImg = flipdim(dImg, 3);
% SCoord.dFH = SCoord.dFH(end:-1:1);
% end
if(isfield(SThisTag,'ProtocolName') && ~strcmp(SThisTag.ProtocolName,'FastView'))
[temp, iInd] = sort(SCoord.dFH, 'ascend');
SCoord.dFH = SCoord.dFH(iInd);
dImg = dImg(:,:,iInd);
SInfo = SInfo(iInd);
end
end
fprintf(1, '\nNumber of matching DICOM images in folder : %u\n', iNDicom);
fprintf(1, ' Number of other files in folder : %u\n', length(SFiles) - iNDicom);
fprintf(1, ' Image Modality : %s\n', SInfo(1).STag.Modality);
fprintf(1, ' Image Orientation : %s\n', SCoord.sOrientation);
fprintf(1, ' Image Resolution : %u x %u\n\n', size(dImg, 2), size(dImg, 1));
fprintf(1, ' range metric FOV center of FOV\n');
fprintf(1, 'LR %-3.2f mm .. %-3.2f mm %-3.2f mm %-3.2f mm\n', min(SCoord.dLR), max(SCoord.dLR), max(SCoord.dLR) - min(SCoord.dLR), (max(SCoord.dLR) + min(SCoord.dLR))/2);
fprintf(1, 'AP %-3.2f mm .. %-3.2f mm %-3.2f mm %-3.2f mm\n', min(SCoord.dAP), max(SCoord.dAP), max(SCoord.dAP) - min(SCoord.dAP), (max(SCoord.dAP) + min(SCoord.dAP))/2);
fprintf(1, 'FH %-3.2f mm .. %-3.2f mm %-3.2f mm %-3.2f mm\n', min(SCoord.dFH), max(SCoord.dFH), max(SCoord.dFH) - min(SCoord.dFH), (max(SCoord.dFH) + min(SCoord.dFH))/2);
end
function lMatch = fTestImageCompatibility(STag, SRefTag)
lMatch = false;
% csTagsToCheck = {'FrameOfReferenceUID', 'PixelSpacing', 'ImageOrientationPatient', 'Modality', 'Width', 'Height'};
csTagsToCheck = {'PixelSpacing', 'Modality', 'Width', 'Height'};
for iI = 1:length(csTagsToCheck)
eval(['rVar = STag.', csTagsToCheck{iI}, ';']);
eval(['rVarRef = SRefTag.', csTagsToCheck{iI}, ';']);
if isnumeric(rVar)
if any(rVar ~= rVarRef)
fprintf(1, ['*** ', csTagsToCheck{iI}, ' ***\n']);
return;
end
elseif islogical(rVar)
if any(rVar ~= rVarRef)
fprintf(1, ['*** ', csTagsToCheck{iI}, ' ***\n']);
return;
end
else
if ~strcmp(rVar, rVarRef)
fprintf(1, ['*** ', csTagsToCheck{iI}, ' ***\n']);
return;
end
end
end
lMatch = true;
end
function hWait = showWaitbar(sMessage, dValue, hWait)
if(exist('multiWaitbar','file'))
multiWaitbar(sMessage, dValue);
hWait = 0;
else
if(nargin < 3)
hWait = waitbar(dValue, sMessage);
else
if(isnumeric(dValue))
waitbar(dValue, hWait);
else % close waitbar
close(hWait);
end
end
end
end
end
|
github
|
thomaskuestner/CNNArt-master
|
fPatchOverlay.m
|
.m
|
CNNArt-master/matlab/deepvis/fPatchOverlay.m
| 4,179 |
utf_8
|
9bc1e1c7e4769b84666acb79855b317d
|
function hfig = fPatchOverlay( dImg, dPatch, iScale, dAlpha, sPathOut, cPlotLimits, lLabel, lGray)
%FPATCHOVERLAY overlay figure
if(nargin < 8)
lGray = false;
end
if(nargin < 7)
lLabel = true;
end
if(nargin < 6)
xLimits = [1 size(dImg,2)];
yLimits = [1 size(dImg,1)];
else
xLimits = cPlotLimits{1};
yLimits = cPlotLimits{2};
end
if(nargin < 5)
sPathOut = cd;
end
if(nargin < 4)
dAlpha = 0.6;
end
if(nargin < 3)
iScale = [0 1; 0 1];
end
h.sPathOut = sPathOut;
h.dAlpha = dAlpha;
h.lGray = lGray;
h.colRange = iScale;
hfig = figure;
dImg = ((dImg - min(dImg(:))).*(h.colRange(1,2)-h.colRange(1,1)))./(max(dImg(:) - min(dImg(:))));
if(h.lGray)
alpha = bsxfun(@times, ones(size(dPatch,1), size(dPatch,2)), .6);
% find a scale dynamically with some limit
Foreground_min = min( min(dPatch(:)), h.colRange(1) );
Foreground_max = max( max(dPatch(:)), h.colRange(2) );
Background_blending = bsxfun(@times, dImg, bsxfun(@minus,1,alpha));
Foreground_blending = bsxfun( @times, bsxfun( @rdivide, ...
bsxfun(@minus, dPatch, Foreground_min), ...
Foreground_max-Foreground_min ), alpha );
h.dImg = Background_blending + Foreground_blending;
h.hI = imshow(h.dImg(:,:,1), h.colRange);
else
h.hI = axes();
h.dImg = dImg;
h.dPatch = dPatch;
[h.hFront,h.hBack] = imoverlay(dImg(:,:,1,1),dPatch(:,:,1,1),h.colRange(1,:),h.colRange(2,:),'jet',h.dAlpha, h.hI);
end
xlim(xLimits);
ylim(yLimits);
h.hA = gca;
h.iActive = 1;
if(lLabel)
% h.hT = uicontrol('Style','text', 'units','normalized', 'Position', [0.925 0.975 0.075 0.0255],'String',sprintf('I: [%.2f:%.2f]', h.colRange(1), h.colRange(2)),'ForegroundColor','k','Backgroundcolor','w');
h.hT = uicontrol('Style','text', 'units','normalized', 'Position', [0.925 0.975 0.075 0.0255],'String',sprintf('%02d/%02d', h.iActive, size(h.dImg,3)),'ForegroundColor','k','Backgroundcolor','w');
end
h.lLabel = lLabel;
set(h.hA, 'Position', [0 0 1 1]);
set(hfig, 'Position', [0 0 size(dImg, 2).*4 size(dImg, 1).*4]);
set(hfig, 'WindowScrollWheelFcn', @fScroll);
set(hfig, 'KeyPressFcn' , @fKeyPressFcn);
currpath = fileparts(mfilename('fullpath'));
addpath(genpath([fileparts(fileparts(currpath)),filesep,'export_fig']));
% set(hfig, 'WindowButtonDownFcn', @fWindowButtonDownFcn);
% set(hfig, 'WindowButtonMotionFcn', @fWindowButtonMotionFcn);
% set(hfig, 'WindowButtonUpFcn', @fWindowButtonUpFcn);
movegui('center');
hold on
guidata(hfig, h);
end
function fScroll(hObject, eventdata, handles)
h = guidata(hObject);
if eventdata.VerticalScrollCount < 0
h.iActive = max([1 h.iActive - 1]);
else
h.iActive = min([size(h.dImg, 3) h.iActive + 1]);
end
if(h.lGray)
set(h.hI, 'CData', h.dImg(:,:,h.iActive));
else
[h.hFront,h.hBack] = imoverlay(h.dImg(:,:,h.iActive,1),h.dPatch(:,:,h.iActive,1),h.colRange(1,:),h.colRange(2,:),'jet',h.dAlpha, h.hI);
end
set(h.hT, 'String', sprintf('%02d/%02d', h.iActive, size(h.dImg,3)));
guidata(hObject, h);
end
function fKeyPressFcn(hObject, eventdata)
if(strcmpi(eventdata.Key,'p'))
h = guidata(hObject);
set(h.hT, 'Visible', 'off');
if(~exist(h.sPathOut,'dir'))
mkdir(h.sPathOut);
end
sFiles = dir(h.sPathOut);
iFound = cellfun(@(x) ~isempty(x), regexp({sFiles(:).name},[num2str(h.iActive,'%03d')]));
if(any(iFound))
sFile = [num2str(h.iActive,'%03d'),'_',nnz(iFound)];
else
sFile = num2str(h.iActive,'%03d');
end
% iFile = nnz(~cell2mat({sFiles(:).isdir})) + 1;
% sFile = num2str(iFile);
try
export_fig([h.sPathOut,filesep,sFile,'.tif']);
catch
warning('export_fig() not on path');
end
set(h.hT, 'Visible', 'on');
end
guidata(hObject, h);
end
|
github
|
AMGoldsborough/tSDRG_PBC-master
|
PBC_pos.m
|
.m
|
tSDRG_PBC-master/PBC_pos.m
| 149 |
utf_8
|
cfa59d5fd986e812e7f18499790643a4
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = PBC_pos(x,L)
%gives position with PBCs
x = mod(x-1,L)+1;
end
|
github
|
jsjolund/sailoraid-master
|
serialRead.m
|
.m
|
sailoraid-master/Utilities/matlab/serialRead.m
| 3,280 |
utf_8
|
c5128330d2222fc30a7bed8ecebfb4f5
|
%% Start listening to sensor data
function serialRead(serialPort,callback)
if exist('s', 'var')
try
fclose(s);
catch
end
delete(s);
clear s;
end
% Supported baud rates 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200,
% 38400, 57600, 115200, 230400, 460800, 921600
s = serial(serialPort);
if (s.Status == 'closed')
s.BaudRate = 230400;
s.ReadAsyncMode = 'continuous';
s.InputBufferSize = 1024;
s.ByteOrder = 'littleEndian';
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 31*4;
s.Timeout = 2;
% Open the serial connection
fprintf('Opening connection...\n')
fprintf('Press Ctrl+C to stop recording.\n')
fprintf('Recording.');
fopen(s);
% Start the sensor value stream
fprintf(s,sprintf('\r\n\r\n\r\nmatlab\r\n'));
tic();
set(s,'BytesAvailableFcn',{@serialReceive,callback});
% Read
pause(1);
% Close the serial connection
fprintf('Closing connection...\n')
fclose(s);
delete(s);
clear s;
end
end
%% Read the serial stream
function serialReceive(obj,~,callback)
% Read data as float array
[data,~] = fread(obj, 31*4, 'float32');
% If last float is not NaN, we need to sync the stream
if ~isnan(data(31))
fprintf('\nSynchronizing...\n');
ffCnt = 0;
while 1
[data,~] = fread(obj, 1, 'uint8');
if data(1) == 255
ffCnt = ffCnt+1;
else
ffCnt = 0;
end
if ffCnt == 4
break;
end
end
fprintf('Recording.');
return;
end
% Store sensor values in struct with fields
sensor.imu.ax = data(1);
sensor.imu.ay = data(2);
sensor.imu.az = data(3);
sensor.imu.gx = data(4);
sensor.imu.gy = data(5);
sensor.imu.gz = data(6);
sensor.imu.mx = data(7);
sensor.imu.my = data(8);
sensor.imu.mz = data(9);
sensor.imu.roll = data(10);
sensor.imu.pitch = data(11);
sensor.imu.yaw = data(12);
sensor.env.humidity = data(13);
sensor.env.pressure = data(14);
sensor.env.temperature = data(15);
sensor.gps.time.year = ftoi(data(16));
sensor.gps.time.month = ftoi(data(17));
sensor.gps.time.day = ftoi(data(18));
sensor.gps.time.hour = ftoi(data(19));
sensor.gps.time.min = ftoi(data(20));
sensor.gps.time.sec = ftoi(data(21));
sensor.gps.time.hsec = ftoi(data(22));
sensor.gps.pos.latitude = data(23);
sensor.gps.pos.longitude = data(24);
sensor.gps.pos.elevation = data(25);
sensor.gps.pos.speed = data(26);
sensor.gps.pos.direction = data(27);
sensor.gps.info.satUse = ftoi(data(28));
sensor.gps.info.satView = ftoi(data(29));
sensor.range.range0 = data(30);
% Add a timestamp
sensor.sys.dateTime = now;
% Store time in milliseconds since last update
sensor.sys.deltaTime = toc()*1000;
tic();
% Absolute time in ms
global absTime
if isempty(absTime)
absTime = 0;
end
absTime = absTime + sensor.sys.deltaTime;
sensor.sys.absTime = absTime;
% User callback
callback(sensor);
end
%% Cast 32 bit floating point to 32 bit integer
function i = ftoi(f)
i = typecast(single(f),'int32');
end
|
github
|
jsjolund/sailoraid-master
|
main.m
|
.m
|
sailoraid-master/Utilities/matlab/main.m
| 1,656 |
utf_8
|
17a84b2c220b6a508d528876ff8e2695
|
%% Script which logs sensor values from serial port and can plot real-time
% Press Ctrl+C in the Command Window to stop reading and recording.
clear -global;
clear;
%serialPort = 'COM1'; % Windows
serialPort = '/dev/ttyACM0'; % Linux
% Can be removed for faster logging
% realTimePlot();
% Start reading from serial
serialRead(serialPort, @sensorUpdateCallback);
% Plot from sensor log after serial read stopped
global sensorLog
% imuLog = [sensorLog.imu];
% timeLog = [sensorLog.sys];
% plot([timeLog.absTime],[imuLog.az])
fprintf('Program terminated.\n');
%% This callback is run when sensor values are updated
function sensorUpdateCallback(sensor)
global hp sensorLog
sensorLog = [sensorLog, sensor];
if ishghandle(hp)
realTimePlotUpdate(sensor);
end
if mod(length(sensorLog), 25) == 0
fprintf('.');
end
end
%% Real time plot functions
% Create a figure to plot into
function realTimePlot()
global hp step
% Number of "sliding points" in your figure
nPointsInFigure = 300;
% X points spacing
step = 0.01;
% Prepare empty data for the plot
xVals = linspace(-(nPointsInFigure-1)*step, 0, nPointsInFigure);
yVals = NaN(nPointsInFigure, 1);
figure(1);
% Generate the plot (with empty data) it will be passed to the callback.
hp = plot(xVals , yVals);
ylim([-100 100]);
end
% Update the plot by circle shifting the values as needed
function realTimePlotUpdate(sensor)
plotVar = sensor.range.range0;
global hp step
xVals = get(hp,'XData');
yVals = get(hp,'YData');
yVals = circshift(yVals,-1);
yVals(end) = plotVar;
xVals = circshift(xVals,-1);
xVals(end) = xVals(end-1) + step;
set(hp, 'XData', xVals, 'YData', yVals);
drawnow limitrate
end
|
github
|
jsjolund/sailoraid-master
|
serialRead.m
|
.m
|
sailoraid-master/Kalman_Filter/Serial_Read/serialRead.m
| 2,808 |
utf_8
|
607933805d0c2b6a07459c8e7cd4a338
|
%% Start listening to sensor data
function serialRead(serialPort,callback)
if exist('s', 'var')
try
fclose(s);
catch
end
delete(s);
clear s;
end
s = serial(serialPort);
if (s.Status == 'closed')
s.BaudRate = 115200;
s.ReadAsyncMode = 'continuous';
s.InputBufferSize = 1024;
s.ByteOrder = 'littleEndian';
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 30*4;
set(s,'BytesAvailableFcn',{@serialReceive,callback})
s.Timeout = 2;
% Open the serial connection
fprintf('Opening connection...\n')
fopen(s);
pause(1);
% Start the sensor value stream
fprintf(s,sprintf('\r\n\r\n\r\nmatlab\r\n'));
pause(1);
% Close the serial connection
fprintf('Closing connection...\n')
fclose(s);
delete(s);
clear s;
end
end
%% Read the serial stream
function serialReceive(obj,~,callback)
% Read data as float array
[data,~] = fread(obj, 30*4, 'float32');
% If last float is not NaN, we need to sync the stream
if ~isnan(data(30))
fprintf('Synchronizing...\n');
nanCnt = 0;
while 1
[data,~] = fread(obj, 1, 'uint8');
if data(1) == 255
nanCnt = nanCnt+1;
else
nanCnt = 0;
end
if nanCnt == 4
break;
end
end
return;
end
% Store in struct with fields
sensor.imu.ax = data(1);
sensor.imu.ay = data(2);
sensor.imu.az = data(3);
sensor.imu.gx = data(4);
sensor.imu.gy = data(5);
sensor.imu.gz = data(6);
sensor.imu.mx = data(7);
sensor.imu.my = data(8);
sensor.imu.mz = data(9);
sensor.imu.roll = data(10);
sensor.imu.pitch = data(11);
sensor.imu.yaw = data(12);
sensor.env.humidity = data(13);
sensor.env.pressure = data(14);
sensor.env.temperature = data(15);
sensor.gps.time.year = typecast(single(data(16)),'int32');
sensor.gps.time.month = typecast(single(data(17)),'int32');
sensor.gps.time.day = typecast(single(data(18)),'int32');
sensor.gps.time.hour = typecast(single(data(19)),'int32');
sensor.gps.time.min = typecast(single(data(20)),'int32');
sensor.gps.time.sec = typecast(single(data(21)),'int32');
sensor.gps.time.hsec = typecast(single(data(22)),'int32');
sensor.gps.pos.latitude = data(23);
sensor.gps.pos.longitude = data(24);
sensor.gps.pos.elevation = data(25);
sensor.gps.pos.speed = data(26);
sensor.gps.pos.direction = data(27);
sensor.gps.info.satUse = typecast(single(data(28)),'int32');
sensor.gps.info.satView = typecast(single(data(29)),'int32');
% Add a timestamp
sensor.sys.dateTime = datevec(now);
try
% Store time in milliseconds since last update
sensor.sys.deltaTime = toc()*1000;
catch
sensor.sys.deltaTime = 0;
end
tic();
% User callback
callback(sensor);
end
|
github
|
jsjolund/sailoraid-master
|
main.m
|
.m
|
sailoraid-master/Kalman_Filter/Serial_Read/main.m
| 1,485 |
utf_8
|
50d87825b14a282b6b04225f526eb936
|
%% Script which logs sensor values from serial port and can plot real-time
clear -global;
clear;
serialPort = 'COM7'; % Windows
%serialPort = '/dev/ttyACM3'; % Linux
% realTimePlot();
% Start reading from serial
serialRead(serialPort, @sensorUpdateCallback);
% Plot from sensor log
global sensorLog
imu = [sensorLog.imu];
plot([sensorLog.timestamp],[imu.az])
fprintf('Program terminated.\n');
%% This callback is run when sensor values are updated
function sensorUpdateCallback(sensor)
global hp sensorLog
sensorLog = [sensorLog, sensor];
if ishghandle(hp)
realTimePlotUpdate(sensor);
end
end
%% Real time plot functions
% Create a figure to plot into
function realTimePlot()
global hp step
nPointsInFigure = 250; % Number of "sliding points" in your figure
step = 0.01; % X points spacing
xVals = linspace(-(nPointsInFigure-1)*step, 0, nPointsInFigure); % Prepare empty data for the plot
yVals = NaN(nPointsInFigure, 1);
figure(1);
hp = plot(xVals , yVals); % Generate the plot (with empty data) it will be passed to the callback.
ylim([-3 3]);
end
% Update the plot by circle shifting the values as needed
function realTimePlotUpdate(sensor)
global hp step
xVals = get(hp,'XData');
yVals = get(hp,'YData');
yVals = circshift(yVals,-1);
yVals(end) = sensor.imu.az; % Plot variable
xVals = circshift(xVals,-1);
xVals(end) = xVals(end-1) + step;
set(hp, 'XData', xVals, 'YData', yVals);
drawnow limitrate
end
|
github
|
Kazell/coloring-contours-of-objects-master
|
fig_n.m
|
.m
|
coloring-contours-of-objects-master/fig_n.m
| 3,150 |
utf_8
|
fb24e5717c1560f3bfecedccce8df1b2
|
function clea=fig_n(a)
%
%This function takes a picture a='name.extension' as an argument and returns a figure of external boundaries of objects
%placed on picture all colored differently (on the white background)if the background of the given picture is uniform
%and all objects don't touch the borders of the picture.
%
b=imread(a); %Function imread returns the matrix of three dimentions (number of pixels in length, number of pixels in hight, rgb - 3 numbers )
k=size(b); %gives the matrix=[length hight 3]
b1=b(1,1,:); %left upper corner, gives rgb combination for background
c=[]; %prepares an empty massive for matrix(length, hight) with 0 for background coordinates and 1 for objects' pixels
for i=1:1:k(1,1); %goes through raws from the first to the last
for j=1:1:k(1,2); %and columns
if b(i,j,:)==b1;
c(i,j)=0; %changes all background's rgb-vectors to 0
else
c(i,j)=1; % changes objects' rgb-vectors to 1
end
end
end
%starting from here prepares a massive l (<--it is small letter L) for object contours (not colored). Points of boundaries will be equal to 0,
%all the others to 1.
l=[];
l(size(c)(1,1),size(c)(1,2))=1; %violently makes right lower corner equal to 1, i.e.it is background.
l(1,size(c)(1,2))=1;% the same with right upper
l(size(c)(1,1),1)=1;%...and left lower
l(1,1)=1;% and left upper
for i=2:1:(size(c)(1,1)-1); %goes through raws
l(i,1)=1; %makes first raw to be a background
l(i,size(c)(1,2))=1; %and the last
for j=2:1:(size(c)(1,2)-1);%through columns
l(1,j)=1; %makes the first column to be a background
l(size(c)(1,1),j)=1; %and the last
if ((c(i,j)==0) && (c(i,j+1)==1)) || ((c(i,j)==0) && (c(i,j-1)==1)) || ((c(i,j)==0) && (c(i+1,j)==1)) || ((c(i,j)==0) && (c(i-1,j)==1));% if at least one of the
l(i,j)=0; %neighbor-pixels for 0-pixel of massive l (<--small L again) is 1 it stays 0 (as it was)
else
l(i,j)=1; %if not turns into 1
end
end
end % now we have all contours marked as 0 in matrix l
p=ones(size(l)(1,1),size(l)(1,2),3).*255; %creates massive to be transformed into picture with rgb-colors. At this step it is a white empty picture
p1=size(p)(1,1); %length of future picture
p2=size(p)(1,2);%its height
for i=2:1:(size(l)(1,1)-1); %goes through lines
for j=2:1:(size(l)(1,2)-1); % through columns
if l(i,j)==0; % point belongs to the objects' contour
d=[rand(max(p1,p2),max(p1,p2),255)(i,j) rand(max(p1,p2),max(p1,p2),255)(1,i) rand(max(p1,p2),max(p1,p2),255)(j,i)];%randomly chooses color
[l,p] = recurpix (l,p,d,i,j); %%% calls a function (with full description in file named recurpix.m)
end
end
end
clea = imshow(p); %returns a picture of an object
end
|
github
|
gunpowder78/CMU-Perceptual-Computing-Lab-openpose-master
|
classification_demo.m
|
.m
|
CMU-Perceptual-Computing-Lab-openpose-master/3rdparty/caffe/matlab/demo/classification_demo.m
| 5,466 |
utf_8
|
45745fb7cfe37ef723c307dfa06f1b97
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
lifeng9472/IBCCF-master
|
tracker.m
|
.m
|
IBCCF-master/tracker.m
| 8,795 |
utf_8
|
12e1cf165656dd49d0a525d7b49f7501
|
% Tracker: Integrating Boundary and Center Correlation Filters for Visual Tracking with
% Aspect Ratio Variation
%
% Input:
% - img_files: list of image names
% - pos: intialized center position of the target in (row, col)
% - init_target_sz: intialized target size in (Height, Width)
% Output:
% - results: return the tracking results and fps
%
function results = tracker(img_files, pos, init_target_sz)
% ================================================================================
% Environment setting
% ================================================================================
% read the default parameters from file
opts = [];
opts = init_params(opts);
% Get the CNN layers for both CCF and BCFs
indLayers = opts.indLayers ;
indLayers_border = opts.indLayers_border;
% Initialize the parameters of CCF
padding = opts.padding;
cell_size = opts.cell_size;
% Initialize the parameters of BCFs
decay_ratio = opts.decay_ratio;
cell_size_border = opts.cell_size_border;
% Get the range of target scale changes during tracking
min_scale_factor = opts.min_scale_factor;
max_scale_factor = opts.max_scale_factor;
% Other parameters
output_sigma_factor = opts.output_sigma_factor;
show_visualization = opts.show_visualization;
video_path = [];
% Get the number of layers for CCF
numLayers = length(indLayers);
numLayers_border = length(indLayers_border);
% Get image size and search window size for CCF
im_sz = size(imread([video_path img_files{1}]));
[searching_sz, padding_strategy] = get_search_window(init_target_sz, im_sz, padding, -1);
% Get the padding method and search window size for BCFs
padding_border = get_border_padding(init_target_sz, im_sz);
searching_sz_horz = floor(init_target_sz .* [padding_border.secondary, padding_border.primary_horz]);
searching_sz_vert = floor(init_target_sz .* [padding_border.primary_vert, padding_border.secondary]);
opts.padding_border = padding_border;
% Compute the sigma for the Gaussian function label
output_sigma = sqrt(prod(init_target_sz)) * output_sigma_factor / cell_size;
output_sigma_horz = searching_sz_horz(2) * output_sigma_factor / cell_size_border;
output_sigma_vert = searching_sz_vert(1) * output_sigma_factor / cell_size_border;
% Compute the desired filter sizes
feature_sz = floor(searching_sz / cell_size);
feature_sz_horz = floor(searching_sz_horz / cell_size_border);
feature_sz_vert = floor(searching_sz_vert / cell_size_border);
% Compute the Fourier Transform of the Gaussian function label
yf = fft2(gaussian_shaped_labels(output_sigma, feature_sz,'center'));
yf_horz = fft(gaussian_shaped_labels(output_sigma_horz, feature_sz_horz(2),'horz'))';
yf_vert = fft(gaussian_shaped_labels(output_sigma_vert, feature_sz_vert(1),'vert'));
% Compute the cosine window (for avoiding boundary discontinuity)
cos_window = hann(size(yf,1)) * hann(size(yf,2))';
cos_window_horz = hann(size(yf_horz, 2))';
cos_window_vert = hann(size(yf_vert, 1));
% Clip the boundary cosine windows to suppress the effects of context
% region
cos_window_horz(1:floor(size(yf_horz,2) / 2)) = cos_window_horz(1:floor(size(yf_horz, 2) / 2)) * decay_ratio;
cos_window_vert(1:floor(size(yf_vert,1) / 2)) = cos_window_vert(1:floor(size(yf_vert, 1) / 2)) * decay_ratio;
% Create video interface for visualization
if(show_visualization)
update_visualization = show_video(img_files, video_path);
end
% Initialize the variables
positions = zeros(numel(img_files), 4);
boundary_positions = zeros(numel(img_files), 4);
boundary_positions(1,:) = get_boundary_position(pos, init_target_sz);
% Initialize the processing orders of the boundary features
opts.reshape_mode = [{'horz'},{'horz'},{'vert'},{'vert'}];
opts.feat_size_border = [{feature_sz_horz},{feature_sz_horz},{feature_sz_vert},{feature_sz_vert}];
opts.cos_window_border = [{cos_window_horz},{cos_window_horz(end:-1:1)},{cos_window_vert},{cos_window_vert(end:-1:1)}];
opts.yf_border = [{yf_horz},{yf_horz},{yf_vert},{yf_vert}];
% Note: variables ending with 'f' are in the Fourier domain.
[model_xf, model_alphaf] = deal(cell(numLayers, 1));
[model_xf_border, model_alphaf_border] = deal(cell(numLayers_border, 4));
% Initialize the target position, size and time
cur_pos = pos;
cur_target_sz = init_target_sz;
time = 0;
% ================================================================================
% Start tracking
% ================================================================================
for frame = 1:numel(img_files)
opts.frame = frame;
im = imread([video_path img_files{frame}]); % Load the image at the current frame
if ismatrix(im)
im = cat(3, im, im, im);
end
tic();
% ================================================================================
% Predict the object position from the learned CFs
% ================================================================================
if frame > 1
% Estimate the intial positions of the target with the center CF
% Extract the deep features
feat = extract_features_CCF(im, cur_pos, searching_sz, cos_window, opts);
% Predict the initial position in current frame
[cur_pos, confidence_CCF] = predict_position_CCF(feat, cur_pos, feature_sz, model_xf, model_alphaf, cur_target_sz ./ init_target_sz ,opts);
% Compute the initial positions for four boundaries in current frame
boundary_positions(frame,:) = get_boundary_position(cur_pos, cur_target_sz);
% Extract deep features for 1D boundary trackers
feat_border = extract_features_BCFs(im, cur_pos, cur_target_sz, opts);
% Refine the boundary positions with 1D boundary trackers
delta_border = predict_position_BCFs(feat_border, model_xf_border, model_alphaf_border, opts);
boundary_positions(frame, :) = boundary_positions(frame, :) + delta_border;
% Clamp the boundaries
boundary_positions(frame, :) = clamp_region(boundary_positions(frame, :), size(im));
old_pos = cur_pos;
old_target_sz = cur_target_sz;
cur_pos = [(boundary_positions(frame, 3) + boundary_positions(frame, 4)), (boundary_positions(frame, 1) + boundary_positions(frame, 2)) ] / 2;
cur_target_sz = [(boundary_positions(frame, 4) - boundary_positions(frame, 3) + mod(cur_target_sz(1),2)),...
(boundary_positions(frame, 2) - boundary_positions(frame, 1) + mod(cur_target_sz(2),2))];
% Clamp the target size
cur_target_sz = clamp_target_sz(cur_target_sz, init_target_sz, min_scale_factor, max_scale_factor);
% Compare the tracking results between CCF and BCFs
searching_sz = get_search_window(cur_target_sz, im_sz, padding, padding_strategy);
feat = extract_features_CCF(im, cur_pos, searching_sz, cos_window, opts);
[~, confidence_BCFs] = predict_position_CCF(feat, cur_pos, feature_sz, model_xf, model_alphaf, cur_target_sz ./ init_target_sz, opts);
if(confidence_BCFs < confidence_CCF)
cur_target_sz = old_target_sz;
cur_pos = old_pos;
end
% Clamp the target size again
cur_target_sz = clamp_target_sz(cur_target_sz, init_target_sz, min_scale_factor, max_scale_factor);
end
% ================================================================================
% Update the CF models with Alternating Direction Method of Multipliers (ADMM)
% ================================================================================
searching_sz = get_search_window(cur_target_sz, im_sz, padding, padding_strategy);
feat = extract_features_CCF(im, cur_pos, searching_sz, cos_window, opts);
feat_border = extract_features_BCFs(im, cur_pos, cur_target_sz, opts);
[model_xf, model_xf_border, model_alphaf, model_alphaf_border] = update_model(feat, feat_border,...
yf, model_xf, model_xf_border, model_alphaf, model_alphaf_border, init_target_sz, opts);
% ================================================================================
% Save predicted position and time
% ================================================================================
positions(frame,:) = [cur_pos([2,1]) - cur_target_sz([2,1])/2, cur_target_sz([2,1])];
time = time + toc();
% Visualization
if show_visualization,
box = [cur_pos([2,1]) - cur_target_sz([2,1])/2, cur_target_sz([2,1])];
stop = update_visualization(frame, box);
if stop, break, end %user pressed Esc, stop early
drawnow
end
end
results.type = 'rect';
results.res = positions;
results.fps = numel(img_files) / time;
end
|
github
|
lifeng9472/IBCCF-master
|
test_examples.m
|
.m
|
IBCCF-master/external_libs/matconvnet/utils/test_examples.m
| 1,591 |
utf_8
|
16831be7382a9343beff5cc3fe301e51
|
function test_examples()
%TEST_EXAMPLES Test some of the examples in the `examples/` directory
addpath examples/mnist ;
addpath examples/cifar ;
trainOpts.gpus = [] ;
trainOpts.continue = true ;
num = 1 ;
exps = {} ;
for networkType = {'dagnn', 'simplenn'}
for index = 1:4
clear ex ;
ex.trainOpts = trainOpts ;
ex.networkType = char(networkType) ;
ex.index = index ;
exps{end+1} = ex ;
end
end
if num > 1
if isempty(gcp('nocreate')),
parpool('local',num) ;
end
parfor e = 1:numel(exps)
test_one(exps{e}) ;
end
else
for e = 1:numel(exps)
test_one(exps{e}) ;
end
end
% ------------------------------------------------------------------------
function test_one(ex)
% -------------------------------------------------------------------------
suffix = ['-' ex.networkType] ;
switch ex.index
case 1
cnn_mnist(...
'expDir', ['data/test-mnist' suffix], ...
'batchNormalization', false, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 2
cnn_mnist(...
'expDir', ['data/test-mnist-bnorm' suffix], ...
'batchNormalization', true, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 3
cnn_cifar(...
'expDir', ['data/test-cifar-lenet' suffix], ...
'modelType', 'lenet', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 4
cnn_cifar(...
'expDir', ['data/test-cifar-nin' suffix], ...
'modelType', 'nin', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
end
|
github
|
lifeng9472/IBCCF-master
|
simplenn_caffe_compare.m
|
.m
|
IBCCF-master/external_libs/matconvnet/utils/simplenn_caffe_compare.m
| 5,638 |
utf_8
|
8e9862ffbf247836e6ff7579d1e6dc85
|
function diffStats = simplenn_caffe_compare( net, caffeModelBaseName, testData, varargin)
% SIMPLENN_CAFFE_COMPARE compare the simplenn network and caffe models
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME) Evaluates a forward
% pass of a simplenn network NET and caffe models stored in
% CAFFE_BASE_MODELNAME and numerically compares the network outputs using
% a random input data.
%
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME, TEST_DATA) Evaluates
% the simplenn network and Caffe model on a given data. If TEST_DATA is
% an empty array, uses a random input.
%
% RES = SIMPLENN_CAFFE_COMPARE(...) returns a structure with the
% statistics of the differences where each field of a structure RES is
% named after a blob and contains basic statistics:
% `[MIN_DIFF, MEAN_DIFF, MAX_DIFF]`
%
% This script attempts to match the NET layer names and caffe blob names
% and shows the MIN, MEAN and MAX difference between the outputs. For
% caffe model, the mean image stored with the caffe model is used (see
% `simplenn_caffe_deploy` for details). Furthermore the script compares
% the execution time of both networks.
%
% Compiled MatCaffe (usually located in `<caffe_dir>/matlab`, built
% with the `matcaffe` target) must be in path.
%
% SIMPLENN_CAFFE_COMPARE(..., 'OPT', VAL, ...) takes the following
% options:
%
% `numRepetitions`:: `1`
% Evaluate the network multiple times. Useful to compare the execution
% time.
%
% `device`:: `cpu`
% Evaluate the network on the specified device (CPU or GPU). For GPU
% evaluation, the current GPU is used for both Caffe and simplenn.
%
% `silent`:: `false`
% When true, supress all outputs to stdin.
%
% See Also: simplenn_caffe_deploy
% Copyright (C) 2016 Karel Lenc, Zohar Bar-Yehuda
% 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).
opts.numRepetitions = 1;
opts.randScale = 100;
opts.device = 'cpu';
opts.silent = false;
opts = vl_argparse(opts, varargin);
info = @(varargin) fprintf(1, varargin{:});
if opts.silent, info = @(varargin) []; end;
if ~exist('caffe.Net', 'class'), error('MatCaffe not in path.'); end
prototxtFilename = [caffeModelBaseName '.prototxt'];
if ~exist(prototxtFilename, 'file')
error('Caffe net definition `%s` not found', prototxtFilename);
end;
modelFilename = [caffeModelBaseName '.caffemodel'];
if ~exist(prototxtFilename, 'file')
error('Caffe net model `%s` not found', modelFilename);
end;
meanFilename = [caffeModelBaseName, '_mean_image.binaryproto'];
net = vl_simplenn_tidy(net);
net = vl_simplenn_move(net, opts.device);
netBlobNames = [{'data'}, cellfun(@(l) l.name, net.layers, ...
'UniformOutput', false)];
% Load the Caffe model
caffeNet = caffe.Net(prototxtFilename, modelFilename, 'test');
switch opts.device
case 'cpu'
caffe.set_mode_cpu();
case 'gpu'
caffe.set_mode_gpu();
gpuDev = gpuDevice();
caffe.set_device(gpuDev.Index - 1);
end
caffeBlobNames = caffeNet.blob_names';
[caffeLayerFound, caffe2netres] = ismember(caffeBlobNames, netBlobNames);
info('Found %d matches between simplenn layers and caffe blob names.\n',...
sum(caffeLayerFound));
% If testData not supplied, use random input
imSize = net.meta.normalization.imageSize;
if ~exist('testData', 'var') || isempty(testData)
testData = rand(imSize, 'single') * opts.randScale;
end
if ischar(testData), testData = imread(testData); end
testDataSize = [size(testData), 1, 1];
assert(all(testDataSize(1:3) == imSize(1:3)), 'Invalid test data size.');
testData = single(testData);
dataCaffe = matlab_img_to_caffe(testData);
if isfield(net.meta.normalization, 'averageImage') && ...
~isempty(net.meta.normalization.averageImage)
avImage = net.meta.normalization.averageImage;
if numel(avImage) == imSize(3)
avImage = reshape(avImage, 1, 1, imSize(3));
end
testData = bsxfun(@minus, testData, avImage);
end
% Test MatConvNet model
stime = tic;
for rep = 1:opts.numRepetitions
res = vl_simplenn(net, testData, [], [], 'ConserveMemory', false);
end
info('MatConvNet %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
if ~isempty(meanFilename) && exist(meanFilename, 'file')
mean_img_caffe = caffe.io.read_mean(meanFilename);
dataCaffe = bsxfun(@minus, dataCaffe, mean_img_caffe);
end
% Test Caffe model
stime = tic;
for rep = 1:opts.numRepetitions
caffeNet.forward({dataCaffe});
end
info('Caffe %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
diffStats = struct();
for li = 1:numel(caffeBlobNames)
blob = caffeNet.blobs(caffeBlobNames{li});
caffeData = permute(blob.get_data(), [2, 1, 3, 4]);
if li == 1 && size(caffeData, 3) == 3
caffeData = caffeData(:, :, [3, 2, 1]);
end
mcnData = gather(res(caffe2netres(li)).x);
diff = abs(caffeData(:) - mcnData(:));
diffStats.(caffeBlobNames{li}) = [min(diff), mean(diff), max(diff)]';
end
if ~opts.silent
pp = '% 10s % 10s % 10s % 10s\n';
precp = '% 10.2e';
fprintf(pp, 'Layer name', 'Min', 'Mean', 'Max');
for li = 1:numel(caffeBlobNames)
lstats = diffStats.(caffeBlobNames{li});
fprintf(pp, caffeBlobNames{li}, sprintf(precp, lstats(1)), ...
sprintf(precp, lstats(2)), sprintf(precp, lstats(3)));
end
fprintf('\n');
end
end
function img = matlab_img_to_caffe(img)
img = single(img);
% Convert from HxWxCxN to WxHxCxN per Caffe's convention
img = permute(img, [2 1 3 4]);
if size(img,3) == 3
% Convert from RGB to BGR channel order per Caffe's convention
img = img(:,:, [3 2 1], :);
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_train_dag.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/cnn_train_dag.m
| 13,629 |
utf_8
|
73e1103b1f7118b23a1bc12237e953ed
|
function [net,stats] = cnn_train_dag(net, imdb, getBatch, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
% CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
% the DagNN wrapper instead of the SimpleNN wrapper.
% 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).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.derOutputs = {'objective', 1} ;
opts.extractStatsFn = @extractStats ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
if isempty(opts.derOutputs)
error('DEROUTPUTS must be specified when training.\n') ;
end
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(opts.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if opts.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
state.momentum = num2cell(zeros(1, numel(net.params))) ;
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net.move('gpu') ;
state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ;
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
net.setParameterServer(parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
num = 0 ;
epoch = params.epoch ;
subset = params.(mode) ;
adjustTime = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if strcmp(mode, 'train')
net.mode = 'normal' ;
net.accumulateParamDers = (s ~= 1) ;
net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;
else
net.mode = 'test' ;
net.eval(inputs) ;
end
end
% Accumulate gradient.
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
state = accumulateGradients(net, state, params, batchSize, parserv) ;
end
% Get statistics.
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats.num = num ;
stats.time = time ;
stats = params.extractStatsFn(stats,net) ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
state.momentum = cellfun(@gather, state.momentum, 'uniformoutput', false) ;
end
net.reset() ;
net.move('cpu') ;
% -------------------------------------------------------------------------
function state = accumulateGradients(net, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for p=1:numel(net.params)
if ~isempty(parserv)
parDer = parserv.pullWithIndex(p) ;
else
parDer = net.params(p).der ;
end
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate ;
net.params(p).value = vl_taccum(...
1 - thisLR, net.params(p).value, ...
(thisLR/batchSize/net.params(p).fanout), parDer) ;
case 'gradient'
thisDecay = params.weightDecay * net.params(p).weightDecay ;
thisLR = params.learningRate * net.params(p).learningRate ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.params(p).value) ;
% Update momentum.
state.momentum{p} = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
else
delta = state.momentum{p} ;
end
% Update parameters.
net.params(p).value = vl_taccum(...
1, net.params(p).value, thisLR, delta) ;
end
otherwise
error('Unknown training method ''%s'' for parameter ''%s''.', ...
net.params(p).trainMethod, ...
net.params(p).name) ;
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(stats, net)
% -------------------------------------------------------------------------
sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;
for i = 1:numel(sel)
stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net_, state)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = dagnn.DagNN.loadobj(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_train.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/cnn_train.m
| 19,153 |
utf_8
|
c6c0c0c8532f9c3653af4410497f80c3
|
function [net, stats] = cnn_train(net, imdb, getBatch, varargin)
%CNN_TRAIN An example implementation of SGD for training CNNs
% CNN_TRAIN() is an example learner implementing stochastic
% gradient descent with momentum to train a CNN. It can be used
% with different datasets and tasks by providing a suitable
% getBatch function.
%
% 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).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
for i = 1:numel(net.layers)
for j = 1:numel(net.layers{i}.weights)
state.momentum{i}{j} = 0 ;
end
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move(net, 'gpu') ;
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[im, labels] = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
res = vl_simplenn(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats = extractStats(net, params, error / num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
% collect diagnostic statistics
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ;
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ;
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gather(state.momentum{i}{j}) ;
end
end
end
net = vl_simplenn_move(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for l=numel(net.layers):-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
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, ...
parDer) ;
else
% Standard gradient training.
thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;
thisLR = params.learningRate * net.layers{l}.learningRate(j) ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.layers{l}.weights{j}) ;
% Update momentum.
state.momentum{l}{j} = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
else
delta = state.momentum{l}{j} ;
end
% Update parameters.
net.layers{l}.weights{j} = vl_taccum(...
1, net.layers{l}.weights{j}, ...
thisLR, delta) ;
end
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename) ;
clearMex() ;
if numGpus == 1
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_stn_cluttered_mnist.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/spatial_transformer/cnn_stn_cluttered_mnist.m
| 3,872 |
utf_8
|
3235801f70028cc27d54d15ec2964808
|
function [net, info] = cnn_stn_cluttered_mnist(varargin)
%CNN_STN_CLUTTERED_MNIST Demonstrates training a spatial transformer
% The spatial transformer network (STN) is trained on the
% cluttered MNIST dataset.
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.useSpatialTransformer = true ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataPath = fullfile(opts.dataDir,'cluttered-mnist.mat') ;
if opts.useSpatialTransformer
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-stn') ;
else
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-no-stn') ;
end
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.dataURL = 'http://www.vlfeat.org/matconvnet/download/data/cluttered-mnist.mat' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getImdDB(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net = cnn_stn_cluttered_mnist_init([60 60], true) ; % initialize the network
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
fbatch = @(i,b) getBatch(opts.train,i,b);
[net, info] = cnn_train_dag(net, imdb, fbatch, ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 2)) ;
% --------------------------------------------------------------------
% Show transformer
% --------------------------------------------------------------------
figure(100) ; clf ;
v = net.getVarIndex('xST') ;
net.vars(v).precious = true ;
net.eval({'input',imdb.images.data(:,:,:,1:6)}) ;
for t = 1:6
subplot(2,6,t) ; imagesc(imdb.images.data(:,:,:,t)) ; axis image off ;
subplot(2,6,6+t) ; imagesc(net.vars(v).value(:,:,:,t)) ; axis image off ;
colormap gray ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if ~isa(imdb.images.data, 'gpuArray') && numel(opts.gpus) > 0
imdb.images.data = gpuArray(imdb.images.data);
imdb.images.labels = gpuArray(imdb.images.labels);
end
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getImdDB(opts)
% --------------------------------------------------------------------
% Prepare the IMDB structure:
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
if ~exist(opts.dataPath)
fprintf('Downloading %s to %s.\n', opts.dataURL, opts.dataPath) ;
urlwrite(opts.dataURL, opts.dataPath) ;
end
dat = load(opts.dataPath);
set = [ones(1,numel(dat.y_tr)) 2*ones(1,numel(dat.y_vl)) 3*ones(1,numel(dat.y_ts))];
data = single(cat(4,dat.x_tr,dat.x_vl,dat.x_ts));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, dat.y_tr,dat.y_vl,dat.y_ts)) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
lifeng9472/IBCCF-master
|
fast_rcnn_train.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/fast_rcnn/fast_rcnn_train.m
| 6,399 |
utf_8
|
54b0bc7fa26d672ed6673d3f1832944e
|
function [net, info] = fast_rcnn_train(varargin)
%FAST_RCNN_TRAIN Demonstrates training a Fast-RCNN detector
% Copyright (C) 2016 Hakan Bilen.
% 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','bbox_functions'));
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','datasets'));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.sswDir = fullfile(vl_rootnn, 'data', 'SSW');
opts.expDir = fullfile(vl_rootnn, 'data', 'fast-rcnn-vgg16-pascal07') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.dataDir, 'models', ...
'imagenet-vgg-verydeep-16.mat') ;
opts.piecewise = true; % piecewise training (+bbox regression)
opts.train.gpus = [] ;
opts.train.batchSize = 2 ;
opts.train.numSubBatches = 1 ;
opts.train.continue = true ;
opts.train.prefetch = false ; % does not help for two images in a batch
opts.train.learningRate = 1e-3 / 64 * [ones(1,6) 0.1*ones(1,6)];
opts.train.weightDecay = 0.0005 ;
opts.train.numEpochs = 12 ;
opts.train.derOutputs = {'losscls', 1, 'lossbbox', 1} ;
opts.lite = false ;
opts.numFetchThreads = 2 ;
opts = vl_argparse(opts, varargin) ;
display(opts);
opts.train.expDir = opts.expDir ;
opts.train.numEpochs = numel(opts.train.learningRate) ;
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = fast_rcnn_init(...
'piecewise',opts.piecewise,...
'modelPath',opts.modelPath);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file') == 2
fprintf('Loading imdb...');
imdb = load(opts.imdbPath) ;
else
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir);
end
fprintf('Setting VOC2007 up, this may take a few minutes\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir', opts.dataDir, ...
'sswDir', opts.sswDir, ...
'addFlipped', true, ...
'useDifficult', true) ;
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
fprintf('\n');
end
fprintf('done\n');
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
% use train + val split to train
imdb.images.set(imdb.images.set == 2) = 1;
% minibatch options
bopts = net.meta.normalization;
bopts.useGpu = numel(opts.train.gpus) > 0 ;
bopts.numFgRoisPerImg = 16;
bopts.numRoisPerImg = 64;
bopts.maxScale = 1000;
bopts.scale = 600;
bopts.bgLabel = numel(imdb.classes.name)+1;
bopts.visualize = 0;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
bopts.prefetch = opts.train.prefetch;
[net,info] = cnn_train_dag(net, imdb, @(i,b) ...
getBatch(bopts,i,b), ...
opts.train) ;
% --------------------------------------------------------------------
% Deploy
% --------------------------------------------------------------------
modelPath = fullfile(opts.expDir, 'net-deployed.mat');
if ~exist(modelPath,'file')
net = deployFRCNN(net,imdb);
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
opts.visualize = 0;
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois,labels,btargets] = fast_rcnn_train_get_batch(images,imdb,...
batch, opts);
if opts.prefetch, return; end
nb = numel(labels);
nc = numel(imdb.classes.name) + 1;
% regression error only for positives
instance_weights = zeros(1,1,4*nc,nb,'single');
targets = zeros(1,1,4*nc,nb,'single');
for b=1:nb
if labels(b)>0 && labels(b)~=opts.bgLabel
targets(1,1,4*(labels(b)-1)+1:4*labels(b),b) = btargets(b,:)';
instance_weights(1,1,4*(labels(b)-1)+1:4*labels(b),b) = 1;
end
end
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
targets = gpuArray(targets) ;
instance_weights = gpuArray(instance_weights) ;
end
inputs = {'input', im, 'label', labels, 'rois', rois, 'targets', targets, ...
'instance_weights', instance_weights} ;
% --------------------------------------------------------------------
function net = deployFRCNN(net,imdb)
% --------------------------------------------------------------------
% function net = deployFRCNN(net)
for l = numel(net.layers):-1:1
if isa(net.layers(l).block, 'dagnn.Loss') || ...
isa(net.layers(l).block, 'dagnn.DropOut')
layer = net.layers(l);
net.removeLayer(layer.name);
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
end
net.rebuild();
pfc8 = net.getLayerIndex('predcls') ;
net.addLayer('probcls',dagnn.SoftMax(),net.layers(pfc8).outputs{1},...
'probcls',{});
net.vars(net.getVarIndex('probcls')).precious = true ;
idxBox = net.getLayerIndex('predbbox') ;
if ~isnan(idxBox)
net.vars(net.layers(idxBox).outputIndexes(1)).precious = true ;
% incorporate mean and std to bbox regression parameters
blayer = net.layers(idxBox) ;
filters = net.params(net.getParamIndex(blayer.params{1})).value ;
biases = net.params(net.getParamIndex(blayer.params{2})).value ;
boxMeans = single(imdb.boxes.bboxMeanStd{1}');
boxStds = single(imdb.boxes.bboxMeanStd{2}');
net.params(net.getParamIndex(blayer.params{1})).value = ...
bsxfun(@times,filters,...
reshape([boxStds(:)' zeros(1,4,'single')]',...
[1 1 1 4*numel(net.meta.classes.name)]));
biases = biases .* [boxStds(:)' zeros(1,4,'single')];
net.params(net.getParamIndex(blayer.params{2})).value = ...
bsxfun(@plus,biases, [boxMeans(:)' zeros(1,4,'single')]);
end
net.mode = 'test' ;
|
github
|
lifeng9472/IBCCF-master
|
fast_rcnn_evaluate.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/fast_rcnn/fast_rcnn_evaluate.m
| 6,941 |
utf_8
|
a54a3f8c3c8e5a8ff7ebe4e2b12ede30
|
function [aps, speed] = fast_rcnn_evaluate(varargin)
%FAST_RCNN_EVALUATE Evaluate a trained Fast-RCNN model on PASCAL VOC 2007
% Copyright (C) 2016 Hakan Bilen.
% 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn, 'data', 'VOCdevkit', 'VOCcode'));
addpath(genpath(fullfile(vl_rootnn, 'examples', 'fast_rcnn')));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.sswDir = fullfile(opts.dataDir, 'SSW');
opts.expDir = fullfile(opts.dataDir, 'fast-rcnn-vgg16-pascal07') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.expDir, 'net-deployed.mat') ;
opts.gpu = [] ;
opts.numFetchThreads = 1 ;
opts.nmsThresh = 0.3 ;
opts.maxPerImage = 100 ;
opts = vl_argparse(opts, varargin) ;
display(opts) ;
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir) ;
end
if ~isempty(opts.gpu)
gpuDevice(opts.gpu)
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = dagnn.DagNN.loadobj(load(opts.modelPath)) ;
net.mode = 'test' ;
if ~isempty(opts.gpu)
net.move('gpu') ;
end
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file')
fprintf('Loading precomputed imdb...\n');
imdb = load(opts.imdbPath) ;
else
fprintf('Obtaining dataset and imdb...\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir',opts.dataDir,...
'sswDir',opts.sswDir);
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
end
fprintf('done\n');
bopts.averageImage = net.meta.normalization.averageImage;
bopts.useGpu = numel(opts.gpu) > 0 ;
bopts.maxScale = 1000;
bopts.bgLabel = 21;
bopts.visualize = 0;
bopts.scale = 600;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
% -------------------------------------------------------------------------
% Evaluate
% -------------------------------------------------------------------------
VOCinit;
VOCopts.testset='test';
testIdx = find(imdb.images.set == 3) ;
cls_probs = cell(1,numel(testIdx)) ;
box_deltas = cell(1,numel(testIdx)) ;
boxscores_nms = cell(numel(VOCopts.classes),numel(testIdx)) ;
ids = cell(numel(VOCopts.classes),numel(testIdx)) ;
dataVar = 'input' ;
probVarI = net.getVarIndex('probcls') ;
boxVarI = net.getVarIndex('predbbox') ;
if isnan(probVarI)
dataVar = 'data' ;
probVarI = net.getVarIndex('cls_prob') ;
boxVarI = net.getVarIndex('bbox_pred') ;
end
net.vars(probVarI).precious = true ;
net.vars(boxVarI).precious = true ;
start = tic ;
for t=1:numel(testIdx)
speed = t/toc(start) ;
fprintf('Image %d of %d (%.f HZ)\n', t, numel(testIdx), speed) ;
batch = testIdx(t);
inputs = getBatch(bopts, imdb, batch);
inputs{1} = dataVar ;
net.eval(inputs) ;
cls_probs{t} = squeeze(gather(net.vars(probVarI).value)) ;
box_deltas{t} = squeeze(gather(net.vars(boxVarI).value)) ;
end
% heuristic: keep an average of 40 detections per class per images prior
% to NMS
max_per_set = 40 * numel(testIdx);
% detection thresold for each class (this is adaptively set based on the
% max_per_set constraint)
cls_thresholds = zeros(1,numel(VOCopts.classes));
cls_probs_concat = horzcat(cls_probs{:});
for c = 1:numel(VOCopts.classes)
q = find(strcmp(VOCopts.classes{c}, net.meta.classes.name)) ;
so = sort(cls_probs_concat(q,:),'descend');
cls_thresholds(q) = so(min(max_per_set,numel(so)));
fprintf('Applying NMS for %s\n',VOCopts.classes{c});
for t=1:numel(testIdx)
si = find(cls_probs{t}(q,:) >= cls_thresholds(q)) ;
if isempty(si), continue; end
cls_prob = cls_probs{t}(q,si)';
pbox = imdb.boxes.pbox{testIdx(t)}(si,:);
% back-transform bounding box corrections
delta = box_deltas{t}(4*(q-1)+1:4*q,si)';
pred_box = bbox_transform_inv(pbox, delta);
im_size = imdb.images.size(testIdx(t),[2 1]);
pred_box = bbox_clip(round(pred_box), im_size);
% Threshold. Heuristic: keep at most 100 detection per class per image
% prior to NMS.
boxscore = [pred_box cls_prob];
[~,si] = sort(boxscore(:,5),'descend');
boxscore = boxscore(si,:);
boxscore = boxscore(1:min(size(boxscore,1),opts.maxPerImage),:);
% NMS
pick = bbox_nms(double(boxscore),opts.nmsThresh);
boxscores_nms{c,t} = boxscore(pick,:) ;
ids{c,t} = repmat({imdb.images.name{testIdx(t)}(1:end-4)},numel(pick),1) ;
if 0
figure(1) ; clf ;
idx = boxscores_nms{c,t}(:,5)>0.5;
if sum(idx)==0, continue; end
bbox_draw(imread(fullfile(imdb.imageDir,imdb.images.name{testIdx(t)})), ...
boxscores_nms{c,t}(idx,:)) ;
title(net.meta.classes.name{q}) ;
drawnow ;
pause;
%keyboard
end
end
end
%% PASCAL VOC evaluation
VOCdevkitPath = fullfile(vl_rootnn,'data','VOCdevkit');
aps = zeros(numel(VOCopts.classes),1);
% fix voc folders
VOCopts.imgsetpath = fullfile(VOCdevkitPath,'VOC2007','ImageSets','Main','%s.txt');
VOCopts.annopath = fullfile(VOCdevkitPath,'VOC2007','Annotations','%s.xml');
VOCopts.localdir = fullfile(VOCdevkitPath,'local','VOC2007');
VOCopts.detrespath = fullfile(VOCdevkitPath, 'results', 'VOC2007', 'Main', ['%s_det_', VOCopts.testset, '_%s.txt']);
% write det results to txt files
for c=1:numel(VOCopts.classes)
fid = fopen(sprintf(VOCopts.detrespath,'comp3',VOCopts.classes{c}),'w');
for i=1:numel(testIdx)
if isempty(boxscores_nms{c,i}), continue; end
dets = boxscores_nms{c,i};
for j=1:size(dets,1)
fprintf(fid,'%s %.6f %d %d %d %d\n', ...
imdb.images.name{testIdx(i)}(1:end-4), ...
dets(j,5),dets(j,1:4)) ;
end
end
fclose(fid);
[rec,prec,ap] = VOCevaldet(VOCopts,'comp3',VOCopts.classes{c},0);
fprintf('%s ap %.1f\n',VOCopts.classes{c},100*ap);
aps(c) = ap;
end
fprintf('mean ap %.1f\n',100*mean(aps));
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois] = fast_rcnn_eval_get_batch(images, imdb, batch, opts);
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
end
inputs = {'input', im, 'rois', rois} ;
|
github
|
lifeng9472/IBCCF-master
|
cnn_cifar.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/cifar/cnn_cifar.m
| 5,334 |
utf_8
|
eb9aa887d804ee635c4295a7a397206f
|
function [net, info] = cnn_cifar(varargin)
% CNN_CIFAR Demonstrates MatConvNet on CIFAR-10
% The demo includes two standard model: LeNet and Network in
% Network (NIN). Use the 'modelType' option to choose one.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.modelType = 'lenet' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.expDir = fullfile(vl_rootnn, 'data', ...
sprintf('cifar-%s', opts.modelType)) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data','cifar') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.whitenData = true ;
opts.contrastNormalization = true ;
opts.networkType = 'simplenn' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare model and data
% -------------------------------------------------------------------------
switch opts.modelType
case 'lenet'
net = cnn_cifar_init('networkType', opts.networkType) ;
case 'nin'
net = cnn_cifar_init_nin('networkType', opts.networkType) ;
otherwise
error('Unknown model type ''%s''.', opts.modelType) ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getCifarImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = imdb.meta.classes(:)' ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% -------------------------------------------------------------------------
function fn = getBatch(opts)
% -------------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% -------------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% -------------------------------------------------------------------------
function imdb = getCifarImdb(opts)
% -------------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
unpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');
files = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...
{'test_batch.mat'}];
files = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);
file_set = uint8([ones(1, 5), 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
% remove mean in any case
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean);
% normalize by image mean and std as suggested in `An Analysis of
% Single-Layer Networks in Unsupervised Feature Learning` Adam
% Coates, Honglak Lee, Andrew Y. Ng
if opts.contrastNormalization
z = reshape(data,[],60000) ;
z = bsxfun(@minus, z, mean(z,1)) ;
n = std(z,0,1) ;
z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;
data = reshape(z, 32, 32, 3, []) ;
end
if opts.whitenData
z = reshape(data,[],60000) ;
W = z(:,set == 1)*z(:,set == 1)'/60000 ;
[V,D] = eig(W) ;
% the scale is selected to approximately preserve the norm of W
d2 = diag(D) ;
en = sqrt(mean(d2)) ;
z = V*diag(en./max(sqrt(d2), 10))*V'*z ;
data = reshape(z, 32, 32, 3, []) ;
end
clNames = load(fullfile(unpackPath, 'batches.meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.label_names;
|
github
|
lifeng9472/IBCCF-master
|
cnn_cifar_init_nin.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/cifar/cnn_cifar_init_nin.m
| 5,561 |
utf_8
|
aca711e04a8cd82821f658922218368c
|
function net = cnn_cifar_init_nin(varargin)
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
% CIFAR-10 model from
% M. Lin, Q. Chen, and S. Yan. Network in network. CoRR,
% abs/1312.4400, 2013.
%
% It reproduces the NIN + Dropout result of Table 1 (<= 10.41% top1 error).
net.layers = {} ;
lr = [1 10] ;
% Block 1
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv1', ...
'weights', {init_weights(5,3,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp1', ...
'weights', {init_weights(1,192,160)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp2', ...
'weights', {init_weights(1,160,96)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp2') ;
net.layers{end+1} = struct('name', 'pool1', ...
'type', 'pool', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout1', 'rate', 0.5) ;
% Block 2
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv2', ...
'weights', {init_weights(5,96,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu2') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp3', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp4', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp4') ;
net.layers{end+1} = struct('name', 'pool2', ...
'type', 'pool', ...
'method', 'avg', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout2', 'rate', 0.5) ;
% Block 3
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv3', ...
'weights', {init_weights(3,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 1) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp5', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp5') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp6', ...
'weights', {init_weights(1,192,10)}, ...
'learningRate', 0.001*lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end}.weights{1} = 0.1 * net.layers{end}.weights{1} ;
%net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp6') ;
net.layers{end+1} = struct('type', 'pool', ...
'name', 'pool3', ...
'method', 'avg', ...
'pool', [7 7], ...
'stride', 1, ...
'pad', 0) ;
% Loss layer
net.layers{end+1} = struct('type', 'softmaxloss') ;
% Meta parameters
net.meta.inputSize = [32 32 3] ;
net.meta.trainOpts.learningRate = [0.002, 0.01, 0.02, 0.04 * ones(1,80), 0.004 * ones(1,10), 0.0004 * ones(1,10)] ;
net.meta.trainOpts.weightDecay = 0.0005 ;
net.meta.trainOpts.batchSize = 100 ;
net.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate) ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('error', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'error') ;
otherwise
assert(false) ;
end
function weights = init_weights(k,m,n)
weights{1} = randn(k,k,m,n,'single') * sqrt(2/(k*k*m)) ;
weights{2} = zeros(n,1,'single') ;
|
github
|
lifeng9472/IBCCF-master
|
cnn_imagenet_init_resnet.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/imagenet/cnn_imagenet_init_resnet.m
| 6,717 |
utf_8
|
aa905a97830e90dc7d33f75ad078301e
|
function net = cnn_imagenet_init_resnet(varargin)
%CNN_IMAGENET_INIT_RESNET Initialize the ResNet-50 model for ImageNet classification
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts = vl_argparse(opts, varargin) ;
net = dagnn.DagNN() ;
lastAdded.var = 'input' ;
lastAdded.depth = 3 ;
function Conv(name, ksize, depth, varargin)
% Helper function to add a Convolutional + BatchNorm + ReLU
% sequence to the network.
args.relu = true ;
args.downsample = false ;
args.bias = false ;
args = vl_argparse(args, varargin) ;
if args.downsample, stride = 2 ; else stride = 1 ; end
if args.bias, pars = {[name '_f'], [name '_b']} ; else pars = {[name '_f']} ; end
net.addLayer([name '_conv'], ...
dagnn.Conv('size', [ksize ksize lastAdded.depth depth], ...
'stride', stride, ....
'pad', (ksize - 1) / 2, ...
'hasBias', args.bias, ...
'opts', {'cudnnworkspacelimit', opts.cudnnWorkspaceLimit}), ...
lastAdded.var, ...
[name '_conv'], ...
pars) ;
net.addLayer([name '_bn'], ...
dagnn.BatchNorm('numChannels', depth, 'epsilon', 1e-5), ...
[name '_conv'], ...
[name '_bn'], ...
{[name '_bn_w'], [name '_bn_b'], [name '_bn_m']}) ;
lastAdded.depth = depth ;
lastAdded.var = [name '_bn'] ;
if args.relu
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
lastAdded.var, ...
[name '_relu']) ;
lastAdded.var = [name '_relu'] ;
end
end
% -------------------------------------------------------------------------
% Add input section
% -------------------------------------------------------------------------
Conv('conv1', 7, 64, ...
'relu', true, ...
'bias', false, ...
'downsample', true) ;
net.addLayer(...
'conv1_pool' , ...
dagnn.Pooling('poolSize', [3 3], ...
'stride', 2, ...
'pad', 1, ...
'method', 'max'), ...
lastAdded.var, ...
'conv1') ;
lastAdded.var = 'conv1' ;
% -------------------------------------------------------------------------
% Add intermediate sections
% -------------------------------------------------------------------------
for s = 2:5
switch s
case 2, sectionLen = 3 ;
case 3, sectionLen = 4 ; % 8 ;
case 4, sectionLen = 6 ; % 23 ; % 36 ;
case 5, sectionLen = 3 ;
end
% -----------------------------------------------------------------------
% Add intermediate segments for each section
for l = 1:sectionLen
depth = 2^(s+4) ;
sectionInput = lastAdded ;
name = sprintf('conv%d_%d', s, l) ;
% Optional adapter layer
if l == 1
Conv([name '_adapt_conv'], 1, 2^(s+6), 'downsample', s >= 3, 'relu', false) ;
end
sumInput = lastAdded ;
% ABC: 1x1, 3x3, 1x1; downsample if first segment in section from
% section 2 onwards.
lastAdded = sectionInput ;
%Conv([name 'a'], 1, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
%Conv([name 'b'], 3, 2^(s+4)) ;
Conv([name 'a'], 1, 2^(s+4)) ;
Conv([name 'b'], 3, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
Conv([name 'c'], 1, 2^(s+6), 'relu', false) ;
% Sum layer
net.addLayer([name '_sum'] , ...
dagnn.Sum(), ...
{sumInput.var, lastAdded.var}, ...
[name '_sum']) ;
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
[name '_sum'], ...
name) ;
lastAdded.var = name ;
end
end
net.addLayer('prediction_avg' , ...
dagnn.Pooling('poolSize', [7 7], 'method', 'avg'), ...
lastAdded.var, ...
'prediction_avg') ;
net.addLayer('prediction' , ...
dagnn.Conv('size', [1 1 2048 1000]), ...
'prediction_avg', ...
'prediction', ...
{'prediction_f', 'prediction_b'}) ;
net.addLayer('loss', ...
dagnn.Loss('loss', 'softmaxlog') ,...
{'prediction', 'label'}, ...
'objective') ;
net.addLayer('top1error', ...
dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, ...
'top1error') ;
net.addLayer('top5error', ...
dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
{'prediction', 'label'}, ...
'top5error') ;
% -------------------------------------------------------------------------
% Meta parameters
% -------------------------------------------------------------------------
net.meta.normalization.imageSize = [224 224 3] ;
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions ;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [3/4, 4/3] ;
net.meta.augmentation.jitterScale = [0.4, 1.1] ;
%net.meta.augmentation.jitterSaturation = 0.4 ;
%net.meta.augmentation.jitterContrast = 0.4 ;
net.meta.inputSize = {'input', [net.meta.normalization.imageSize 32]} ;
%lr = logspace(-1, -3, 60) ;
lr = [0.1 * ones(1,30), 0.01*ones(1,30), 0.001*ones(1,30)] ;
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.momentum = 0.9 ;
net.meta.trainOpts.batchSize = 256 ;
net.meta.trainOpts.numSubBatches = 4 ;
net.meta.trainOpts.weightDecay = 0.0001 ;
% Init parameters randomly
net.initParams() ;
% For uniformity with the other ImageNet networks, t
% the input data is *not* normalized to have unit standard deviation,
% whereas this is enforced by batch normalization deeper down.
% The ImageNet standard deviation (for each of R, G, and B) is about 60, so
% we adjust the weights and learing rate accordingly in the first layer.
%
% This simple change improves performance almost +1% top 1 error.
p = net.getParamIndex('conv1_f') ;
net.params(p).value = net.params(p).value / 100 ;
net.params(p).learningRate = net.params(p).learningRate / 100^2 ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, 'dagnn.BatchNorm')
k = net.getParamIndex(net.layers(l).params{3}) ;
net.params(k).learningRate = 0.3 ;
end
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_imagenet_init.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/imagenet/cnn_imagenet_init.m
| 15,279 |
utf_8
|
43bffc7ab4042d49c4f17c0e44c36bf9
|
function net = cnn_imagenet_init(varargin)
% CNN_IMAGENET_INIT Initialize a standard CNN for ImageNet
opts.scale = 1 ;
opts.initBias = 0 ;
opts.weightDecay = 1 ;
%opts.weightInitMethod = 'xavierimproved' ;
opts.weightInitMethod = 'gaussian' ;
opts.model = 'alexnet' ;
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts = vl_argparse(opts, varargin) ;
% Define layers
switch opts.model
case 'alexnet'
net.meta.normalization.imageSize = [227, 227, 3] ;
net = alexnet(net, opts) ;
bs = 256 ;
case 'vgg-f'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_f(net, opts) ;
bs = 256 ;
case {'vgg-m', 'vgg-m-1024'}
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_m(net, opts) ;
bs = 196 ;
case 'vgg-s'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_s(net, opts) ;
bs = 128 ;
case 'vgg-vd-16'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 32 ;
case 'vgg-vd-19'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 24 ;
otherwise
error('Unknown model ''%s''', opts.model) ;
end
% final touches
switch lower(opts.weightInitMethod)
case {'xavier', 'xavierimproved'}
net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ;
end
net.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;
% Meta parameters
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [2/3, 3/2] ;
if ~opts.batchNormalization
lr = logspace(-2, -4, 60) ;
else
lr = logspace(-1, -4, 20) ;
end
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.batchSize = bs ;
net.meta.trainOpts.weightDecay = 0.0005 ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{'prediction','label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = add_block(net, opts, id, h, w, in, out, stride, pad)
% --------------------------------------------------------------------
info = vl_simplenn_display(net) ;
fc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;
if fc
name = 'fc' ;
else
name = 'conv' ;
end
convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...
'weights', {{init_weight(opts, h, w, in, out, 'single'), ...
ones(out, 1, 'single')*opts.initBias}}, ...
'stride', stride, ...
'pad', pad, ...
'dilate', 1, ...
'learningRate', [1 2], ...
'weightDecay', [opts.weightDecay 0], ...
'opts', {convOpts}) ;
if opts.batchNormalization
net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%s',id), ...
'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single'), ...
zeros(out, 2, 'single')}}, ...
'epsilon', 1e-4, ...
'learningRate', [2 1 0.1], ...
'weightDecay', [0 0]) ;
end
net.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
% --------------------------------------------------------------------
function net = add_norm(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'normalize', ...
'name', sprintf('norm%s', id), ...
'param', [5 1 0.0001/5 0.75]) ;
end
% --------------------------------------------------------------------
function net = add_dropout(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'dropout', ...
'name', sprintf('dropout%s', id), ...
'rate', 0.5) ;
end
% --------------------------------------------------------------------
function net = alexnet(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 96, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 48, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 384, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 192, 384, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 192, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_s(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 2 0 2]) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 1, 0) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_m(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 2, 1) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
switch opts.model
case 'vgg-m'
bottleneck = 4096 ;
case 'vgg-m-1024'
bottleneck = 1024 ;
end
net = add_block(net, opts, '7', 1, 1, 4096, bottleneck, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, bottleneck, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_f(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 64, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '2', 5, 5, 64, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 256, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_vd(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1_1', 3, 3, 3, 64, 1, 1) ;
net = add_block(net, opts, '1_2', 3, 3, 64, 64, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2_1', 3, 3, 64, 128, 1, 1) ;
net = add_block(net, opts, '2_2', 3, 3, 128, 128, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3_1', 3, 3, 128, 256, 1, 1) ;
net = add_block(net, opts, '3_2', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '3_3', 3, 3, 256, 256, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '3_4', 3, 3, 256, 256, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool3', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '4_1', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '4_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '4_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool4', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '5_1', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '5_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 7, 7, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
|
github
|
lifeng9472/IBCCF-master
|
cnn_imagenet.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/imagenet/cnn_imagenet.m
| 6,211 |
utf_8
|
f11556c91bb9796f533c8f624ad8adbd
|
function [net, info] = cnn_imagenet(varargin)
%CNN_IMAGENET Demonstrates training a CNN on ImageNet
% This demo demonstrates training the AlexNet, VGG-F, VGG-S, VGG-M,
% VGG-VD-16, and VGG-VD-19 architectures on ImageNet data.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data','ILSVRC2012') ;
opts.modelType = 'alexnet' ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
opts.batchNormalization = true ;
opts.weightInitMethod = 'gaussian' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.modelType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
sfx = [sfx '-' opts.networkType] ;
opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.numFetchThreads = 12 ;
opts.lite = false ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% Compute image statistics (mean, RGB covariances, etc.)
imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;
if exist(imageStatsPath)
load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
else
train = find(imdb.images.set == 1) ;
images = fullfile(imdb.imageDir, imdb.images.name(train(1:100:end))) ;
[averageImage, rgbMean, rgbCovariance] = getImageStats(images, ...
'imageSize', [256 256], ...
'numThreads', opts.numFetchThreads, ...
'gpus', opts.train.gpus) ;
save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
end
[v,d] = eig(rgbCovariance) ;
rgbDeviation = v*sqrt(d) ;
clear v d ;
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
if isempty(opts.network)
switch opts.modelType
case 'resnet-50'
net = cnn_imagenet_init_resnet('averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
opts.networkType = 'dagnn' ;
otherwise
net = cnn_imagenet_init('model', opts.modelType, ...
'batchNormalization', opts.batchNormalization, ...
'weightInitMethod', opts.weightInitMethod, ...
'networkType', opts.networkType, ...
'averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
end
else
net = opts.network ;
opts.network = [] ;
end
% -------------------------------------------------------------------------
% Learn
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainFn = @cnn_train ;
case 'dagnn', trainFn = @cnn_train_dag ;
end
[net, info] = trainFn(net, imdb, getBatchFn(opts, net.meta), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train) ;
% -------------------------------------------------------------------------
% Deploy
% -------------------------------------------------------------------------
net = cnn_imagenet_deploy(net) ;
modelPath = fullfile(opts.expDir, 'net-deployed.mat')
switch opts.networkType
case 'simplenn'
save(modelPath, '-struct', 'net') ;
case 'dagnn'
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', meta.normalization.cropSize, ...
'subtractAverage', mu) ;
% Copy the parameters for data augmentation
bopts.train = bopts.test ;
for f = fieldnames(meta.augmentation)'
f = char(f) ;
bopts.train.(f) = meta.augmentation.(f) ;
end
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_imagenet_deploy.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/imagenet/cnn_imagenet_deploy.m
| 6,585 |
utf_8
|
2f3e6d216fa697ff9adfce33e75d44d8
|
function net = cnn_imagenet_deploy(net)
%CNN_IMAGENET_DEPLOY Deploy a CNN
isDag = isa(net, 'dagnn.DagNN') ;
if isDag
dagRemoveLayersOfType(net, 'dagnn.Loss') ;
dagRemoveLayersOfType(net, 'dagnn.DropOut') ;
else
net = simpleRemoveLayersOfType(net, 'softmaxloss') ;
net = simpleRemoveLayersOfType(net, 'dropout') ;
end
if isDag
net.addLayer('prob', dagnn.SoftMax(), 'prediction', 'prob', {}) ;
else
net.layers{end+1} = struct('name', 'prob', 'type', 'softmax') ;
end
if isDag
dagMergeBatchNorm(net) ;
dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ;
else
net = simpleMergeBatchNorm(net) ;
net = simpleRemoveLayersOfType(net, 'bnorm') ;
end
if ~isDag
net = simpleRemoveMomentum(net) ;
end
% Switch to use MatConvNet default memory limit for CuDNN (512 MB)
if ~isDag
for l = simpleFindLayersOfType(net, 'conv')
net.layers{l}.opts = removeCuDNNMemoryLimit(net.layers{l}.opts) ;
end
else
for name = dagFindLayersOfType(net, 'dagnn.Conv')
l = net.getLayerIndex(char(name)) ;
net.layers(l).block.opts = removeCuDNNMemoryLimit(net.layers(l).block.opts) ;
end
end
% -------------------------------------------------------------------------
function opts = removeCuDNNMemoryLimit(opts)
% -------------------------------------------------------------------------
remove = false(1, numel(opts)) ;
for i = 1:numel(opts)
if isstr(opts{i}) && strcmp(lower(opts{i}), 'CudnnWorkspaceLimit')
remove([i i+1]) = true ;
end
end
opts = opts(~remove) ;
% -------------------------------------------------------------------------
function net = simpleRemoveMomentum(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if isfield(net.layers{l}, 'momentum')
net.layers{l} = rmfield(net.layers{l}, 'momentum') ;
end
end
% -------------------------------------------------------------------------
function layers = simpleFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = find(cellfun(@(x)strcmp(x.type, type), net.layers)) ;
% -------------------------------------------------------------------------
function net = simpleRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = simpleFindLayersOfType(net, type) ;
net.layers(layers) = [] ;
% -------------------------------------------------------------------------
function layers = dagFindLayersWithOutput(net, outVarName)
% -------------------------------------------------------------------------
layers = {} ;
for l = 1:numel(net.layers)
if any(strcmp(net.layers(l).outputs, outVarName))
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function dagRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, type) ;
for i = 1:numel(names)
layer = net.layers(net.getLayerIndex(names{i})) ;
net.removeLayer(names{i}) ;
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
% -------------------------------------------------------------------------
function dagMergeBatchNorm(net)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, 'dagnn.BatchNorm') ;
for name = names
name = char(name) ;
layer = net.layers(net.getLayerIndex(name)) ;
% merge into previous conv layer
playerName = dagFindLayersWithOutput(net, layer.inputs{1}) ;
playerName = playerName{1} ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
if ~isa(player.block, 'dagnn.Conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
% if the convolution layer does not have a bias,
% recreate it to have one
if ~player.block.hasBias
block = player.block ;
block.hasBias = true ;
net.renameLayer(playerName, 'tmp') ;
net.addLayer(playerName, ...
block, ...
player.inputs, ...
player.outputs, ...
{player.params{1}, sprintf('%s_b',playerName)}) ;
net.removeLayer('tmp') ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
biases = net.getParamIndex(player.params{2}) ;
net.params(biases).value = zeros(block.size(4), 1, 'single') ;
end
filters = net.getParamIndex(player.params{1}) ;
biases = net.getParamIndex(player.params{2}) ;
multipliers = net.getParamIndex(layer.params{1}) ;
offsets = net.getParamIndex(layer.params{2}) ;
moments = net.getParamIndex(layer.params{3}) ;
[filtersValue, biasesValue] = mergeBatchNorm(...
net.params(filters).value, ...
net.params(biases).value, ...
net.params(multipliers).value, ...
net.params(offsets).value, ...
net.params(moments).value) ;
net.params(filters).value = filtersValue ;
net.params(biases).value = biasesValue ;
end
% -------------------------------------------------------------------------
function net = simpleMergeBatchNorm(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if strcmp(net.layers{l}.type, 'bnorm')
if ~strcmp(net.layers{l-1}.type, 'conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
[filters, biases] = mergeBatchNorm(...
net.layers{l-1}.weights{1}, ...
net.layers{l-1}.weights{2}, ...
net.layers{l}.weights{1}, ...
net.layers{l}.weights{2}, ...
net.layers{l}.weights{3}) ;
net.layers{l-1}.weights = {filters, biases} ;
end
end
% -------------------------------------------------------------------------
function [filters, biases] = mergeBatchNorm(filters, biases, multipliers, offsets, moments)
% -------------------------------------------------------------------------
% wk / sqrt(sigmak^2 + eps)
% bk - wk muk / sqrt(sigmak^2 + eps)
a = multipliers(:) ./ moments(:,2) ;
b = offsets(:) - moments(:,1) .* a ;
biases(:) = biases(:) + b(:) ;
sz = size(filters) ;
numFilters = sz(4) ;
filters = reshape(bsxfun(@times, reshape(filters, [], numFilters), a'), sz) ;
|
github
|
lifeng9472/IBCCF-master
|
cnn_imagenet_evaluate.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/imagenet/cnn_imagenet_evaluate.m
| 5,089 |
utf_8
|
f22247bd3614223cad4301daa91f6bd7
|
function info = cnn_imagenet_evaluate(varargin)
% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile('data', 'ILSVRC2012') ;
opts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;
opts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.networkType = [] ;
opts.lite = false ;
opts.numFetchThreads = 12 ;
opts.train.batchSize = 128 ;
opts.train.numEpochs = 1 ;
opts.train.gpus = [] ;
opts.train.prefetch = true ;
opts.train.expDir = opts.expDir ;
opts = vl_argparse(opts, varargin) ;
display(opts);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = load(opts.modelPath) ;
if isfield(net, 'net') ;
net = net.net ;
end
% Cannot use isa('dagnn.DagNN') because it is not an object yet
isDag = isfield(net, 'params') ;
if isDag
opts.networkType = 'dagnn' ;
net = dagnn.DagNN.loadobj(net) ;
trainfn = @cnn_train_dag ;
% Drop existing loss layers
drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;
for n = {net.layers(drop).name}
net.removeLayer(n) ;
end
% Extract raw predictions from softmax
sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;
predVar = 'prediction' ;
for n = {net.layers(sftmx).name}
% check if output
l = net.getLayerIndex(n) ;
v = net.getVarIndex(net.layers(l).outputs{1}) ;
if net.vars(v).fanout == 0
% remove this layer and update prediction variable
predVar = net.layers(l).inputs{1} ;
net.removeLayer(n) ;
end
end
% Add custom objective and loss layers on top of raw predictions
net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...
{predVar,'label'}, 'objective') ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{predVar,'label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{predVar,'label'}, 'top5err') ;
% Make sure that the input is called 'input'
v = net.getVarIndex('data') ;
if ~isnan(v)
net.renameVar('data', 'input') ;
end
% Swtich to test mode
net.mode = 'test' ;
else
opts.networkType = 'simplenn' ;
net = vl_simplenn_tidy(net) ;
trainfn = @cnn_train ;
net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss
end
% Synchronize label indexes used in IMDB with the ones used in NET
imdb = cnn_imagenet_sync_labels(imdb, net);
% Run evaluation
[net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...
opts.train, ...
'train', NaN, ...
'val', find(imdb.images.set==2)) ;
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if isfield(meta.normalization, 'keepAspect')
keepAspect = meta.normalization.keepAspect ;
else
keepAspect = true ;
end
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', max(meta.normalization.imageSize(1:2)) / 256, ...
'subtractAverage', mu, ...
'keepAspect', keepAspect) ;
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
lifeng9472/IBCCF-master
|
cnn_mnist_init.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/mnist/cnn_mnist_init.m
| 3,111 |
utf_8
|
367b1185af58e108aec40b61818ec6e7
|
function net = cnn_mnist_init(varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
opts.batchNormalization = true ;
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
rng('default');
rng(0) ;
f=1/100 ;
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu') ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% optionally switch to batch normalization
if opts.batchNormalization
net = insertBnorm(net, 1) ;
net = insertBnorm(net, 4) ;
net = insertBnorm(net, 7) ;
end
% Meta parameters
net.meta.inputSize = [28 28 1] ;
net.meta.trainOpts.learningRate = 0.001 ;
net.meta.trainOpts.numEpochs = 20 ;
net.meta.trainOpts.batchSize = 100 ;
% Fill in defaul values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, 'error') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topk', 5}), {'prediction', 'label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = insertBnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
ndim = size(net.layers{l}.weights{1}, 4);
layer = struct('type', 'bnorm', ...
'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...
'learningRate', [1 1 0.05], ...
'weightDecay', [0 0]) ;
net.layers{l}.biases = [] ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
|
github
|
lifeng9472/IBCCF-master
|
cnn_mnist.m
|
.m
|
IBCCF-master/external_libs/matconvnet/examples/mnist/cnn_mnist.m
| 4,613 |
utf_8
|
d23586e79502282a6f6d632c3cf8a47e
|
function [net, info] = cnn_mnist(varargin)
%CNN_MNIST Demonstrates MatConvNet on MNIST
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.batchNormalization = false ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.networkType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
opts.expDir = fullfile(vl_rootnn, 'data', ['mnist-baseline-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data', 'mnist') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if isempty(opts.network)
net = cnn_mnist_init('batchNormalization', opts.batchNormalization, ...
'networkType', opts.networkType) ;
else
net = opts.network ;
opts.network = [] ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getMnistImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% --------------------------------------------------------------------
function fn = getBatch(opts)
% --------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% --------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
% --------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getMnistImdb(opts)
% --------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
files = {'train-images-idx3-ubyte', ...
'train-labels-idx1-ubyte', ...
't10k-images-idx3-ubyte', ...
't10k-labels-idx1-ubyte'} ;
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
for i=1:4
if ~exist(fullfile(opts.dataDir, files{i}), 'file')
url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;
fprintf('downloading %s\n', url) ;
gunzip(url, opts.dataDir) ;
end
end
f=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;
x1=fread(f,inf,'uint8');
fclose(f) ;
x1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;
x2=fread(f,inf,'uint8');
fclose(f) ;
x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;
y1=fread(f,inf,'uint8');
fclose(f) ;
y1=double(y1(9:end)')+1 ;
f=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;
y2=fread(f,inf,'uint8');
fclose(f) ;
y2=double(y2(9:end)')+1 ;
set = [ones(1,numel(y1)) 3*ones(1,numel(y2))];
data = single(reshape(cat(3, x1, x2),28,28,1,[]));
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean) ;
imdb.images.data = data ;
imdb.images.data_mean = dataMean;
imdb.images.labels = cat(2, y1, y2) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
lifeng9472/IBCCF-master
|
vl_nnloss.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/vl_nnloss.m
| 11,212 |
utf_8
|
e4c325752a9cddab59f01afa0d561ea1
|
function y = vl_nnloss(x,c,dzdy,varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logisticlog`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% 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).
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
hasIgnoreLabel = any(c(:) == 0);
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights)
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
else
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
y(ci) = y(ci) - 1 ;
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
lifeng9472/IBCCF-master
|
vl_compilenn.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/vl_compilenn.m
| 30,050 |
utf_8
|
6339b625106e6c7b479e57c2b9aa578e
|
function vl_compilenn(varargin)
%VL_COMPILENN Compile the MatConvNet toolbox.
% The `vl_compilenn()` function compiles the MEX files in the
% MatConvNet toolbox. See below for the requirements for compiling
% CPU and GPU code, respectively.
%
% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:
%
% `EnableGpu`:: `false`
% Set to true in order to enable GPU support.
%
% `Verbose`:: 0
% Set the verbosity level (0, 1 or 2).
%
% `Debug`:: `false`
% Set to true to compile the binaries with debugging
% information.
%
% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`
% Choose the method used to compile the CUDA code. There are two
% methods:
%
% * The **`mex`** method uses the MATLAB MEX command with the
% configuration file
% `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]`
% This configuration file is in XML format since MATLAB 8.3
% (R2014a) and is a Shell script for earlier versions. This
% is, principle, the preferred method as it uses the
% MATLAB-sanctioned compiler options.
%
% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`
% directly to compile CUDA source code into object files.
%
% This method allows to use a CUDA toolkit version that is not
% the one that officially supported by a particular MATALB
% version (see below). It is also the default method for
% compilation under Windows and with CuDNN.
%
% `CudaRoot`:: guessed automatically
% This option specifies the path to the CUDA toolkit to use for
% compilation.
%
% `EnableImreadJpeg`:: `true`
% Set this option to `true` to compile `vl_imreadjpeg`.
%
% `EnableDouble`:: `true`
% Set this option to `true` to compile the support for DOUBLE
% data types.
%
% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)
% The image library to use for `vl_impreadjpeg`.
%
% `ImageLibraryCompileFlags`:: platform dependent
% A cell-array of additional flags to use when compiling
% `vl_imreadjpeg`.
%
% `ImageLibraryLinkFlags`:: platform dependent
% A cell-array of additional flags to use when linking
% `vl_imreadjpeg`.
%
% `EnableCudnn`:: `false`
% Set to `true` to compile CuDNN support. See CuDNN
% documentation for the Hardware/CUDA version requirements.
%
% `CudnnRoot`:: `'local/'`
% Directory containing the unpacked binaries and header files of
% the CuDNN library.
%
% ## Compiling the CPU code
%
% By default, the `EnableGpu` option is switched to off, such that
% the GPU code support is not compiled in.
%
% Generally, you only need a 64bit C/C++ compiler (usually Xcode, GCC or
% Visual Studio for Mac, Linux, and Windows respectively). The
% compiler can be setup in MATLAB using the
%
% mex -setup
%
% command.
%
% ## Compiling the GPU code
%
% In order to compile the GPU code, set the `EnableGpu` option to
% `true`. For this to work you will need:
%
% * To satisfy all the requirements to compile the CPU code (see
% above).
%
% * A NVIDIA GPU with at least *compute capability 2.0*.
%
% * The *MATALB Parallel Computing Toolbox*. This can be purchased
% from Mathworks (type `ver` in MATLAB to see if this toolbox is
% already comprised in your MATLAB installation; it often is).
%
% * A copy of the *CUDA Devkit*, which can be downloaded for free
% from NVIDIA. Note that each MATLAB version requires a
% particular CUDA Devkit version:
%
% | MATLAB version | Release | CUDA Devkit |
% |----------------|---------|--------------|
% | 8.2 | 2013b | 5.5 |
% | 8.3 | 2014a | 5.5 |
% | 8.4 | 2014b | 6.0 |
% | 8.6 | 2015b | 7.0 |
% | 9.0 | 2016a | 7.5 |
%
% Different versions of CUDA may work using the hack described
% above (i.e. setting the `CudaMethod` to `nvcc`).
%
% The following configurations have been tested successfully:
%
% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010, 2013 and CUDA Toolkit
% 6.5. VS 2015 CPU version only (not supported by CUDA Toolkit yet).
% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA
% Toolkit 6.5.
% * Mac OS X 10.9, 10.10, 10.11, MATLAB R2013a to R2016a, Xcode, CUDA
% Toolkit 5.5 to 7.5.
% * GNU/Linux, MATALB R2014a/R2015a/R2015b/R2016a, gcc/g++, CUDA Toolkit 5.5/6.5/7.5.
%
% Compilation on Windows with MinGW compiler (the default mex compiler in
% Matlab) is not supported. For Windows, please reconfigure mex to use
% Visual Studio C/C++ compiler.
% Furthermore your GPU card must have ComputeCapability >= 2.0 (see
% output of `gpuDevice()`) in order to be able to run the GPU code.
% To change the compute capabilities, for `mex` `CudaMethod` edit
% the particular config file. For the 'nvcc' method, compute
% capability is guessed based on the GPUDEVICE output. You can
% override it by setting the 'CudaArch' parameter (e.g. in case of
% multiple GPUs with various architectures).
%
% See also: [Compliling MatConvNet](../install.md#compiling),
% [Compiling MEX files containing CUDA
% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),
% `vl_setup()`, `vl_imreadjpeg()`.
% Copyright (C) 2014-16 Karel Lenc and 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).
% Get MatConvNet root directory
root = fileparts(fileparts(mfilename('fullpath'))) ;
addpath(fullfile(root, 'matlab')) ;
% --------------------------------------------------------------------
% Parse options
% --------------------------------------------------------------------
opts.enableGpu = false;
opts.enableImreadJpeg = true;
opts.enableCudnn = false;
opts.enableDouble = true;
opts.imageLibrary = [] ;
opts.imageLibraryCompileFlags = {} ;
opts.imageLibraryLinkFlags = [] ;
opts.verbose = 0;
opts.debug = false;
opts.cudaMethod = [] ;
opts.cudaRoot = [] ;
opts.cudaArch = [] ;
opts.defCudaArch = [...
'-gencode=arch=compute_20,code=\"sm_20,compute_20\" '...
'-gencode=arch=compute_30,code=\"sm_30,compute_30\"'];
opts.cudnnRoot = 'local/cudnn' ;
opts = vl_argparse(opts, varargin);
% --------------------------------------------------------------------
% Files to compile
% --------------------------------------------------------------------
arch = computer('arch') ;
if isempty(opts.imageLibrary)
switch arch
case 'glnxa64', opts.imageLibrary = 'libjpeg' ;
case 'maci64', opts.imageLibrary = 'quartz' ;
case 'win64', opts.imageLibrary = 'gdiplus' ;
end
end
if isempty(opts.imageLibraryLinkFlags)
switch opts.imageLibrary
case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;
case 'quartz', opts.imageLibraryLinkFlags = {'-framework Cocoa -framework ImageIO'} ;
case 'gdiplus', opts.imageLibraryLinkFlags = {'gdiplus.lib'} ;
end
end
lib_src = {} ;
mex_src = {} ;
% Files that are compiled as CPP or CU depending on whether GPU support
% is enabled.
if opts.enableGpu, ext = 'cu' ; else ext='cpp' ; end
lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbilinearsampler.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnroipooling.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbilinearsampler.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnroipool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_taccummex.' ext]) ;
switch arch
case {'glnxa64','maci64'}
% not yet supported in windows
mex_src{end+1} = fullfile(root,'matlab','src',['vl_tmove.' ext]) ;
end
% CPU-specific files
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','imread.cpp') ;
% GPU-specific files
if opts.enableGpu
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;
mex_src{end+1} = fullfile(root,'matlab','src','vl_cudatool.cu') ;
end
% cuDNN-specific files
if opts.enableCudnn
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbilinearsampler_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbnorm_cudnn.cu') ;
end
% Other files
if opts.enableImreadJpeg
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg_old.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;
end
% --------------------------------------------------------------------
% Setup CUDA toolkit
% --------------------------------------------------------------------
if opts.enableGpu
opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ;
% Find the CUDA Devkit
if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ...
mfilename, opts.cudaRoot) ;
opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;
switch arch
case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;
case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;
case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
% Set the nvcc method as default for Win platforms
if strcmp(arch, 'win64') && isempty(opts.cudaMethod)
opts.cudaMethod = 'nvcc';
end
% Activate the CUDA Devkit
cuver = activate_nvcc(opts.nvccPath) ;
opts.verbose && fprintf('%s:\tCUDA: using NVCC ''%s'' (%d).\n', ...
mfilename, opts.nvccPath, cuver) ;
% Set the CUDA arch string (select GPU architecture)
if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ...
mfilename, opts.cudaArch) ;
end
if opts.enableCudnn
opts.cudnnIncludeDir = fullfile(opts.cudnnRoot, 'include') ;
switch arch
case 'win64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib', 'x64') ;
case 'maci64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib') ;
case 'glnxa64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
end
% --------------------------------------------------------------------
% Compiler options
% --------------------------------------------------------------------
% Build directories
mex_dir = fullfile(root, 'matlab', 'mex') ;
bld_dir = fullfile(mex_dir, '.build');
if ~exist(fullfile(bld_dir,'bits','impl'), 'dir')
mkdir(fullfile(bld_dir,'bits','impl')) ;
end
% Compiler flags
flags.cc = {} ;
flags.ccpass = {} ;
flags.ccoptim = {} ;
flags.link = {} ;
flags.linklibs = {} ;
flags.linkpass = {} ;
flags.nvccpass = {char(opts.cudaArch)} ;
if opts.verbose > 1
flags.cc{end+1} = '-v' ;
end
if opts.debug
flags.cc{end+1} = '-g' ;
flags.nvccpass{end+1} = '-O0' ;
else
flags.cc{end+1} = '-DNDEBUG' ;
flags.nvccpass{end+1} = '-O3' ;
end
if opts.enableGpu
flags.cc{end+1} = '-DENABLE_GPU' ;
end
if opts.enableCudnn
flags.cc{end+1} = '-DENABLE_CUDNN' ;
flags.cc{end+1} = ['-I"' opts.cudnnIncludeDir '"'] ;
end
if opts.enableDouble
flags.cc{end+1} = '-DENABLE_DOUBLE' ;
end
flags.link{end+1} = '-lmwblas' ;
switch arch
case {'maci64'}
case {'glnxa64'}
flags.linklibs{end+1} = '-lrt' ;
case {'win64'}
% VisualC does not pass this even if available in the CPU architecture
flags.cc{end+1} = '-D__SSSE3__' ;
end
if opts.enableImreadJpeg
flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;
flags.linklibs = horzcat(flags.linklibs, opts.imageLibraryLinkFlags) ;
end
if opts.enableGpu
flags.link = horzcat(flags.link, {['-L"' opts.cudaLibDir '"'], '-lcudart', '-lcublas'}) ;
switch arch
case {'maci64', 'glnxa64'}
flags.link{end+1} = '-lmwgpu' ;
case 'win64'
flags.link{end+1} = '-lgpu' ;
end
if opts.enableCudnn
flags.link{end+1} = ['-L"' opts.cudnnLibDir '"'] ;
flags.link{end+1} = '-lcudnn' ;
end
end
switch arch
case {'maci64'}
flags.ccpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.linkpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.ccoptim{end+1} = '-mssse3 -ffast-math' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
if opts.enableGpu && cuver < 70000
% CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native
% clang libc++. This should go away in the future.
flags.ccpass{end+1} = '-stdlib=libstdc++' ;
flags.linkpass{end+1} = '-stdlib=libstdc++' ;
if ~verLessThan('matlab', '8.5.0')
% Complicating matters, MATLAB 8.5.0 links to clang's libc++ by
% default when linking MEX files overriding the option above. We
% force it to use GCC libstdc++
flags.linkpass{end+1} = '-L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ;
end
end
case {'glnxa64'}
flags.ccoptim{end+1} = '-mssse3 -ftree-vect-loop-version -ffast-math -funroll-all-loops' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC -D_FORCE_INLINES' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
case {'win64'}
flags.nvccpass{end+1} = '-Xcompiler /MD' ;
cl_path = fileparts(check_clpath()); % check whether cl.exe in path
flags.nvccpass{end+1} = sprintf('--compiler-bindir "%s"', cl_path) ;
end
% --------------------------------------------------------------------
% Command flags
% --------------------------------------------------------------------
flags.mexcc = horzcat(flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' strjoin(flags.ccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' strjoin(flags.ccoptim)]}) ;
if ~ispc, flags.mexcc{end+1} = '-cxx'; end
% mex: compile GPU
flags.mexcu= horzcat({'-f' mex_cuda_config(root)}, ...
flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' quote_nvcc(flags.ccpass) ' ' strjoin(flags.nvccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' quote_nvcc(flags.ccoptim)]}) ;
% mex: link
flags.mexlink = horzcat(flags.cc, flags.link, ...
{'-largeArrayDims'}, ...
{['LDFLAGS=$LDFLAGS ', strjoin(flags.linkpass)]}, ...
{['LINKLIBS=', strjoin(flags.linklibs), ' $LINKLIBS']}) ;
% nvcc: compile GPU
flags.nvcc = horzcat(flags.cc, ...
{opts.cudaArch}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'extern', 'include'))}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include'))}, ...
{quote_nvcc(flags.ccpass)}, ...
{quote_nvcc(flags.ccoptim)}, ...
flags.nvccpass) ;
if opts.verbose
fprintf('%s: * Compiler and linker configurations *\n', mfilename) ;
fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ;
fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ;
fprintf('%s: \tMEX options [CC CPU]: %s\n', mfilename, strjoin(flags.mexcc)) ;
fprintf('%s: \tMEX options [LINK]: %s\n', mfilename, strjoin(flags.mexlink)) ;
end
if opts.verbose && opts.enableGpu
fprintf('%s: \tMEX options [CC GPU]: %s\n', mfilename, strjoin(flags.mexcu)) ;
end
if opts.verbose && opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')
fprintf('%s: \tNVCC options [CC GPU]: %s\n', mfilename, strjoin(flags.nvcc)) ;
end
if opts.verbose && opts.enableImreadJpeg
fprintf('%s: * Reading images *\n', mfilename) ;
fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ;
fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ;
fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;
fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;
end
% --------------------------------------------------------------------
% Compile
% --------------------------------------------------------------------
% Intermediate object files
srcs = horzcat(lib_src,mex_src) ;
for i = 1:numel(horzcat(lib_src, mex_src))
[~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;
objfile = toobj(bld_dir,srcs{i});
if strcmp(ext,'cu')
if strcmp(opts.cudaMethod,'nvcc')
nvcc_compile(opts, srcs{i}, objfile, flags.nvcc) ;
else
mex_compile(opts, srcs{i}, objfile, flags.mexcu) ;
end
else
mex_compile(opts, srcs{i}, objfile, flags.mexcc) ;
end
assert(exist(objfile, 'file') ~= 0, 'Compilation of %s failed.', objfile);
end
% Link into MEX files
for i = 1:numel(mex_src)
objs = toobj(bld_dir, [mex_src(i), lib_src]) ;
mex_link(opts, objs, mex_dir, flags.mexlink) ;
end
% Reset path adding the mex subdirectory just created
vl_setupnn() ;
% --------------------------------------------------------------------
% Utility functions
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function objs = toobj(bld_dir,srcs)
% --------------------------------------------------------------------
str = fullfile('matlab','src') ;
multiple = iscell(srcs) ;
if ~multiple, srcs = {srcs} ; end
objs = cell(1, numel(srcs));
for t = 1:numel(srcs)
i = strfind(srcs{t},str);
objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;
end
if ~multiple, objs = objs{1} ; end
objs = regexprep(objs,'.cpp$',['.' objext]) ;
objs = regexprep(objs,'.cu$',['.' objext]) ;
objs = regexprep(objs,'.c$',['.' objext]) ;
% --------------------------------------------------------------------
function mex_compile(opts, src, tgt, mex_opts)
% --------------------------------------------------------------------
mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;
opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function nvcc_compile(opts, src, tgt, nvcc_opts)
% --------------------------------------------------------------------
nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');
nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ...
nvcc_path, src, ...
strjoin(nvcc_opts), tgt);
opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ;
status = system(nvcc_cmd);
if status, error('Command %s failed.', nvcc_cmd); end;
% --------------------------------------------------------------------
function mex_link(opts, objs, mex_dir, mex_flags)
% --------------------------------------------------------------------
mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;
opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function ext = objext()
% --------------------------------------------------------------------
% Get the extension for an 'object' file for the current computer
% architecture
switch computer('arch')
case 'win64', ext = 'obj';
case {'maci64', 'glnxa64'}, ext = 'o' ;
otherwise, error('Unsupported architecture %s.', computer) ;
end
% --------------------------------------------------------------------
function conf_file = mex_cuda_config(root)
% --------------------------------------------------------------------
% Get mex CUDA config file
mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;
if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end
arch = computer('arch') ;
switch arch
case {'win64'}
config_dir = fullfile(matlabroot, 'toolbox', ...
'distcomp', 'gpu', 'extern', ...
'src', 'mex', arch) ;
case {'maci64', 'glnxa64'}
config_dir = fullfile(root, 'matlab', 'src', 'config') ;
end
conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);
fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file);
% --------------------------------------------------------------------
function cl_path = check_clpath()
% --------------------------------------------------------------------
% Checks whether the cl.exe is in the path (needed for the nvcc). If
% not, tries to guess the location out of mex configuration.
cc = mex.getCompilerConfigurations('c++');
if isempty(cc)
error(['Mex is not configured.'...
'Run "mex -setup" to configure your compiler. See ',...
'http://www.mathworks.com/support/compilers ', ...
'for supported compilers for your platform.']);
end
cl_path = fullfile(cc.Location, 'VC', 'bin', 'amd64');
[status, ~] = system('cl.exe -help');
if status == 1
warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');
prev_path = getenv('PATH');
setenv('PATH', [prev_path ';' cl_path]);
status = system('cl.exe');
if status == 1
setenv('PATH', prev_path);
error('Unable to find cl.exe');
else
fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ...
cl_path);
end
end
% -------------------------------------------------------------------------
function paths = which_nvcc()
% -------------------------------------------------------------------------
switch computer('arch')
case 'win64'
[~, paths] = system('where nvcc.exe');
paths = strtrim(paths);
paths = paths(strfind(paths, '.exe'));
case {'maci64', 'glnxa64'}
[~, paths] = system('which nvcc');
paths = strtrim(paths) ;
end
% -------------------------------------------------------------------------
function cuda_root = search_cuda_devkit(opts)
% -------------------------------------------------------------------------
% This function tries to to locate a working copy of the CUDA Devkit.
opts.verbose && fprintf(['%s:\tCUDA: searching for the CUDA Devkit' ...
' (use the option ''CudaRoot'' to override):\n'], mfilename);
% Propose a number of candidate paths for NVCC
paths = {getenv('MW_NVCC_PATH')} ;
paths = [paths, which_nvcc()] ;
for v = {'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0'}
switch computer('arch')
case 'glnxa64'
paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;
case 'maci64'
paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;
case 'win64'
paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ;
end
end
paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;
% Validate each candidate NVCC path
for i=1:numel(paths)
nvcc(i).path = paths{i} ;
[nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(paths{i}) ;
end
if opts.verbose
fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ;
for i=1:numel(paths)
fprintf('\t| %5d | %5d | %-70s |\n', ...
nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;
end
end
% Pick an entry
index = find([nvcc.isvalid]) ;
if isempty(index)
error('Could not find a valid NVCC executable\n') ;
end
[~, newest] = max([nvcc(index).version]);
nvcc = nvcc(index(newest)) ;
cuda_root = fileparts(fileparts(nvcc.path)) ;
if opts.verbose
fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ...
mfilename, nvcc.path, nvcc.version) ;
end
% -------------------------------------------------------------------------
function [valid, cuver] = validate_nvcc(nvccPath)
% -------------------------------------------------------------------------
[status, output] = system(sprintf('"%s" --version', nvccPath)) ;
valid = (status == 0) ;
if ~valid
cuver = 0 ;
return ;
end
match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ;
if isempty(match), valid = false ; return ; end
cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;
% --------------------------------------------------------------------
function cuver = activate_nvcc(nvccPath)
% --------------------------------------------------------------------
% Validate the NVCC compiler installation
[valid, cuver] = validate_nvcc(nvccPath) ;
if ~valid
error('The NVCC compiler ''%s'' does not appear to be valid.', nvccPath) ;
end
% Make sure that NVCC is visible by MEX by setting the MW_NVCC_PATH
% environment variable to the NVCC compiler path
if ~strcmp(getenv('MW_NVCC_PATH'), nvccPath)
warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', nvccPath) ;
setenv('MW_NVCC_PATH', nvccPath) ;
end
% In some operating systems and MATLAB versions, NVCC must also be
% available in the command line search path. Make sure that this is%
% the case.
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
warning('NVCC not found in the command line path or the one found does not matches ''%s''.', nvccPath);
nvccDir = fileparts(nvccPath) ;
prevPath = getenv('PATH') ;
switch computer
case 'PCWIN64', separator = ';' ;
case {'GLNXA64', 'MACI64'}, separator = ':' ;
end
setenv('PATH', [nvccDir separator prevPath]) ;
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
setenv('PATH', prevPath) ;
error('Unable to set the command line path to point to ''%s'' correctly.', nvccPath) ;
else
fprintf('Location of NVCC (%s) added to your command search PATH.\n', nvccDir) ;
end
end
% -------------------------------------------------------------------------
function str = quote_nvcc(str)
% -------------------------------------------------------------------------
if iscell(str), str = strjoin(str) ; end
str = strrep(strtrim(str), ' ', ',') ;
if ~isempty(str), str = ['-Xcompiler ' str] ; end
% --------------------------------------------------------------------
function cudaArch = get_cuda_arch(opts)
% --------------------------------------------------------------------
opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename);
try
gpu_device = gpuDevice();
arch_code = strrep(gpu_device.ComputeCapability, '.', '');
cudaArch = ...
sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ...
arch_code, arch_code, arch_code) ;
catch
opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU; ' ...
'falling back to default\n'], mfilename);
cudaArch = opts.defCudaArch;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.