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
Steganalysis-CNN/CNN-without-BN-master
cnn_imagenet_init.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
cnn_imagenet.m
.m
CNN-without-BN-master/dependencies/matconvnet/examples/imagenet/cnn_imagenet.m
6,240
utf_8
eaead56ec3104ef8f4b39e043aaf0d41
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 = 'resnet-50' ; 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.imdb.classes.name, ... 'classDescriptions', imdb.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.imdb.images.name(batch)) ; if ~isempty(batch) && imdb.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.imdb.images.label(batch) ; switch networkType case 'simplenn' varargout = {data, labels} ; case 'dagnn' varargout{1} = {'input', data, 'label', labels} ; end end
github
Steganalysis-CNN/CNN-without-BN-master
cnn_imagenet_deploy.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
cnn_imagenet_evaluate.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
cnn_mnist_init.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
cnn_mnist.m
.m
CNN-without-BN-master/dependencies/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
Steganalysis-CNN/CNN-without-BN-master
vl_nnloss.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/vl_nnloss.m
11,377
utf_8
a070d1cf73525dca7566f6e5c0205297
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) ; [~,predictions] = sort(x,3,'descend') ; %size(predictions) opts.topK = 2; 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
Steganalysis-CNN/CNN-without-BN-master
vl_compilenn.m
.m
CNN-without-BN-master/dependencies/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
github
Steganalysis-CNN/CNN-without-BN-master
getVarReceptiveFields.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/+dagnn/@DagNN/getVarReceptiveFields.m
3,635
utf_8
6d61896e475e64e9f05f10303eee7ade
function rfs = getVarReceptiveFields(obj, var) %GETVARRECEPTIVEFIELDS Get the receptive field of a variable % RFS = GETVARRECEPTIVEFIELDS(OBJ, VAR) gets the receptivie fields RFS of % all the variables of the DagNN OBJ into variable VAR. VAR is a variable % name or index. % % RFS has one entry for each variable in the DagNN following the same % format as has DAGNN.GETRECEPTIVEFIELDS(). For example, RFS(i) is the % receptive field of the i-th variable in the DagNN into variable VAR. If % the i-th variable is not a descendent of VAR in the DAG, then there is % no receptive field, indicated by `rfs(i).size == []`. If the receptive % field cannot be computed (e.g. because it depends on the values of % variables and not just on the network topology, or if it cannot be % expressed as a sliding window), then `rfs(i).size = [NaN NaN]`. % Copyright (C) 2015 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). if ~isnumeric(var) var_n = obj.getVarIndex(var) ; if isnan(var_n) error('Variable %s not found.', var_n); end var = var_n; end nv = numel(obj.vars) ; nw = numel(var) ; rfs = struct('size', cell(nw, nv), 'stride', cell(nw, nv), 'offset', cell(nw,nv)) ; for w = 1:numel(var) rfs(w,var(w)).size = [1 1] ; rfs(w,var(w)).stride = [1 1] ; rfs(w,var(w)).offset = [1 1] ; end for l = obj.executionOrder % visit all blocks and get their receptive fields in = obj.layers(l).inputIndexes ; out = obj.layers(l).outputIndexes ; blockRfs = obj.layers(l).block.getReceptiveFields() ; for w = 1:numel(var) % find the receptive fields in each of the inputs of the block for i = 1:numel(in) for j = 1:numel(out) rf = composeReceptiveFields(rfs(w, in(i)), blockRfs(i,j)) ; rfs(w, out(j)) = resolveReceptiveFields([rfs(w, out(j)), rf]) ; end end end end end % ------------------------------------------------------------------------- function rf = composeReceptiveFields(rf1, rf2) % ------------------------------------------------------------------------- if isempty(rf1.size) || isempty(rf2.size) rf.size = [] ; rf.stride = [] ; rf.offset = [] ; return ; end rf.size = rf1.stride .* (rf2.size - 1) + rf1.size ; rf.stride = rf1.stride .* rf2.stride ; rf.offset = rf1.stride .* (rf2.offset - 1) + rf1.offset ; end % ------------------------------------------------------------------------- function rf = resolveReceptiveFields(rfs) % ------------------------------------------------------------------------- rf.size = [] ; rf.stride = [] ; rf.offset = [] ; for i = 1:numel(rfs) if isempty(rfs(i).size), continue ; end if isnan(rfs(i).size) rf.size = [NaN NaN] ; rf.stride = [NaN NaN] ; rf.offset = [NaN NaN] ; break ; end if isempty(rf.size) rf = rfs(i) ; else if ~isequal(rf.stride,rfs(i).stride) % incompatible geometry; this cannot be represented by a sliding % window RF field and may denotes an error in the network structure rf.size = [NaN NaN] ; rf.stride = [NaN NaN] ; rf.offset = [NaN NaN] ; break; else % the two RFs have the same stride, so they can be recombined % the new RF is just large enough to contain both of them a = rf.offset - (rf.size-1)/2 ; b = rf.offset + (rf.size-1)/2 ; c = rfs(i).offset - (rfs(i).size-1)/2 ; d = rfs(i).offset + (rfs(i).size-1)/2 ; e = min(a,c) ; f = max(b,d) ; rf.offset = (e+f)/2 ; rf.size = f-e+1 ; end end end end
github
Steganalysis-CNN/CNN-without-BN-master
rebuild.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/+dagnn/@DagNN/rebuild.m
3,243
utf_8
e368536d9e70c805d8424cdd6b593960
function rebuild(obj) %REBUILD Rebuild the internal data structures of a DagNN object % REBUILD(obj) rebuilds the internal data structures % of the DagNN obj. It is an helper function used internally % to update the network when layers are added or removed. varFanIn = zeros(1, numel(obj.vars)) ; varFanOut = zeros(1, numel(obj.vars)) ; parFanOut = zeros(1, numel(obj.params)) ; for l = 1:numel(obj.layers) ii = obj.getVarIndex(obj.layers(l).inputs) ; oi = obj.getVarIndex(obj.layers(l).outputs) ; pi = obj.getParamIndex(obj.layers(l).params) ; obj.layers(l).inputIndexes = ii ; obj.layers(l).outputIndexes = oi ; obj.layers(l).paramIndexes = pi ; varFanOut(ii) = varFanOut(ii) + 1 ; varFanIn(oi) = varFanIn(oi) + 1 ; parFanOut(pi) = parFanOut(pi) + 1 ; end [obj.vars.fanin] = tolist(num2cell(varFanIn)) ; [obj.vars.fanout] = tolist(num2cell(varFanOut)) ; if ~isempty(parFanOut) [obj.params.fanout] = tolist(num2cell(parFanOut)) ; end % dump unused variables keep = (varFanIn + varFanOut) > 0 ; obj.vars = obj.vars(keep) ; varRemap = cumsum(keep) ; % dump unused parameters keep = parFanOut > 0 ; obj.params = obj.params(keep) ; parRemap = cumsum(keep) ; % update the indexes to account for removed layers, variables and parameters for l = 1:numel(obj.layers) obj.layers(l).inputIndexes = varRemap(obj.layers(l).inputIndexes) ; obj.layers(l).outputIndexes = varRemap(obj.layers(l).outputIndexes) ; obj.layers(l).paramIndexes = parRemap(obj.layers(l).paramIndexes) ; obj.layers(l).block.layerIndex = l ; end % update the variable and parameter names hash maps obj.varNames = cell2struct(num2cell(1:numel(obj.vars)), {obj.vars.name}, 2) ; obj.paramNames = cell2struct(num2cell(1:numel(obj.params)), {obj.params.name}, 2) ; obj.layerNames = cell2struct(num2cell(1:numel(obj.layers)), {obj.layers.name}, 2) ; % determine the execution order again (and check for consistency) obj.executionOrder = getOrder(obj) ; % -------------------------------------------------------------------- function order = getOrder(obj) % -------------------------------------------------------------------- hops = cell(1, numel(obj.vars)) ; for l = 1:numel(obj.layers) for v = obj.layers(l).inputIndexes hops{v}(end+1) = l ; end end order = zeros(1, numel(obj.layers)) ; for l = 1:numel(obj.layers) if order(l) == 0 order = dagSort(obj, hops, order, l) ; end end if any(order == -1) warning('The network graph contains a cycle') ; end [~,order] = sort(order, 'descend') ; % -------------------------------------------------------------------- function order = dagSort(obj, hops, order, layer) % -------------------------------------------------------------------- if order(layer) > 0, return ; end order(layer) = -1 ; % mark as open n = 0 ; for o = obj.layers(layer).outputIndexes ; for child = hops{o} if order(child) == -1 return ; end if order(child) == 0 order = dagSort(obj, hops, order, child) ; end n = max(n, order(child)) ; end end order(layer) = n + 1 ; % -------------------------------------------------------------------- function varargout = tolist(x) % -------------------------------------------------------------------- [varargout{1:numel(x)}] = x{:} ;
github
Steganalysis-CNN/CNN-without-BN-master
print.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/+dagnn/@DagNN/print.m
15,032
utf_8
7da4e68e624f559f815ee3076d9dd966
function str = print(obj, inputSizes, varargin) %PRINT Print information about the DagNN object % PRINT(OBJ) displays a summary of the functions and parameters in the network. % STR = PRINT(OBJ) returns the summary as a string instead of printing it. % % PRINT(OBJ, INPUTSIZES) where INPUTSIZES is a cell array of the type % {'input1nam', input1size, 'input2name', input2size, ...} prints % information using the specified size for each of the listed inputs. % % PRINT(___, 'OPT', VAL, ...) accepts the following options: % % `All`:: false % Display all the information below. % % `Layers`:: '*' % Specify which layers to print. This can be either a list of % indexes, a cell array of array names, or the string '*', meaning % all layers. % % `Parameters`:: '*' % Specify which parameters to print, similar to the option above. % % `Variables`:: [] % Specify which variables to print, similar to the option above. % % `Dependencies`:: false % Whether to display the dependency (geometric transformation) % of each variables from each input. % % `Format`:: 'ascii' % Choose between `ascii`, `latex`, `csv`, 'digraph', and `dot`. % The first three format print tables; `digraph` uses the plot function % for a `digraph` (supported in MATLAB>=R2015b) and the last one % prints a graph in `dot` format. In case of zero outputs, it % attmepts to compile and visualise the dot graph using `dot` command % and `start` (Windows), `display` (Linux) or `open` (Mac OSX) on your system. % In the latter case, all variables and layers are included in the % graph, regardless of the other parameters. % % `FigurePath`:: 'tempname.pdf' % Sets the path where any generated `dot` figure will be saved. Currently, % this is useful only in combination with the format `dot`. % By default, a unique temporary filename is used (`tempname` % is replaced with a `tempname()` call). The extension specifies the % output format (passed to dot as a `-Text` parameter). % If not extension provided, PDF used by default. % Additionally, stores the .dot file used to generate the figure to % the same location. % % `dotArgs`:: '' % Additional dot arguments. E.g. '-Gsize="7"' to generate a smaller % output (for a review of the network structure etc.). % % `MaxNumColumns`:: 18 % Maximum number of columns in each table. % % See also: DAGNN, DAGNN.GETVARSIZES(). if nargin > 1 && ischar(inputSizes) % called directly with options, skipping second argument varargin = {inputSizes, varargin{:}} ; inputSizes = {} ; end opts.all = false ; opts.format = 'ascii' ; opts.figurePath = 'tempname.pdf' ; opts.dotArgs = ''; [opts, varargin] = vl_argparse(opts, varargin) ; opts.layers = '*' ; opts.parameters = [] ; opts.variables = [] ; if opts.all || nargin > 1 opts.variables = '*' ; end if opts.all opts.parameters = '*' ; end opts.memory = true ; opts.dependencies = opts.all ; opts.maxNumColumns = 18 ; opts = vl_argparse(opts, varargin) ; if nargin == 1, inputSizes = {} ; end varSizes = obj.getVarSizes(inputSizes) ; paramSizes = cellfun(@size, {obj.params.value}, 'UniformOutput', false) ; str = {''} ; if strcmpi(opts.format, 'dot') str = printDot(obj, varSizes, paramSizes, opts) ; if nargout == 0 displayDot(str, opts) ; end return ; end if strcmpi(opts.format,'digraph') str = printdigraph(obj, varSizes) ; return ; end if ~isempty(opts.layers) table = {'func', '-', 'type', 'inputs', 'outputs', 'params', 'pad', 'stride'} ; for l = select(obj, 'layers', opts.layers) layer = obj.layers(l) ; table{l+1,1} = layer.name ; table{l+1,2} = '-' ; table{l+1,3} = player(class(layer.block)) ; table{l+1,4} = strtrim(sprintf('%s ', layer.inputs{:})) ; table{l+1,5} = strtrim(sprintf('%s ', layer.outputs{:})) ; table{l+1,6} = strtrim(sprintf('%s ', layer.params{:})) ; if isprop(layer.block, 'pad') table{l+1,7} = pdims(layer.block.pad) ; else table{l+1,7} = 'n/a' ; end if isprop(layer.block, 'stride') table{l+1,8} = pdims(layer.block.stride) ; else table{l+1,8} = 'n/a' ; end end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if ~isempty(opts.parameters) table = {'param', '-', 'dims', 'mem', 'fanout'} ; for v = select(obj, 'params', opts.parameters) table{v+1,1} = obj.params(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(paramSizes{v}) ; table{v+1,4} = pmem(prod(paramSizes{v}) * 4) ; table{v+1,5} = sprintf('%d',obj.params(v).fanout) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if ~isempty(opts.variables) table = {'var', '-', 'dims', 'mem', 'fanin', 'fanout'} ; for v = select(obj, 'vars', opts.variables) table{v+1,1} = obj.vars(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(varSizes{v}) ; table{v+1,4} = pmem(prod(varSizes{v}) * 4) ; table{v+1,5} = sprintf('%d',obj.vars(v).fanin) ; table{v+1,6} = sprintf('%d',obj.vars(v).fanout) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if opts.memory paramMem = sum(cellfun(@getMem, paramSizes)) ; varMem = sum(cellfun(@getMem, varSizes)) ; table = {'params', 'vars', 'total'} ; table{2,1} = pmem(paramMem) ; table{2,2} = pmem(varMem) ; table{2,3} = pmem(paramMem + varMem) ; str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end if opts.dependencies % print variable to input dependencies inputs = obj.getInputs() ; rfs = obj.getVarReceptiveFields(inputs) ; for i = 1:size(rfs,1) table = {sprintf('rf in ''%s''', inputs{i}), '-', 'size', 'stride', 'offset'} ; for v = 1:size(rfs,2) table{v+1,1} = obj.vars(v).name ; table{v+1,2} = '-' ; table{v+1,3} = pdims(rfs(i,v).size) ; table{v+1,4} = pdims(rfs(i,v).stride) ; table{v+1,5} = pdims(rfs(i,v).offset) ; end str{end+1} = printtable(opts, table') ; str{end+1} = sprintf('\n') ; end end % finish str = horzcat(str{:}) ; if nargout == 0, fprintf('%s',str) ; clear str ; end end % ------------------------------------------------------------------------- function str = printtable(opts, table) % ------------------------------------------------------------------------- str = {''} ; for i=2:opts.maxNumColumns:size(table,2) sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ; str{end+1} = printtablechunk(opts, table(:, [1 sel])) ; str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; end % ------------------------------------------------------------------------- function str = printtablechunk(opts, table) % ------------------------------------------------------------------------- str = {''} ; switch opts.format case 'ascii' sizes = max(cellfun(@(x) numel(x), table),[],1) ; for i=1:size(table,1) for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds|', sizes(j)) ; if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end str{end+1} = sprintf(fmt, s) ; end str{end+1} = sprintf('\n') ; end case 'latex' sizes = max(cellfun(@(x) numel(x), table),[],1) ; str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ; for i=1:size(table,1) if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds', sizes(j)) ; str{end+1} = sprintf(fmt, latexesc(s)) ; if j<size(table,2), str{end+1} = sprintf('&') ; end end str{end+1} = sprintf('\\\\\n') ; end str{end+1}= sprintf('\\end{tabular}\n') ; case 'csv' sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ; for i=1:size(table,1) if isequal(table{i,1},'-'), continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds,', sizes(j)) ; str{end+1} = sprintf(fmt, ['"' s '"']) ; end str{end+1} = sprintf('\n') ; end otherwise error('Uknown format %s', opts.format) ; end str = horzcat(str{:}) ; end % ------------------------------------------------------------------------- function s = latexesc(s) % ------------------------------------------------------------------------- s = strrep(s,'\','\\') ; s = strrep(s,'_','\char`_') ; end % ------------------------------------------------------------------------- function s = pmem(x) % ------------------------------------------------------------------------- if isnan(x), s = 'NaN' ; elseif x < 1024^1, s = sprintf('%.0fB', x) ; elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ; elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ; else s = sprintf('%.0fGB', x / 1024^3) ; end end % ------------------------------------------------------------------------- function s = pdims(x) % ------------------------------------------------------------------------- if all(isnan(x)) s = 'n/a' ; return ; end if all(x==x(1)) s = sprintf('%.4g', x(1)) ; else s = sprintf('%.4gx', x(:)) ; s(end) = [] ; end end % ------------------------------------------------------------------------- function x = player(x) % ------------------------------------------------------------------------- if numel(x) < 7, return ; end if x(1:6) == 'dagnn.', x = x(7:end) ; end end % ------------------------------------------------------------------------- function m = getMem(sz) % ------------------------------------------------------------------------- m = prod(sz) * 4 ; if isnan(m), m = 0 ; end end % ------------------------------------------------------------------------- function sel = select(obj, type, pattern) % ------------------------------------------------------------------------- if isnumeric(pattern) sel = pattern ; else if isstr(pattern) if strcmp(pattern, '*') sel = 1:numel(obj.(type)) ; return ; else pattern = {pattern} ; end end sel = find(cellfun(@(x) any(strcmp(x, pattern)), {obj.(type).name})) ; end end % ------------------------------------------------------------------------- function h = printdigraph(net, varSizes) % ------------------------------------------------------------------------- if exist('digraph') ~= 2 error('MATLAB graph support not present.'); end s = []; t = []; w = []; varsNames = {net.vars.name}; layerNames = {net.layers.name}; numVars = numel(varsNames); spatSize = cellfun(@(vs) vs(1), varSizes); spatSize(isnan(spatSize)) = 1; varChannels = cellfun(@(vs) vs(3), varSizes); varChannels(isnan(varChannels)) = 0; for li = 1:numel(layerNames) l = net.layers(li); lidx = numVars + li; s = [s l.inputIndexes]; t = [t lidx*ones(1, numel(l.inputIndexes))]; w = [w spatSize(l.inputIndexes)]; s = [s lidx*ones(1, numel(l.outputIndexes))]; t = [t l.outputIndexes]; w = [w spatSize(l.outputIndexes)]; end nodeNames = [varsNames, layerNames]; g = digraph(s, t, w); lw = 5*g.Edges.Weight/max([g.Edges.Weight; 5]); h = plot(g, 'NodeLabel', nodeNames, 'LineWidth', lw); highlight(h, numVars+1:numVars+numel(layerNames), 'MarkerSize', 8, 'Marker', 's'); highlight(h, 1:numVars, 'MarkerSize', 5, 'Marker', 's'); cmap = copper; varNvalRel = varChannels./max(varChannels); for vi = 1:numel(varChannels) highlight(h, vi, 'NodeColor', cmap(max(round(varNvalRel(vi)*64), 1),:)); end axis off; layout(h, 'force'); end % ------------------------------------------------------------------------- function str = printDot(net, varSizes, paramSizes, otps) % ------------------------------------------------------------------------- str = {} ; str{end+1} = sprintf('digraph DagNN {\n\tfontsize=12\n') ; font_style = 'fontsize=12 fontname="helvetica"'; for v = 1:numel(net.vars) label=sprintf('{{%s} | {%s | %s }}', net.vars(v).name, pdims(varSizes{v}), pmem(4*prod(varSizes{v}))) ; str{end+1} = sprintf('\tvar_%s [label="%s" shape=record style="solid,rounded,filled" color=cornsilk4 fillcolor=beige %s ]\n', ... net.vars(v).name, label, font_style) ; end for p = 1:numel(net.params) label=sprintf('{{%s} | {%s | %s }}', net.params(p).name, pdims(paramSizes{p}), pmem(4*prod(paramSizes{p}))) ; str{end+1} = sprintf('\tpar_%s [label="%s" shape=record style="solid,rounded,filled" color=lightsteelblue4 fillcolor=lightsteelblue %s ]\n', ... net.params(p).name, label, font_style) ; end for l = 1:numel(net.layers) label = sprintf('{ %s | %s }', net.layers(l).name, class(net.layers(l).block)) ; str{end+1} = sprintf('\t%s [label="%s" shape=record style="bold,filled" color="tomato4" fillcolor="tomato" %s ]\n', ... net.layers(l).name, label, font_style) ; for i = 1:numel(net.layers(l).inputs) str{end+1} = sprintf('\tvar_%s->%s [weight=10]\n', ... net.layers(l).inputs{i}, ... net.layers(l).name) ; end for o = 1:numel(net.layers(l).outputs) str{end+1} = sprintf('\t%s->var_%s [weight=10]\n', ... net.layers(l).name, ... net.layers(l).outputs{o}) ; end for p = 1:numel(net.layers(l).params) str{end+1} = sprintf('\tpar_%s->%s [weight=1]\n', ... net.layers(l).params{p}, ... net.layers(l).name) ; end end str{end+1} = sprintf('}\n') ; str = cat(2,str{:}) ; end % ------------------------------------------------------------------------- function displayDot(str, opts) % ------------------------------------------------------------------------- %mwdot = fullfile(matlabroot, 'bin', computer('arch'), 'mwdot') ; dotPaths = {'/opt/local/bin/dot', 'dot'} ; if ismember(computer, {'PCWIN64', 'PCWIN'}) winPath = 'c:\Program Files (x86)'; dpath = dir(fullfile(winPath, 'Graphviz*')); if ~isempty(dpath) dotPaths = [{fullfile(winPath, dpath.name, 'bin', 'dot.exe')}, dotPaths]; end end dotExe = '' ; for i = 1:numel(dotPaths) [~,~,ext] = fileparts(dotPaths{i}); if exist(dotPaths{i},'file') && ~strcmp(ext, '.m') dotExe = dotPaths{i} ; break; end end if isempty(dotExe) warning('Could not genereate a figure because the `dot` utility could not be found.') ; return ; end [path, figName, ext] = fileparts(opts.figurePath) ; if isempty(ext), ext = '.pdf' ; end if strcmp(figName, 'tempname') figName = tempname(); end in = fullfile(path, [ figName, '.dot' ]) ; out = fullfile(path, [ figName, ext ]) ; f = fopen(in, 'w') ; fwrite(f, str) ; fclose(f) ; cmd = sprintf('"%s" -T%s %s -o "%s" "%s"', dotExe, ext(2:end), ... opts.dotArgs, out, in) ; [status, result] = system(cmd) ; if status ~= 0 error('Unable to run %s\n%s', cmd, result) ; end if ~isempty(strtrim(result)) fprintf('Dot output:\n%s\n', result) ; end %f = fopen(out,'r') ; file=fread(f, 'char=>char')' ; fclose(f) ; switch computer case {'PCWIN64', 'PCWIN'} system(sprintf('start "" "%s"', out)) ; case 'MACI64' system(sprintf('open "%s"', out)) ; case 'GLNXA64' system(sprintf('display "%s"', out)) ; otherwise fprintf('The figure saved at "%s"\n', out) ; end end
github
Steganalysis-CNN/CNN-without-BN-master
fromSimpleNN.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/+dagnn/@DagNN/fromSimpleNN.m
7,258
utf_8
83f914aec610125592263d74249f54a7
function obj = fromSimpleNN(net, varargin) % FROMSIMPLENN Initialize a DagNN object from a SimpleNN network % FROMSIMPLENN(NET) initializes the DagNN object from the % specified CNN using the SimpleNN format. % % SimpleNN objects are linear chains of computational layers. These % layers exchange information through variables and parameters that % are not explicitly named. Hence, FROMSIMPLENN() uses a number of % rules to assign such names automatically: % % * From the input to the output of the CNN, variables are called % `x0` (input of the first layer), `x1`, `x2`, .... In this % manner `xi` is the output of the i-th layer. % % * Any loss layer requires two inputs, the second being a label. % These are called `label` (for the first such layers), and then % `label2`, `label3`,... for any other similar layer. % % Additionally, given the option `CanonicalNames` the function can % change the names of some variables to make them more convenient to % use. With this option turned on: % % * The network input is called `input` instead of `x0`. % % * The output of each SoftMax layer is called `prob` (or `prob2`, % ...). % % * The output of each Loss layer is called `objective` (or ` % objective2`, ...). % % * The input of each SoftMax or Loss layer of type *softmax log % loss* is called `prediction` (or `prediction2`, ...). If a Loss % layer immediately follows a SoftMax layer, then the rule above % takes precendence and the input name is not changed. % % FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options: % % `CanonicalNames`:: false % If `true` use the rules above to assign more meaningful % names to some of the variables. % Copyright (C) 2015 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). opts.canonicalNames = false ; opts = vl_argparse(opts, varargin) ; import dagnn.* obj = DagNN() ; net = vl_simplenn_move(net, 'cpu') ; net = vl_simplenn_tidy(net) ; % copy meta-information as is obj.meta = net.meta ; for l = 1:numel(net.layers) inputs = {sprintf('x%d',l-1)} ; outputs = {sprintf('x%d',l)} ; params = struct(... 'name', {}, ... 'value', {}, ... 'learningRate', [], ... 'weightDecay', []) ; if isfield(net.layers{l}, 'name') name = net.layers{l}.name ; else name = sprintf('layer%d',l) ; end switch net.layers{l}.type case {'conv', 'convt'} sz = size(net.layers{l}.weights{1}) ; hasBias = ~isempty(net.layers{l}.weights{2}) ; params(1).name = sprintf('%sf',name) ; params(1).value = net.layers{l}.weights{1} ; if hasBias params(2).name = sprintf('%sb',name) ; params(2).value = net.layers{l}.weights{2} ; end if isfield(net.layers{l},'learningRate') params(1).learningRate = net.layers{l}.learningRate(1) ; if hasBias params(2).learningRate = net.layers{l}.learningRate(2) ; end end if isfield(net.layers{l},'weightDecay') params(1).weightDecay = net.layers{l}.weightDecay(1) ; if hasBias params(2).weightDecay = net.layers{l}.weightDecay(2) ; end end switch net.layers{l}.type case 'conv' block = Conv() ; block.size = sz ; block.pad = net.layers{l}.pad ; block.stride = net.layers{l}.stride ; block.dilate = net.layers{l}.dilate ; case 'convt' block = ConvTranspose() ; block.size = sz ; block.upsample = net.layers{l}.upsample ; block.crop = net.layers{l}.crop ; block.numGroups = net.layers{l}.numGroups ; end block.hasBias = hasBias ; block.opts = net.layers{l}.opts ; case 'pool' block = Pooling() ; block.method = net.layers{l}.method ; block.poolSize = net.layers{l}.pool ; block.pad = net.layers{l}.pad ; block.stride = net.layers{l}.stride ; block.opts = net.layers{l}.opts ; case {'normalize', 'lrn'} block = LRN() ; block.param = net.layers{l}.param ; case {'dropout'} block = DropOut() ; block.rate = net.layers{l}.rate ; case {'relu'} block = ReLU() ; block.leak = net.layers{l}.leak ; case {'sigmoid'} block = Sigmoid() ; case {'softmax'} block = SoftMax() ; case {'softmaxloss'} block = Loss('loss', 'softmaxlog') ; % The loss has two inputs inputs{2} = getNewVarName(obj, 'label') ; case {'bnorm'} block = BatchNorm() ; params(1).name = sprintf('%sm',name) ; params(1).value = net.layers{l}.weights{1} ; params(2).name = sprintf('%sb',name) ; params(2).value = net.layers{l}.weights{2} ; params(3).name = sprintf('%sx',name) ; params(3).value = net.layers{l}.weights{3} ; if isfield(net.layers{l},'learningRate') params(1).learningRate = net.layers{l}.learningRate(1) ; params(2).learningRate = net.layers{l}.learningRate(2) ; params(3).learningRate = net.layers{l}.learningRate(3) ; end if isfield(net.layers{l},'weightDecay') params(1).weightDecay = net.layers{l}.weightDecay(1) ; params(2).weightDecay = net.layers{l}.weightDecay(2) ; params(3).weightDecay = 0 ; end otherwise error([net.layers{l}.type ' is unsupported']) ; end obj.addLayer(... name, ... block, ... inputs, ... outputs, ... {params.name}) ; for p = 1:numel(params) pindex = obj.getParamIndex(params(p).name) ; if ~isempty(params(p).value) obj.params(pindex).value = params(p).value ; end if ~isempty(params(p).learningRate) obj.params(pindex).learningRate = params(p).learningRate ; end if ~isempty(params(p).weightDecay) obj.params(pindex).weightDecay = params(p).weightDecay ; end end end % -------------------------------------------------------------------- % Rename variables to canonical names % -------------------------------------------------------------------- if opts.canonicalNames for l = 1:numel(obj.layers) if l == 1 obj.renameVar(obj.layers(l).inputs{1}, 'input') ; end if isa(obj.layers(l).block, 'dagnn.SoftMax') obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ; obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ; end if isa(obj.layers(l).block, 'dagnn.Loss') obj.renameVar(obj.layers(l).outputs{1}, 'objective') ; if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*')) obj.renameVar(obj.layers(l).inputs{1}, ... getNewVarName(obj, 'prediction')) ; end end end end if isfield(obj.meta, 'inputs') obj.meta.inputs(1).name = obj.layers(1).inputs{1} ; end % -------------------------------------------------------------------- function name = getNewVarName(obj, prefix) % -------------------------------------------------------------------- t = 0 ; name = prefix ; while any(strcmp(name, {obj.vars.name})) t = t + 1 ; name = sprintf('%s%d', prefix, t) ; end
github
Steganalysis-CNN/CNN-without-BN-master
vl_simplenn_display.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/simplenn/vl_simplenn_display.m
12,455
utf_8
65bb29cd7c27b68c75fdd27acbd63e2b
function [info, str] = vl_simplenn_display(net, varargin) %VL_SIMPLENN_DISPLAY Display the structure of a SimpleNN network. % VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET. % % INFO = VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO % with several statistics for each layer of the network NET. % % [INFO, STR] = VL_SIMPLENN_DISPLAY(...) returns also a string STR % with the text that would otherwise be printed. % % The function accepts the following options: % % `inputSize`:: auto % Specifies the size of the input tensor X that will be passed to % the network as input. This information is used in order to % estiamte the memory required to process the network. When this % option is not used, VL_SIMPLENN_DISPLAY() tires to use values % in the NET structure to guess the input size: % NET.META.INPUTSIZE and NET.META.NORMALIZATION.IMAGESIZE % (assuming a batch size of one image, unless otherwise specified % by the `batchSize` option). % % `batchSize`:: [] % Specifies the number of data points in a batch in estimating % the memory consumption, overriding the last dimension of % `inputSize`. % % `maxNumColumns`:: 18 % Maximum number of columns in a table. Wider tables are broken % into multiple smaller ones. % % `format`:: `'ascii'` % One of `'ascii'`, `'latex'`, or `'csv'`. % % See also: VL_SIMPLENN(). % 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.inputSize = [] ; opts.batchSize = [] ; opts.maxNumColumns = 18 ; opts.format = 'ascii' ; opts = vl_argparse(opts, varargin) ; % determine input size, using first the option, then net.meta.inputSize, % and eventually net.meta.normalization.imageSize, if any if isempty(opts.inputSize) tmp = [] ; opts.inputSize = [NaN;NaN;NaN;1] ; if isfield(net, 'meta') if isfield(net.meta, 'inputSize') tmp = net.meta.inputSize(:) ; elseif isfield(net.meta, 'normalization') && ... isfield(net.meta.normalization, 'imageSize') tmp = net.meta.normalization.imageSize ; end opts.inputSize(1:numel(tmp)) = tmp(:) ; end end if ~isempty(opts.batchSize) opts.inputSize(4) = opts.batchSize ; end fields={'layer', 'type', 'name', '-', ... 'support', 'filtd', 'filtdil', 'nfilt', 'stride', 'pad', '-', ... 'rfsize', 'rfoffset', 'rfstride', '-', ... 'dsize', 'ddepth', 'dnum', '-', ... 'xmem', 'wmem'}; % get the support, stride, and padding of the operators for l = 1:numel(net.layers) ly = net.layers{l} ; switch ly.type case 'conv' ks = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ; ks = (ks - 1) .* ly.dilate + 1 ; info.support(1:2,l) = ks ; case 'pool' info.support(1:2,l) = ly.pool(:) ; otherwise info.support(1:2,l) = [1;1] ; end if isfield(ly, 'stride') info.stride(1:2,l) = ly.stride(:) ; else info.stride(1:2,l) = 1 ; end if isfield(ly, 'pad') info.pad(1:4,l) = ly.pad(:) ; else info.pad(1:4,l) = 0 ; end % operator applied to the input image info.receptiveFieldSize(1:2,l) = 1 + ... sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ... (info.support(1:2,1:l)-1),2) ; info.receptiveFieldOffset(1:2,l) = 1 + ... sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ... ((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ; info.receptiveFieldStride = cumprod(info.stride,2) ; end % get the dimensions of the data info.dataSize(1:4,1) = opts.inputSize(:) ; for l = 1:numel(net.layers) ly = net.layers{l} ; if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize') sz = ly.getForwardSize(ly, info.dataSize(:,l)) ; info.dataSize(:,l+1) = sz(:) ; continue ; end info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ... sum(info.pad(1:2,l)) - ... info.support(1,l)) / info.stride(1,l)) + 1 ; info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ... sum(info.pad(3:4,l)) - ... info.support(2,l)) / info.stride(2,l)) + 1 ; info.dataSize(3, l+1) = info.dataSize(3,l) ; info.dataSize(4, l+1) = info.dataSize(4,l) ; switch ly.type case 'conv' if isfield(ly, 'weights') f = ly.weights{1} ; else f = ly.filters ; end if size(f, 3) ~= 0 info.dataSize(3, l+1) = size(f,4) ; end case {'loss', 'softmaxloss'} info.dataSize(3:4, l+1) = 1 ; case 'custom' info.dataSize(3,l+1) = NaN ; end end if nargout == 1, return ; end % print table table = {} ; wmem = 0 ; xmem = 0 ; for wi=1:numel(fields) w = fields{wi} ; switch w case 'type', s = 'type' ; case 'stride', s = 'stride' ; case 'rfsize', s = 'rf size' ; case 'rfstride', s = 'rf stride' ; case 'rfoffset', s = 'rf offset' ; case 'dsize', s = 'data size' ; case 'ddepth', s = 'data depth' ; case 'dnum', s = 'data num' ; case 'nfilt', s = 'num filts' ; case 'filtd', s = 'filt dim' ; case 'filtdil', s = 'filt dilat' ; case 'wmem', s = 'param mem' ; case 'xmem', s = 'data mem' ; otherwise, s = char(w) ; end table{wi,1} = s ; % do input pseudo-layer for l=0:numel(net.layers) switch char(w) case '-', s='-' ; case 'layer', s=sprintf('%d', l) ; case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ; case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ; case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ; case 'xmem' a = prod(info.dataSize(:,l+1)) * 4 ; s = pmem(a) ; xmem = xmem + a ; otherwise if l == 0 if strcmp(char(w),'type'), s = 'input'; else s = 'n/a' ; end else ly=net.layers{l} ; switch char(w) case 'name' if isfield(ly, 'name') s=ly.name ; else s='' ; end case 'type' switch ly.type case 'normalize', s='norm'; case 'pool' if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end case 'softmax', s='softmx' ; case 'softmaxloss', s='softmxl' ; otherwise s=ly.type ; end case 'nfilt' switch ly.type case 'conv' if isfield(ly, 'weights'), a = size(ly.weights{1},4) ; else, a = size(ly.filters,4) ; end s=sprintf('%d',a) ; otherwise s='n/a' ; end case 'filtd' switch ly.type case 'conv' s=sprintf('%d',size(ly.weights{1},3)) ; otherwise s='n/a' ; end case 'filtdil' switch ly.type case 'conv' s=sprintf('%d',ly.dilate) ; otherwise s='n/a' ; end case 'support' s = pdims(info.support(:,l)) ; case 'stride' s = pdims(info.stride(:,l)) ; case 'pad' s = pdims(info.pad(:,l)) ; case 'rfsize' s = pdims(info.receptiveFieldSize(:,l)) ; case 'rfoffset' s = pdims(info.receptiveFieldOffset(:,l)) ; case 'rfstride' s = pdims(info.receptiveFieldStride(:,l)) ; case 'wmem' a = 0 ; if isfield(ly, 'weights') ; for j=1:numel(ly.weights) a = a + numel(ly.weights{j}) * 4 ; end end % Legacy code to be removed if isfield(ly, 'filters') ; a = a + numel(ly.filters) * 4 ; end if isfield(ly, 'biases') ; a = a + numel(ly.biases) * 4 ; end s = pmem(a) ; wmem = wmem + a ; end end end table{wi,l+2} = s ; end end str = {} ; for i=2:opts.maxNumColumns:size(table,2) sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ; str{end+1} = ptable(opts, table(:,[1 sel])) ; end table = {... 'parameter memory', sprintf('%s (%.2g parameters)', pmem(wmem), wmem/4); 'data memory', sprintf('%s (for batch size %d)', pmem(xmem), info.dataSize(4,1))} ; str{end+1} = ptable(opts, table) ; str = horzcat(str{:}) ; if nargout == 0 fprintf('%s', str) ; clear info str ; end % ------------------------------------------------------------------------- function str = ptable(opts, table) % ------------------------------------------------------------------------- switch opts.format case 'ascii', str = pascii(table) ; case 'latex', str = platex(table) ; case 'csv', str = pcsv(table) ; end str = horzcat(str,sprintf('\n')) ; % ------------------------------------------------------------------------- function s = pmem(x) % ------------------------------------------------------------------------- if isnan(x), s = 'NaN' ; elseif x < 1024^1, s = sprintf('%.0fB', x) ; elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ; elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ; else s = sprintf('%.0fGB', x / 1024^3) ; end % ------------------------------------------------------------------------- function s = pdims(x) % ------------------------------------------------------------------------- if all(x==x(1)) s = sprintf('%.4g', x(1)) ; else s = sprintf('%.4gx', x(:)) ; s(end) = [] ; end % ------------------------------------------------------------------------- function str = pascii(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) ; for i=1:size(table,1) for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds|', sizes(j)) ; if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end str{end+1} = sprintf(fmt, s) ; end str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function str = pcsv(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ; for i=1:size(table,1) if isequal(table{i,1},'-'), continue ; end for j=1:size(table,2) s = table{i,j} ; str{end+1} = sprintf('%s,', ['"' s '"']) ; end str{end+1} = sprintf('\n') ; end str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function str = platex(table) % ------------------------------------------------------------------------- str = {} ; sizes = max(cellfun(@(x) numel(x), table),[],1) ; str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ; for i=1:size(table,1) if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end for j=1:size(table,2) s = table{i,j} ; fmt = sprintf('%%%ds', sizes(j)) ; str{end+1} = sprintf(fmt, latexesc(s)) ; if j<size(table,2), str{end+1} = sprintf('&') ; end end str{end+1} = sprintf('\\\\\n') ; end str{end+1} = sprintf('\\end{tabular}\n') ; str = horzcat(str{:}) ; % ------------------------------------------------------------------------- function s = latexesc(s) % ------------------------------------------------------------------------- s = strrep(s,'\','\\') ; s = strrep(s,'_','\char`_') ; % ------------------------------------------------------------------------- function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem) % ------------------------------------------------------------------------- if nargin <= 1 cpuMem = 0 ; gpuMem = 0 ; end if isstruct(s) for f=fieldnames(s)' f = char(f) ; for i=1:numel(s) [cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ; end end elseif iscell(s) for i=1:numel(s) [cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ; end elseif isnumeric(s) if isa(s, 'single') mult = 4 ; else mult = 8 ; end if isa(s,'gpuArray') gpuMem = gpuMem + mult * numel(s) ; else cpuMem = cpuMem + mult * numel(s) ; end end
github
Steganalysis-CNN/CNN-without-BN-master
vl_test_economic_relu.m
.m
CNN-without-BN-master/dependencies/matconvnet/matlab/xtest/vl_test_economic_relu.m
790
utf_8
35a3dbe98b9a2f080ee5f911630ab6f3
% VL_TEST_ECONOMIC_RELU function vl_test_economic_relu() x = randn(11,12,8,'single'); w = randn(5,6,8,9,'single'); b = randn(1,9,'single') ; net.layers{1} = struct('type', 'conv', ... 'filters', w, ... 'biases', b, ... 'stride', 1, ... 'pad', 0); net.layers{2} = struct('type', 'relu') ; res = vl_simplenn(net, x) ; dzdy = randn(size(res(end).x), 'like', res(end).x) ; clear res ; res_ = vl_simplenn(net, x, dzdy) ; res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ; a=whos('res_') ; b=whos('res__') ; assert(a.bytes > b.bytes) ; vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ; vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ; vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
github
gsygsy96/dense_flow-master
extractOpticalFlow_gpu.m
.m
dense_flow-master/extractOpticalFlow_gpu.m
3,132
utf_8
b6bb10a83f1f67dab8c935b34f78f236
function [] = extractOpticalFlow_gpu(index, device_id, type) path1 = '/media/sdg/lmwang/Data/UCF101/ucf101_org/'; if type ==0 path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_farn_gpu_step_2/'; elseif type ==1 path2 = '/media/sdg/lmwang/data/UCF101/ucf101_flow_img_tvl1_gpu_size_342/'; else path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_brox_gpu_step_2/'; end device_id = 1; type = 1; fid = fopen('anet_8_1.cmd','w'); path1 = '/nfs_c06/Datasets/ActivityNet/anet_clips_v1.3/'; path2 = '/nfs_c06/Datasets/ActivityNet/anet_clips_v1.3_flow_img_fvl1_gpu_size_256/'; path3 = '/nfs_c06/Datasets/ActivityNet/anet_clips_v1.3_rgb_img_new_size_256/'; filelist = dir([path1,'*.avi']); index = device_id*5000+1:(device_id+1)*5000; for i =2014 if ~exist([path2,filelist(i).name(1:end-4)],'dir') mkdir([path2,filelist(i).name(1:end-4)]); end if ~exist([path3,filelist(i).name(1:end-4)],'dir') mkdir([path3,filelist(i).name(1:end-4)]); end file1 = [path1,filelist(i).name]; file2 = [path2,filelist(i).name(1:end-4),'/','flow_x']; file3 = [path2,filelist(i).name(1:end-4),'/','flow_y']; file4 = [path3,filelist(i).name(1:end-4),'/','image']; % cmd = sprintf('build/denseFlow_gpu -f %s -x %s -y %s -i %s -b 20 -t %d -d %d -s %d',... % file1,file2,file3,file4,type,device_id,1); cmd = sprintf('build/denseImage -f %s -i %s',... file1,file4); fprintf(fid,'%s\n', cmd); end fclose(fid); path = '/nfs_c06/Datasets/ActivityNet/anet_clips_v1.3_rgb_img_size_256/'; folderlist = dir(path); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); duration = zeros(1, length(foldername)); for i = 1:length(foldername) duration(i) = length(dir([path, foldername{i}, '/*.jpg'])); end % path1 = '/nfs/lmwang/lmwang/Data/HMDB51/hmdb51_org/'; % if type ==0 % path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_farn_gpu/'; % elseif type ==1 % path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_tvl1_gpu/'; % else % path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_brox_gpu/'; % end folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); fid = fopen('anet_1_1.cmd','w'); for i = 3175:5000 if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./build/denseFlow_gpu -f %s -x %s -y %s -i %s -b 20 -t %d -d %d -s %d',... file1,file2,file3,file4,type,device_id,1); fprintf(fid,'%s\n', cmd); end i end fclose(fid); end
github
gsygsy96/dense_flow-master
extracOpticalFlow.m
.m
dense_flow-master/extracOpticalFlow.m
1,032
utf_8
6c684588cd7294f4b9da8c772842d1e1
function [] = extracOpticalFlow(index) path1 = '/home/lmwang/data/UCF/ucf101_org/'; path2 = '/home/lmwang/data/UCF/ucf101_warp_flow_img/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./denseFlow -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
gsygsy96/dense_flow-master
extractOpticalFlow.m
.m
dense_flow-master/extractOpticalFlow.m
1,040
utf_8
cc9a423971c037f30e6cd1a2c997f820
function [] = extractOpticalFlow(index) path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/'; path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_TV/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./denseFlow -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
MAS-dfab/T1_python-exercises-master
subsolv.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/subsolv.m
5,830
utf_8
c6a16954d2524b7645e6ed4ccffd8a10
%------------------------------------------------------------- % This is the file subsolv.m % % Version Dec 2006. % Krister Svanberg <[email protected]> % Department of Mathematics, KTH, % SE-10044 Stockholm, Sweden. % function [xmma,ymma,zmma,lamma,xsimma,etamma,mumma,zetmma,smma] = ... subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d); % % This function subsolv solves the MMA subproblem: % % minimize SUM[ p0j/(uppj-xj) + q0j/(xj-lowj) ] + a0*z + % + SUM[ ci*yi + 0.5*di*(yi)^2 ], % % subject to SUM[ pij/(uppj-xj) + qij/(xj-lowj) ] - ai*z - yi <= bi, % alfaj <= xj <= betaj, yi >= 0, z >= 0. % % Input: m, n, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d. % Output: xmma,ymma,zmma, slack variables and Lagrange multiplers. % een = ones(n,1); eem = ones(m,1); epsi = 1; epsvecn = epsi*een; epsvecm = epsi*eem; x = 0.5*(alfa+beta); y = eem; z = 1; lam = eem; xsi = een./(x-alfa); xsi = max(xsi,een); eta = een./(beta-x); eta = max(eta,een); mu = max(eem,0.5*c); zet = 1; s = eem; itera = 0; while epsi > epsimin epsvecn = epsi*een; epsvecm = epsi*eem; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; uxinv1 = een./ux1; xlinv1 = een./xl1; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; dpsidx = plam./ux2 - qlam./xl2 ; rex = dpsidx - xsi + eta; rey = c + d.*y - mu - lam; rez = a0 - zet - a'*lam; relam = gvec - a*z - y + s - b; rexsi = xsi.*(x-alfa) - epsvecn; reeta = eta.*(beta-x) - epsvecn; remu = mu.*y - epsvecm; rezet = zet*z - epsi; res = lam.*s - epsvecm; residu1 = [rex' rey' rez]'; residu2 = [relam' rexsi' reeta' remu' rezet res']'; residu = [residu1' residu2']'; residunorm = sqrt(residu'*residu); residumax = max(abs(residu)); ittt = 0; while residumax > 0.9*epsi & ittt < 200 ittt=ittt + 1; itera=itera + 1; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; ux3 = ux1.*ux2; xl3 = xl1.*xl2; uxinv1 = een./ux1; xlinv1 = een./xl1; uxinv2 = een./ux2; xlinv2 = een./xl2; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; GG = P*spdiags(uxinv2,0,n,n) - Q*spdiags(xlinv2,0,n,n); dpsidx = plam./ux2 - qlam./xl2 ; delx = dpsidx - epsvecn./(x-alfa) + epsvecn./(beta-x); dely = c + d.*y - lam - epsvecm./y; delz = a0 - a'*lam - epsi/z; dellam = gvec - a*z - y - b + epsvecm./lam; diagx = plam./ux3 + qlam./xl3; diagx = 2*diagx + xsi./(x-alfa) + eta./(beta-x); diagxinv = een./diagx; diagy = d + mu./y; diagyinv = eem./diagy; diaglam = s./lam; diaglamyi = diaglam+diagyinv; if m < n blam = dellam + dely./diagy - GG*(delx./diagx); bb = [blam' delz]'; Alam = spdiags(diaglamyi,0,m,m) + GG*spdiags(diagxinv,0,n,n)*GG'; AA = [Alam a a' -zet/z ]; solut = AA\bb; dlam = solut(1:m); dz = solut(m+1); dx = -delx./diagx - (GG'*dlam)./diagx; else diaglamyiinv = eem./diaglamyi; dellamyi = dellam + dely./diagy; Axx = spdiags(diagx,0,n,n) + GG'*spdiags(diaglamyiinv,0,m,m)*GG; azz = zet/z + a'*(a./diaglamyi); axz = -GG'*(a./diaglamyi); bx = delx + GG'*(dellamyi./diaglamyi); bz = delz - a'*(dellamyi./diaglamyi); AA = [Axx axz axz' azz ]; bb = [-bx' -bz]'; solut = AA\bb; dx = solut(1:n); dz = solut(n+1); dlam = (GG*dx)./diaglamyi - dz*(a./diaglamyi) + dellamyi./diaglamyi; end % dy = -dely./diagy + dlam./diagy; dxsi = -xsi + epsvecn./(x-alfa) - (xsi.*dx)./(x-alfa); deta = -eta + epsvecn./(beta-x) + (eta.*dx)./(beta-x); dmu = -mu + epsvecm./y - (mu.*dy)./y; dzet = -zet + epsi/z - zet*dz/z; ds = -s + epsvecm./lam - (s.*dlam)./lam; xx = [ y' z lam' xsi' eta' mu' zet s']'; dxx = [dy' dz dlam' dxsi' deta' dmu' dzet ds']'; % stepxx = -1.01*dxx./xx; stmxx = max(stepxx); stepalfa = -1.01*dx./(x-alfa); stmalfa = max(stepalfa); stepbeta = 1.01*dx./(beta-x); stmbeta = max(stepbeta); stmalbe = max(stmalfa,stmbeta); stmalbexx = max(stmalbe,stmxx); stminv = max(stmalbexx,1); steg = 1/stminv; % xold = x; yold = y; zold = z; lamold = lam; xsiold = xsi; etaold = eta; muold = mu; zetold = zet; sold = s; % itto = 0; resinew = 2*residunorm; while resinew > residunorm & itto < 50 itto = itto+1; x = xold + steg*dx; y = yold + steg*dy; z = zold + steg*dz; lam = lamold + steg*dlam; xsi = xsiold + steg*dxsi; eta = etaold + steg*deta; mu = muold + steg*dmu; zet = zetold + steg*dzet; s = sold + steg*ds; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; uxinv1 = een./ux1; xlinv1 = een./xl1; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; dpsidx = plam./ux2 - qlam./xl2 ; rex = dpsidx - xsi + eta; rey = c + d.*y - mu - lam; rez = a0 - zet - a'*lam; relam = gvec - a*z - y + s - b; rexsi = xsi.*(x-alfa) - epsvecn; reeta = eta.*(beta-x) - epsvecn; remu = mu.*y - epsvecm; rezet = zet*z - epsi; res = lam.*s - epsvecm; residu1 = [rex' rey' rez]'; residu2 = [relam' rexsi' reeta' remu' rezet res']'; residu = [residu1' residu2']'; resinew = sqrt(residu'*residu); steg = steg/2; end residunorm=resinew; residumax = max(abs(residu)); steg = 2*steg; end if ittt > 198 epsi ittt end epsi = 0.1*epsi; end xmma = x; ymma = y; zmma = z; lamma = lam; xsimma = xsi; etamma = eta; mumma = mu; zetmma = zet; smma = s; %-------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
asymp.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/asymp.m
1,193
utf_8
01768c819421ea53bdf0e3d04846acc3
%--------------------------------------------------------------------- % This is the file asymp.m. Version August 2007. % Written by Krister Svanberg <[email protected]>. % % Values on the parameters raa0, raa, low and upp are % calculated in the beginning of each outer iteration. % function [low,upp,raa0,raa] = ... asymp(outeriter,n,xval,xold1,xold2,xmin,xmax,low,upp, ... raa0,raa,raa0eps,raaeps,df0dx,dfdx); % eeen=ones(n,1); xmami = xmax - xmin; xmamieps = 0.00001*eeen; xmami = max(xmami,xmamieps); raa0 = abs(df0dx)'*xmami; raa0 = max(raa0eps,(0.1/n)*raa0); raa = abs(dfdx)*xmami; raa = max(raaeps,(0.1/n)*raa); if outeriter < 2.5 low = xval - 0.5*xmami; upp = xval + 0.5*xmami; else xxx = (xval-xold1).*(xold1-xold2); factor = eeen; factor(find(xxx > 0)) = 1.2; factor(find(xxx < 0)) = 0.7; low = xval - factor.*(xold1 - low); upp = xval + factor.*(upp - xold1); lowmin = xval - 10*xmami; lowmax = xval - 0.01*xmami; uppmin = xval + 0.01*xmami; uppmax = xval + 10*xmami; low = max(low,lowmin); low = min(low,lowmax); upp = min(upp,uppmax); upp = max(upp,uppmin); end %---------------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
beam1.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/beam1.m
820
utf_8
5aba330cf745ee4f38280eb2092fb9a4
%--------------------------------------------------------------------- % This is the file beam1.m. Version April 2007. % Written by Krister Svanberg <[email protected]>. % It calculates function values (but no gradients) % for the "beam problem" from the MMA paper. % % minimize 0.0624*(x(1) + x(2) + x(3) + x(4) + x(5)) % subject to 61/(x(1)^3) + 37/(x(2)^3) + 19/(x(3)^3) + % 7/(x(4)^3) + 1/(x(5)^3) =< 1, % 1 =< x(j) =< 10, for j=1,..,5. % (the bounds on x(j) are defined in gcbeaminit.m) % function [f0val,fval] = beam1(xval); % nx = 5; eeen = ones(nx,1); c1 = 0.0624; c2 = 1; aaa = [61 37 19 7 1]'; xval2 = xval.*xval; xval3 = xval2.*xval; xinv3 = eeen./xval3; f0val=c1*eeen'*xval; fval = aaa'*xinv3-c2; %---------------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
raaupdate.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/raaupdate.m
1,207
utf_8
915f622afb986a8f398908bf83e38780
%--------------------------------------------------------------------- % This is the file raaupdate.m. Version April 2007. % Written by Krister Svanberg <[email protected]>. % % Values of the parameters raa0 and raa are updated % during an inner iteration. % function [raa0,raa] = ... raaupdate(xmma,xval,xmin,xmax,low,upp,f0valnew,fvalnew, ... f0app,fapp,raa0,raa,raa0eps,raaeps,epsimin); % raacofmin = 10^(-12); eeem = ones(size(raa)); eeen = ones(size(xmma)); xmami = xmax-xmin; xmamieps = 0.00001*eeen; xmami = max(xmami,xmamieps); xxux = (xmma-xval)./(upp-xmma); xxxl = (xmma-xval)./(xmma-low); xxul = xxux.*xxxl; ulxx = (upp-low)./xmami; raacof = xxul'*ulxx; raacof = max(raacof,raacofmin); % f0appe = f0app + 0.5*epsimin; if f0valnew > f0appe deltaraa0 = (1/raacof)*(f0valnew-f0app); zz0 = 1.1*(raa0 + deltaraa0); zz0 = min(zz0,10*raa0); % zz0 = min(zz0,1000*raa0); raa0 = zz0; end % fappe = fapp + 0.5*epsimin*eeem; fdelta = fvalnew-fappe; deltaraa = (1/raacof)*(fvalnew-fapp); zzz = 1.1*(raa + deltaraa); zzz = min(zzz,10*raa); %zzz = min(zzz,1000*raa); raa(find(fdelta > 0)) = zzz(find(fdelta > 0)); %---------------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
beam2.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/beam2.m
912
utf_8
2ebb5f82c752ffaa71d6789a0f6ad30d
%--------------------------------------------------------------------- % This is the file beam2.m. Version April 2007. % Written by Krister Svanberg <[email protected]>. % It calculates function values and gradients % for the "beam problem" from the MMA paper. % % minimize 0.0624*(x(1) + x(2) + x(3) + x(4) + x(5)) % subject to 61/(x(1)^3) + 37/(x(2)^3) + 19/(x(3)^3) + % 7/(x(4)^3) + 1/(x(5)^3) =< 1, % 1 =< x(j) =< 10, for j=1,..,5. % (the bounds on x(j) are defined in gcbeaminit.m) % function [f0val,df0dx,fval,dfdx] = beam2(xval); % nx = 5; eeen = ones(nx,1); c1 = 0.0624; c2 = 1; aaa = [61 37 19 7 1]'; xval2 = xval.*xval; xval3 = xval2.*xval; xval4 = xval2.*xval2; xinv3 = eeen./xval3; xinv4 = eeen./xval4; f0val=c1*eeen'*xval; df0dx = c1*eeen; fval = aaa'*xinv3-c2; dfdx = -3*(aaa.*xinv4)'; %---------------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
gcmmasub.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/gcmmasub.m
1,891
utf_8
381682bb5be9cd604f40a94b69786387
%--------------------------------------------------------------------- % This is the file gcmmasub.m. Version Feb 2008. % Written by Krister Svanberg <[email protected]>. % function [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,f0app,fapp] = ... gcmmasub(m,n,iter,epsimin,xval,xmin,xmax,low,upp, ... raa0,raa,f0val,df0dx,fval,dfdx,a0,a,c,d); % eeen = ones(n,1); zeron = zeros(n,1); % % Calculations of the bounds alfa and beta. % albefa = 0.1; zzz = low + albefa*(xval-low); alfa = max(zzz,xmin); zzz = upp - albefa*(upp-xval); beta = min(zzz,xmax); % % Calculations of p0, q0, r0, P, Q, r and b. xmami = xmax-xmin; xmamieps = 0.00001*eeen; xmami = max(xmami,xmamieps); xmamiinv = eeen./xmami; ux1 = upp-xval; ux2 = ux1.*ux1; xl1 = xval-low; xl2 = xl1.*xl1; uxinv = eeen./ux1; xlinv = eeen./xl1; % p0 = zeron; q0 = zeron; p0 = max(df0dx,0); q0 = max(-df0dx,0); %p0(find(df0dx > 0)) = df0dx(find(df0dx > 0)); %q0(find(df0dx < 0)) = -df0dx(find(df0dx < 0)); pq0 = p0 + q0; p0 = p0 + 0.001*pq0; q0 = q0 + 0.001*pq0; p0 = p0 + raa0*xmamiinv; q0 = q0 + raa0*xmamiinv; p0 = p0.*ux2; q0 = q0.*xl2; r0 = f0val - p0'*uxinv - q0'*xlinv; % P = sparse(m,n); Q = sparse(m,n); P = max(dfdx,0); Q = max(-dfdx,0); %P(find(dfdx > 0)) = dfdx(find(dfdx > 0)); %Q(find(dfdx < 0)) = -dfdx(find(dfdx < 0)); PQ = P + Q; P = P + 0.001*PQ; Q = Q + 0.001*PQ; P = P + raa*xmamiinv'; Q = Q + raa*xmamiinv'; P = P * spdiags(ux2,0,n,n); Q = Q * spdiags(xl2,0,n,n); r = fval - P*uxinv - Q*xlinv; b = -r; % % Solving the subproblem by a primal-dual Newton method [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s] = ... subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d); % % Calculations of f0app and fapp. ux1 = upp-xmma; xl1 = xmma-low; uxinv = eeen./ux1; xlinv = eeen./xl1; f0app = r0 + p0'*uxinv + q0'*xlinv; fapp = r + P*uxinv + Q*xlinv; % %---------------------------------------------------------------------
github
MAS-dfab/T1_python-exercises-master
concheck.m
.m
T1_python-exercises-master/07_ur_online/shifted_frames_setup/compas/src/compas/numerical/solvers/_mma/concheck.m
563
utf_8
1af2a5bbf88f34d8f970d1818af498f4
%--------------------------------------------------------------------- % This is the file concheck.m. Version April 2007. % Written by Krister Svanberg <[email protected]>. % % If the current approximations are conservative, % the parameter conserv is set to 1. % function [conserv] = ... concheck(m,epsimin,f0app,f0valnew,fapp,fvalnew); % conserv = 0; eeem = ones(m,1); f0appe = f0app+epsimin; fappe = fapp+epsimin*eeem; if [f0appe,fappe'] >= [f0valnew,fvalnew'] conserv = 1; end %---------------------------------------------------------------------
github
EhomeBurning/Machine-Learning-master
KernelDensity.m
.m
Machine-Learning-master/project/Code/KernelDensity.m
703
utf_8
53710e1313c12cb83a929cde5c53661b
%% 2-D kernel density % last modified on 2011-09-24 function [p_Y p_grid] = KernelDensity(Y, h, is_grid, grid) % Y: 2 by n data matrix % h: bandwidth % grid: 2 by k array, the (grid) points of output % p_Y: the estimated density at the data points % p_grid: estimated density at grid points n = size(Y, 2); n_grid = size(grid, 2); p_Y = zeros(1, n); S = h^2*eye(2); for i = 1:n p_Y(i) = mean(mvnpdf(Y', Y(:, i)', S)); end if is_grid p_1 = zeros(n_grid, n); p_2 = p_1; for i =1:n_grid p_1(i, :) = normpdf(Y(1, :), grid(1, i), h); p_2(i, :) = normpdf(Y(2, :), grid(2, i), h); end p_grid = p_1 * p_2' / n; end end
github
EhomeBurning/Machine-Learning-master
conformal.m
.m
Machine-Learning-master/project/Code/Sample_Code/conformal.m
756
utf_8
ea26d6ff6143e021795fa9d63636670d
%% conformal prediction region % last modified on 2011-09-23 function conf_set = conformal(Y, h, grid, alpha) % Y: 2 by n data matrix % h: bandwidth % grid: 2 by n_grid coordinate grids % alpha: level n = size(Y, 2); n_grid = size(grid, 2); conf_set = zeros(n_grid, n_grid); p_value = conf_set; [p_Y p_grid] = KernelDensity(Y, h, 1, grid); S = h^2 * eye(2); K_0 = mvnpdf([0, 0], [0, 0], S); for i = 1:n_grid for j = 1:n_grid y = [grid(1, i), grid(2, j)]'; p_y = n/(n+1) * p_grid(i, j) + K_0/(n+1); p_y_Y = n/(n+1) * p_Y + 1/(n+1) * mvnpdf(Y', y', S)'; p_value(i, j) = (sum(p_y_Y <= p_y) + 1) / (n+1); end end conf_set = (p_value >= alpha); end
github
EhomeBurning/Machine-Learning-master
KernelDensity.m
.m
Machine-Learning-master/project/Code/Sample_Code/KernelDensity.m
703
utf_8
53710e1313c12cb83a929cde5c53661b
%% 2-D kernel density % last modified on 2011-09-24 function [p_Y p_grid] = KernelDensity(Y, h, is_grid, grid) % Y: 2 by n data matrix % h: bandwidth % grid: 2 by k array, the (grid) points of output % p_Y: the estimated density at the data points % p_grid: estimated density at grid points n = size(Y, 2); n_grid = size(grid, 2); p_Y = zeros(1, n); S = h^2*eye(2); for i = 1:n p_Y(i) = mean(mvnpdf(Y', Y(:, i)', S)); end if is_grid p_1 = zeros(n_grid, n); p_2 = p_1; for i =1:n_grid p_1(i, :) = normpdf(Y(1, :), grid(1, i), h); p_2(i, :) = normpdf(Y(2, :), grid(2, i), h); end p_grid = p_1 * p_2' / n; end end
github
JamesLinus/jbuilder-universe-master
dist.m
.m
jbuilder-universe-master/packages/gpr.1.3.1/test/dist.m
303
utf_8
1a5d8db3738957a2eba64e1597bff7bb
% Part of Ed Snelson's SPGP distribution function D = dist(x0,x1) % dist: compute pairwise distance matrix from two column vectors x0 and x1 warning(['To speed up gradient calculation compile mex' ... ' file dist.c']) n0 = length(x0); n1 = length(x1); D = repmat(x0,1,n1)-repmat(x1',n0,1);
github
JamesLinus/jbuilder-universe-master
oct.m
.m
jbuilder-universe-master/packages/gpr.1.3.1/test/oct.m
4,062
utf_8
52e56ba744ec1e09ea8f81bb2bcecde8
% Octave script for testing Gaussian process regression results % % Copyright (C) 2009- Markus Mottl % email: [email protected] % WWW: http://www.ocaml.info format long global log_sf2; load data/inputs load data/targets load data/inducing_points load data/sigma2 load data/log_ell load data/log_sf2 global epsilon = 1e-6; sigma = sqrt(sigma2); global log_sf2 = log_sf2; global log_sf2_e = log_sf2 + epsilon; global inv_ell2 = exp(-2 * log_ell); global inv_ell2_e = exp(-2*(log_ell + epsilon)); log_inv_ell2 = log(inv_ell2); [dim, N] = size(inputs); [dim, M] = size(inducing_points); function res = eval_rbf2(r2, a, b) res = exp(a + -0.5 * b * r2); end function res = kf(x, y, a, b) [dim, n1] = size(x); n2 = size(y, 2); r2 = repmat(sum(x' .* x', 2), 1, n2) - 2 * x' * y + repmat(sum(y' .* y', 2)', n1, 1); res = eval_rbf2(r2, a, b); [dim, N] = size(res); if (dim == N) jitter = 1e-6; res = res + jitter*eye(N); endif res = res'; end function res = k(x, y) global log_sf2 inv_ell2; res = kf(x, y, log_sf2, inv_ell2); end function res = k_e(x, y) global log_sf2 log_sf2_e inv_ell2 inv_ell2_e epsilon; res = kf(x, y, log_sf2, inv_ell2_e); end function res = kf_diag(x, a, b) r2 = zeros(size(x, 2), 1); res = eval_rbf2(r2, a, b); end function res = k_diag(x) global log_sf2 inv_ell2; res = kf_diag(x, log_sf2, inv_ell2); end function res = k_diag_e(x) global log_sf2 log_sf2_e inv_ell2 inv_ell2_e epsilon; res = kf_diag(x, log_sf2, inv_ell2_e); end %%%%%%%%%%%%%%%%%%%% Covariance matrices %%%%%%%%%%%%%%%%%%%% Km = k(inducing_points, inducing_points); Km_e = k_e(inducing_points, inducing_points); dKm = (Km_e - Km) / epsilon; Knm = k(inducing_points, inputs); Knm_e = k_e(inducing_points, inputs); dKnm = (Knm_e - Knm) / epsilon; Kn_diag = k_diag(inputs); Kn_e_diag = k_diag_e(inputs); dKn_diag = (Kn_e_diag - Kn_diag) / epsilon; %%%%%%%%%%%%%%%%%%%% Main definitions %%%%%%%%%%%%%%%%%%%% y = targets; cholKm = chol(Km); V = Knm / cholKm; r = Kn_diag - sum(V .^ 2, 2); s = r + sigma2; is = ones(size(s, 1), 1) ./ s; is_2 = sqrt(is); inv_lam_sigma = repmat(is_2, 1, size(Knm, 2)); Knm_ = inv_lam_sigma .* Knm; [Q, R] = qr([Knm_; chol(Km)], 1); SF = diag(sign(diag(R))); Q = Q(1:N,1:end)*SF; R = SF*R; S = inv_lam_sigma .* Q / R'; B = Km + Knm_' * Knm_; %%%%%%%%%%%%%%%%%%%% Standard %%%%%%%%%%%%%%%%%%%% %%%%%% Log evidence l1 = ... -0.5*(... 2*sum(log(diag(R))) - 2*sum(log(diag(cholKm))) + sum(log(s)) ... + N * log(2*pi)) y_ = is_2 .* y; t = S'*y; u = y_ - Q*(Q'*y_); l2 = -0.5*(u'*y_) l = l1 + l2 %%%%%% Log evidence derivative T = inv(Km) - inv(B); U = V / cholKm'; v1 = is .* (ones(size(Q, 1), 1) - sum(Q .^ 2, 2)); U1 = repmat(sqrt(v1), 1, size(U, 2)) .* U; W1 = T - U1'*U1; X1 = S - repmat(v1, 1, size(U, 2)) .* U; dl1 = -0.5*(v1' * dKn_diag - trace(W1'*dKm)) - trace(X1'*dKnm) w = is_2 .* u; v2 = w .* w; U2 = repmat(w, 1, size(U, 2)) .* U; W2 = t*t' - U2'*U2; X2 = w*t' - repmat(v2, 1, size(U, 2)) .* U; dl2 = 0.5*(v2' * dKn_diag - trace(W2'*dKm)) + trace(X2'*dKnm) dl = dl1 + dl2 %%%%%% Log evidence derivative wrt. noise dls1 = -0.5*sum(v1) dls2 = 0.5*sum(v2) dls = dls1 + dls2 %%%%%%%%%%%%%%%%%%%% Variational %%%%%%%%%%%%%%%%%%%% %%%%%% Log evidence vl1 = l1 + -0.5*is'*r vl = vl1 + l2 %%%%%% Log evidence derivative vv1 = is .* (2*ones(size(Q, 1), 1) - is .* r - sum(Q .* 2, 2)); vU1 = repmat(sqrt(vv1), 1, size(U, 2)) .* U; vW1 = T - vU1'*vU1; vX1 = S - repmat(vv1, 1, size(U, 2)) .* U; vdl1 = -0.5*(vv1' * dKn_diag - trace(vW1'*dKm)) - trace(vX1'*dKnm) vdl = vdl1 + dl2 %%%%%% Log evidence derivative wrt. noise vdls1 = -0.5*(sum(vv1) - sum(is)) vdls = vdls1 + dls2 %%%%%%%%%%%%%%%%%%%%%%%%% Ed Snelson's stuff %%%%%%%%%%%%%%%%%%%%%%%%% hyp = [log_inv_ell2; log_sf2; log(sigma2)]; ew = [reshape(inducing_points', M*dim, 1); hyp]; [eds_neg_log_likelihood, dfw] = spgp_lik(ew, y, inputs', M); eds_evidence = -eds_neg_log_likelihood eds_dlog_ell = -(-dfw(end - 2) * 2) eds_dlog_sf2 = -dfw(end - 1) eds_dsigma2 = -dfw(end) / sigma2
github
JamesLinus/jbuilder-universe-master
spgp_lik.m
.m
jbuilder-universe-master/packages/gpr.1.3.1/test/spgp_lik.m
3,008
utf_8
7485b4c80e18947f8f12a41b93b8e14c
% Edward Snelson's SPGP implementation in Octave/Matlab function [fw,dfw] = spgp_lik(w,y,x,n,del) % spgp_lik_3: neg. log likelihood for SPGP and gradients with respect to % pseudo-inputs and hyperparameters. Gaussian covariance with one % lengthscale per dimension. % % y -- training targets (N x 1) % x -- training inputs (N x dim) % n -- number of pseudo-inputs % w -- parameters = [reshape(xb,n*dim,1); hyp] % % hyp -- hyperparameters (dim+2 x 1) % hyp(1:dim) = log( b ) % hyp(dim+1) = log( c ) % hyp(dim+2) = log( sig ) % % where cov = c * exp[-0.5 * sum_d b_d * (x_d - x'_d)^2] % + sig * delta(x,x') % % xb -- pseudo-inputs (n*dim) % % del -- OPTIONAL jitter (default 1e-6) % % fw -- likelihood % dfw -- OPTIONAL gradients % % Edward Snelson (2006) if nargin < 5; del = 1e-6; end % default jitter [N,dim] = size(x); xb = reshape(w(1:end-dim-2),n,dim); b = exp(w(end-dim-1:end-2)); c = exp(w(end-1)); sig = exp(w(end)); xb = xb.*repmat(sqrt(b)',n,1); x = x.*repmat(sqrt(b)',N,1); Q = xb*xb'; Q = repmat(diag(Q),1,n) + repmat(diag(Q)',n,1) - 2*Q; Q = c*exp(-0.5*Q) + del*eye(n); K = -2*xb*x' + repmat(sum(x.*x,2)',n,1) + repmat(sum(xb.*xb,2),1,N); K = c*exp(-0.5*K); L = chol(Q)'; V = L\K; ep = 1 + (c-sum(V.^2)')/sig; K = K./repmat(sqrt(ep)',n,1); V = V./repmat(sqrt(ep)',n,1); y = y./sqrt(ep); Lm = chol(sig*eye(n) + V*V')'; invLmV = Lm\V; bet = invLmV*y; % Likelihood fw = sum(log(diag(Lm))) + (N-n)/2*log(sig) + ... (y'*y - bet'*bet)/2/sig + sum(log(ep))/2 + 0.5*N*log(2*pi); % OPTIONAL derivatives if nargout > 1 % precomputations Lt = L*Lm; B1 = Lt'\(invLmV); b1 = Lt'\bet; invLV = L'\V; invL = inv(L); invQ = invL'*invL; clear invL invLt = inv(Lt); invA = invLt'*invLt; clear invLt mu = ((Lm'\bet)'*V)'; sumVsq = sum(V.^2)'; clear V bigsum = y.*(bet'*invLmV)'/sig - sum(invLmV.*invLmV)'/2 - (y.^2+mu.^2)/2/sig ... + 0.5; TT = invLV*(invLV'.*repmat(bigsum,1,n)); % pseudo inputs and lengthscales for i = 1:dim % dnnQ = (repmat(xb(:,i),1,n)-repmat(xb(:,i)',n,1)).*Q; % dNnK = (repmat(x(:,i)',n,1)-repmat(xb(:,i),1,N)).*K; dnnQ = dist(xb(:,i),xb(:,i)).*Q; dNnK = dist(-xb(:,i),-x(:,i)).*K; epdot = -2/sig*dNnK.*invLV; epPmod = -sum(epdot)'; dfxb(:,i) = - b1.*(dNnK*(y-mu)/sig + dnnQ*b1) ... + sum((invQ - invA*sig).*dnnQ,2) ... + epdot*bigsum - 2/sig*sum(dnnQ.*TT,2); dfb(i,1) = (((y-mu)'.*(b1'*dNnK))/sig ... + (epPmod.*bigsum)')*x(:,i); dNnK = dNnK.*B1; % overwrite dNnK dfxb(:,i) = dfxb(:,i) + sum(dNnK,2); dfb(i,1) = dfb(i,1) - sum(dNnK,1)*x(:,i); dfxb(:,i) = dfxb(:,i)*sqrt(b(i)); dfb(i,1) = dfb(i,1)/sqrt(b(i)); dfb(i,1) = dfb(i,1) + dfxb(:,i)'*xb(:,i)/b(i); dfb(i,1) = dfb(i,1)*sqrt(b(i))/2; end % size epc = (c./ep - sumVsq - del*sum((invLV).^2)')/sig; dfc = (n + del*trace(invQ-sig*invA) ... - sig*sum(sum(invA.*Q')))/2 ... - mu'*(y-mu)/sig + b1'*(Q-del*eye(n))*b1/2 ... + epc'*bigsum; % noise dfsig = sum(bigsum./ep); dfw = [reshape(dfxb,n*dim,1);dfb;dfc;dfsig]; end
github
s-guenther/hybrid-master
rand_signal.m
.m
hybrid-master/sample/rand_signal.m
6,001
utf_8
be8f1061458ada6dfdbf9be2af2b302e
function [signal, seed] = rand_signal(varargin) % RAND_SIGNAL generates a random signal satisfying energy constraints % % Generates a random signal of type 'fhandle', which has an integral % function which starts at zero, never becomes negative, and ends at % zero. Signal is reproduceable by specifying the seed of the random % generator. Various options for shaping amplitude, period, harmonics, % roughness. % % [signal, seed] = RAND_SIGNAL(<opt>, <seed>, ... % <roughness>, <n_harmonics>, ... % <high_harmonic>, <rel_mu>) % % Input: % opt optional, default hybridset() % seed optional, default 'shuffle', integer number for % random generator % roughness optional, default 2*rand(), abstract measure for % fluctuations in signal, if passed as vector, use this % specific roughness for each frequency. Size must be % equal to n_harmonics or length(n_harmonics), % respectively. % n_harmonics optional, default randi([2,8]), integer, number of % harmonics in signal option: if vector is passed, use % this specific harmonics instead of generating them % randomly % high_harmonic optional, default randi([30, 300]), highest occouring % harmonic in signal superflous if vector is passed in % n_harmonics % rel_mu optional, default 2*rand(), fraction of the expected % rectified mean value the signal is shifted upwards % DEFERRED: % symmetric optional, default 0, boolean, if true: discharge side % is point symmmetric to charge site % zerosections optional, default 0, specifies the percentage of % time where the signal is zero % period optional, default 2*pi, length of period % amplitude optional, default 1, maximum peak (positive or % negative) % % Output: % signal signal struct, see GEN_SIGNAL % seed random seed to reproduce the obtained signal with % this function % % The last 3 parameters do not alternate the random generation of the % signal, rather they stretch/compress the beforehand randomly generated % signal. % % Parameters symmetric, zerosections, period, amplitude are DEFERRED and % not implemented at the moment % % CAUTION: Sets the matlab random generator to rng('shuffle', twister) at % the end of the algorithm. % % See also GEN_SIGNAL, PULSED_SIGNAL. if nargin < 1 warning(['Executing function without specifying options ', ... 'structure. As the default options are relatively ', ... 'strict, it may take some time to calculate a valid ' , ... 'signal']) end if nargin < 2 n_try = 0; while n_try <= 9 n_try = n_try + 1; try [signal, seed] = rand_signal_calculation(varargin{:}); break catch err if strfind(err.identifier, 'HYBRID') disp([num2str(n_try) '. try failed, trying again... ', ... '(abort at 10)']) else rethrow(err) end end end else [signal, seed] = rand_signal_calculation(varargin{:}); end end %% Local Functions function [signal, seed] = rand_signal_calculation(opt, seed, roughness, ... n_harmonics, high_harmonic, rel_mu) if nargin < 1 opt = hybridset(); end if nargin < 2 || strcmpi(seed, 'shuffle') rng('shuffle', 'twister'); seed = randi(9e6); end % initialize random generator rng(seed, 'twister'); if nargin < 3 roughness = 2*rand(); end if nargin < 4 n_harmonics = randi([2, 8]); end if nargin < 5 high_harmonic = randi([30, 300]); end if nargin < 6 rel_mu = 2*rand(); end % if nargin < 7 % symmetric = 0; % end % if nargin < 8 % zerosections = 0; % end if nargin < 9 period = 2*pi; end if nargin < 10 amplitude = 1; end % set expected charge duration Tp = 100; Tc = ceil(Tp*(0.7*rand() + 0.15)); % Set frequency and amplitudes of harmonics if length(n_harmonics) > 1 harmonics = n_harmonics; else harmonics = [sort(randi([2 high_harmonic-1], 1, n_harmonics - 1)), ... high_harmonic]; end if length(roughness) > 1 amp_harm = roughness; else amp_harm = abs(1 + roughness.*randn(size(harmonics))); end %% generate base signal and add harmonics iteratively mean_gauss = sqrt(2/pi); mu = rel_mu*mean(amp_harm)*mean_gauss; base_sig = @(t) mu.*(t <= Tc) + -mu*(Tc)/(Tp-Tc).*(t > Tc); for ii = 1:length(harmonics) n_points = 4*harmonics(ii) + 1; points = [0, (1:(n_points-2)) + (rand(1, n_points-2)-0.5), n_points]*4*Tp/n_points; vals = base_sig(points) + randn(1, n_points)*amp_harm(ii); base_sig = @(t) interp1(points, vals, t, 'pchip'); end %% integrate signal, add mu_top, mu_bot, cut exceeding vals [tout, yout] = ode45(@(t,y) base_sig(t), [0 4*Tp], 0, ... odeset('RelTol', 1e-5)); energy = @(tt) interp1(tout, yout, tt, 'spline'); time = linspace(0, tout(end), 10*length(tout))'; % filter energy exceedings; cut_low = 0; cut_top = inf; power = base_sig(time); power = power(energy(time) > cut_low & energy(time) < cut_top); dtime = [0; diff(time)]; dtime = dtime(energy(time) > cut_low & energy(time) < cut_top); time = cumsum(dtime); % determine max amplitude real_amplitude = max(abs(power)); real_period = time(end); fcn = @(t) interp1(period/real_period*time, ... amplitude/real_amplitude*power, ... t, ... 'pchip'); % to ensure fresh numbers for further calculations within matlab rng('shuffle', 'twister'); signal = gen_signal(fcn, period, opt); end%mainfcn
github
s-guenther/hybrid-master
parse_gen_storages_input.m
.m
hybrid-master/src/_gen_storages/parse_gen_storages_input.m
2,561
utf_8
df9d6a4c4d7cdd50e5b3274370b9027f
function [prices, names, opt] = parse_gen_storages_input(spec_powers, ... varargin) % Checks input data of gen_storages if types/classes are correct and % consistent if nargin == 1 opt = hybridset(); prices = make_prices(spec_powers); names = make_names(spec_powers); end if nargin == 2 if ishybridset(varargin{1}) opt = varargin{1}; prices = make_prices(spec_powers); names = make_names(spec_powers); elseif isnumeric(varargin{1}) && isvector(varargin{1}) opt = hybridset(); prices = varargin{1}; names = make_names(spec_powers); elseif iscell(varargin{1}) opt = hybridset(); prices = make_prices(spec_powers); names = varargin{1}; else error('HYBRID:stor:invalid_input', ... 'Invalid 2nd input') end end if nargin == 3 if isnumeric(varargin{1}) && isvector(varargin{1}) prices = varargin{1}; if ishybridset(varargin{2}) opt = varargin{2}; names = make_names(spec_powers); elseif iscell(varargin{2}) opt = hybridset(); names = varargin{2}; else error('HYBRID:stor:invalid_input', ... 'Invalid 3rd input') end else error('HYBRID:stor:invalid_input', ... 'Invalid 2nd input') end end if nargin == 4 if isnumeric(varargin{1}) && isvector(varargin{1}) prices = varargin{1}; if iscell(varargin{2}) names = varargin{2}; if ishybridset(varargin{3}) opt = varargin{3}; else error('HYBRID:stor:invalid_input', ... 'Invalid 4th input') end else error('HYBRID:stor:invalid_input', ... 'Invalid 3rd input') end else error('HYBRID:stor:invalid_input', ... 'Invalid 2nd input') end end if nargin > 4 error('HYBRID:stor:invalid_input', ... 'Too many input arguments') end assert(length(prices) == length(spec_powers), ... 'number of spec_powers and prices differ') assert(length(names) == length(spec_powers), ... 'number of spec_powers and names differ') end %% LOCAL FUNCTIONS function prices = make_prices(spec_powers) prices = 1 + spec_powers; end function names = make_names(spec_powers) names = cellfun(@num2str, num2cell(spec_powers), ... 'UniformOutput', false); end
github
s-guenther/hybrid-master
get_min_limits.m
.m
hybrid-master/src/_plot_eco/get_min_limits.m
2,110
utf_8
e24989e79984f8fd27062a8021bd16cf
function limits = get_min_limits(ecodata, dtype, opt) % GET_MIN_LIMITS determines power cut ranges for cheapest storage pair % % Determines the cheapest base/peak storage combination in power cut % bound. For each storage pair, a tuple of [lower bound, upper bound] is % determined. Output will be written to a cell array of vectors. % % LIMITS = GET_MIN_LIMITS(ECODATA, DTYPE) with ECODATA being the result % of ECO() and DTYPE being either 'cost', 'energy', 'power'. LIMITS is of % the same size as ECODATA. % % See also PLOT_ECO, PLOT_SPECIFIC_ECO_DATA. if nargin < 3 opt = hybridset(); end % TODO magic numbers that 1e-6 might be unstable cut = linspace(1e-3, 1 - 1e-3, opt.cut_sample)'; costs = zeros(length(cut), numel(ecodata)); % evaluate costs at points of cut for ii = 1:numel(ecodata) costs(:, ii) = ecodata(ii).both.(dtype)(cut); end % get cheapest storage pair for each point (index) [~, pair] = min(costs, [], 2); % get bounds [bounds, base, peak] = find_bounds(cut, pair, size(ecodata)); % write bounds to output limits = repmat({[]}, size(ecodata)); for ii = 1:size(bounds,1) limits{base(ii), peak(ii)} = [limits{base(ii), peak(ii)}; ... bounds(ii, :)]; end end%mainfcn %% LOCAL FCNS function [bounds, base, peak] = find_bounds(cut, pair, dimeco) bounds = []; base = []; peak = []; startcut = cut(1); currentpair = pair(1); for ii = 2:length(cut) thispair = pair(ii); if thispair == currentpair continue else endcut = cut(ii-1); bounds = [bounds; startcut, endcut]; %#ok [thisbase, thispeak] = ind2sub(dimeco, currentpair); base = [base; thisbase]; %#ok peak = [peak; thispeak]; %#ok currentpair = thispair; startcut = cut(ii); end end if startcut < 1-5e-2 % TODO eliminate magic number bounds = [bounds; startcut, 1]; [thisbase, thispeak] = ind2sub(dimeco, currentpair); base = [base; thisbase]; peak = [peak; thispeak]; end end
github
s-guenther/hybrid-master
verbose.m
.m
hybrid-master/src/miscellaneous/verbose.m
1,500
utf_8
c349da36cf4b896a2a179c858aac8daf
function verbose(trigger, level, message) % VERBOSE displays an information message if verbosity level is reached % % VERBOSE(TRIGGER, LEVEL, MESSAGE) displays the message MESSAGE if TRIGGER % is equal or higher LEVEL. It also adds a timestamp to the message and % indents it depending on LEVEL. % % With this, a simple verbosity level system can be built. A global % VERBOSITY variable can be defined. if it reaches the LEVEL of VERBOSE, % then the MESSAGE is shown, else it is ommited. % % Examples: % verbose(2, 1, 'This will be displayed.') % verbose(2, 2, 'This will also be displayed and indented.') % verbose(1, 2, 'This will not be displayed' % % See also FPRINTF. LINEWIDTH = 73; if trigger < level return end % Add timestamp message = [datestr(now(), 'HH:MM:SS.FFF'), ' - ', message]; % Wrap lines, max with is dependent on level % Indent whole message with 4 spaces for each level higher 1 messagecell = linewrap(message, LINEWIDTH - (level-1)*4); for ii = 1:length(messagecell) messagecell{ii} = [make_n_spaces((level-1)*4), messagecell{ii}]; end % Indent two additional spaces for lines proceeding the first line if length(messagecell) > 1 for ii = 2:length(messagecell) messagecell{ii} = [make_n_spaces(1), messagecell{ii}]; end end fprintf('%s\n', messagecell{:}) end % LOCAL FUNCTIONS function spaces = make_n_spaces(nn) spaces = ''; if nn == 0 return end for ii = 1:nn spaces = [spaces, ' ']; %#ok end end
github
s-guenther/hybrid-master
solve_fhandle_sdode.m
.m
hybrid-master/src/_hybrid/solve_fhandle_sdode.m
2,726
utf_8
02069b9840a254a1d8ec9fd952131e49
function [tout, yout] = solve_fhandle_sdode(build, decay, opt) % SOLVE_FHANDLE_SDODE specialized SDODE solver for function handles % % [TOUT, YOUT] = SOLVE_FHANDLE_SDODE(BUILD, DECAY, OPT) % % See also SOLVE_SDODE. odesol = opt.continuous_solver; ode = @(t, y) sdode(t, y, build.fcn, decay.fcn); [tout, yout] = odesol(ode, [0 build.period], 0, opt.odeset); end % LOCAL FUNCTIONS function dydt = sdode(t, y, build_fcn, decay_fcn, build_cond, decay_cond) % SDODE integrates build or decay fcn depending on build cond % % ODE where build_fcn is integrated if build_cond holds true and decay_fcn % is integrated if decay_cond holds true. % Default behaviour: integrate build fcn if it is positive, else reduce % integral with decay fcn % % Input: % t ode input arg time % y ode input arg state % build_fcn fcn handle, will be integrated if build_cond is true, % function of t % decay_fcn fcn handle, will be integrated if decay_cond is true, % function of t % build_cond optional, default: see below; % fcn handle, logical expression controlling build fcn, % function of t, y, build_val, decay_val % decay_cond optional, default: see below; % fcn handle, logical expression controlling decay fcn, % function of t, y, build_val, decay_val % Output: % dydt ode output arg derivative state % % default build_cond: true if build >= 0, % default decay_cond: true if build_cond == 0 & y > 0 & decay < 0 % % It is intended that only a maximum of one condition holds true. It is % possible to formulate conditions where both can be true. Then, the build % and decay will be superpositioned. The user is responsible for % formulating consistent build and decay conditions % % Code is vectorized. % % If function is called w/o parameters, the build and decay function will % be returned as a cell array of strings. These can be evaluated with % build_cond = eval(out{1}) and decay_cond = eval(out{2}) if nargin == 0 dydt = {'@(t, y, build_val, decay_val) build_val >= 0;'; '@(t, y, build_val, decay_val) build_val <= 0 & y > 0 & decay_val <= 0;'}; return end if nargin < 5 build_cond = @(t, y, build_val, decay_val) build_val > 0; end if nargin < 6 decay_cond = @(t, y, build_val, decay_val) build_val <= 0 & ... y > 0 & ... decay_val <= 0; end build_val = build_fcn(t); decay_val = decay_fcn(t); build_bool = build_cond(t, y, build_val, decay_val); decay_bool = decay_cond(t, y, build_val, decay_val); dydt = build_val.*build_bool + decay_val.*decay_bool; end
github
s-guenther/hybrid-master
solve_discrete_sdode.m
.m
hybrid-master/src/_hybrid/solve_discrete_sdode.m
6,206
utf_8
bdc51ac54646c42a9cd8ec124493d3ce
function [tout, yout] = solve_discrete_sdode(build, decay, opt) % SOLVE_DISCRETE_SDODE specialized SDODE solver for discrete fcns % % [TOUT, YOUT] = SOLVE_DISCRETE_SDODE(BUILD, DECAY, OPT) % % See also SOLVE_SDODE. % Allocate space for result vectors tout = zeros(2*length(build.val), 1); yout = zeros(2*length(build.val), 1); % Set solvers and other functions or vectors depending on fcn type 'step' % or 'linear' if strcmpi(build.type, 'step') % virtually add 0 at start to make vector size compatible to 'linear' times = [0; build.time]; sdode = @(ii, yy) discrete_sdode(ii, yy, ... [0; build.val], [0; decay.val]); int_one_step = @int_step_fcn; repair_int = @repair_step_int; elseif strcmpi(build.type, 'linear') times = build.time; sdode = @(ii, yy) discrete_sdode(ii, yy, build.val, decay.val); int_one_step = @int_linear_fcn; repair_int = @repair_linear_int; end % second control variable jj introduced as there may be steps in between % original steps in result vector (if peak storage runs empty in between a % timestep) start at 2 because initial condition is implicitly set to zero jj = 2; % Loop through integration for ii = 2:length(times) % allocate new space if needed if jj > length(tout) tout = [tout; zeros(size(tout))]; %#ok yout = [yout; zeros(size(yout))]; %#ok end % naive one-step integration tout(jj) = times(ii); yout(jj) = int_one_step(sdode, ii, tout(jj) - tout(jj-1), yout(jj-1)); % Repair result if integral gets negative if yout(jj) < 0 [tinter, yinter] = repair_int(tout(jj-1), tout(jj), ... yout(jj-1), yout(jj), ... sdode(ii-1, yout(jj-1)), ... sdode(ii, yout(jj))); tout(jj:jj+1) = tinter; yout(jj:jj+1) = yinter; jj = jj + 1; end jj = jj + 1; end % remove unneccessary allocation tout = tout(1:jj-1); yout = yout(1:jj-1); if strcmpi(opt.discrete_solver, 'time_preserving') warning('HYBRID:discrete_solver', ... 'Solver varaint ''exact'', not implemented at the moment') end end % LOCAL FUNCTIONS function dydt = discrete_sdode(ii, yy, build_vec, decay_vec, ... build_cond, decay_cond) % SDODE integrates build or decay fcn, discrete implementation % % ODE where build_fcn is integrated if build_cond holds true and decay_fcn % is integrated if decay_cond holds true. % Default behaviour: integrate build fcn if it is positive, else reduce % integral with decay fcn % % Input: % ii discrete step % y last value of integral % build_vec value vector of build function, will be integrated if % build_cond is true, function of step ii, implicitely of % time % decay_vec value vector of decay function, will be integrated if % decay_cond is true, function of step ii, implicitely of % time % decay_vec fcn handle, will be integrated if decay_cond is true, % function of t % build_cond optional, default: see below; % fcn handle, logical expression controlling build fcn, % function of t, y, build_val, decay_val % decay_cond optional, default: see below; % fcn handle, logical expression controlling decay fcn, % function of t, y, build_val, decay_val % Output: % dydt ode output arg derivative state % % default build_cond: true if build >= 0, % default decay_cond: true if build_cond == 0 & y > 0 & decay < 0 % % It is intended that only a maximum of one condition holds true. It is % possible to formulate conditions where both can be true. Then, the build % and decay will be superpositioned. The user is responsible for % formulating consistent build and decay conditions % % Code is vectorized. % % If function is called w/o parameters, the build and decay function will % be returned as a cell array of strings. These can be evaluated with % build_cond = eval(out{1}) and decay_cond = eval(out{2}) if nargin == 0 dydt = {'@(ii, yy, build_val, decay_val) build_val >= 0;'; ['@(ii, yy, build_val, decay_val) ', ... 'build_val <= 0 & yy > 0 & decay_val <= 0;']}; return end if nargin < 5 build_cond = @(ii, yy, build_val, decay_val) build_val > 0; end if nargin < 6 decay_cond = @(ii, yy, build_val, decay_val) ... build_val <= 0 & yy > 0 & decay_val <= 0; end build_val = build_vec(ii); decay_val = decay_vec(ii); build_bool = build_cond(ii, yy, build_val, decay_val); decay_bool = decay_cond(ii, yy, build_val, decay_val); dydt = build_val.*build_bool + decay_val.*decay_bool; end function yout = int_step_fcn(sdode, ii, tstep, ylast) % naive integration of one time step, assuming an input function with % constant steps yout = ylast + sdode(ii, ylast)*tstep; end function yout = int_linear_fcn(sdode, ii, tstep, ylast) % naive integration of one time step, assuming an input function with % linear pieces between two points dy_start = sdode(ii-1, ylast); dy_end = sdode(ii, ylast); yout = ylast + trapz([0 tstep], [dy_start dy_end]); end function [tinter, yinter] = repair_step_int(t1, t2, y1, y2, dy1, dy2) %#ok % If integration step drops below zero, it is corrected to zero and the % point in time where this happens is determined. tinter = [y1/(y1 - y2); 1]*(t2 - t1) + t1; yinter = [0; 0]; end function [tinter, yinter] = repair_linear_int(t1, t2, y1, y2, dy1, dy2) %#ok % If integration step drops below zero, it is corrected to zero and the % point in time where this happens is determined. % integral is a quadratically falling equation of the form % y = a*t^2 + b*t + c % y = 0.5*m*t^2 + p1*t + y1 % with m = (p2-p1)/(t2 - t1), % (p1 & p2) <= 0, % t1 < t2 % coefficients of quadratic equation a = 0.5*(dy2 - dy1)/(t2 - t1); b = dy1; c = y1; % solve quadratic equation for t r = roots([a, b, c])+t1; % take root which is within t1 and t2 tmid = r'*(r > t1 & r < t2); % write output tinter = [tmid; t2]; yinter = [0; 0]; end
github
s-guenther/hybrid-master
reload_factory.m
.m
hybrid-master/src/_sim_operation/reload_factory.m
3,468
utf_8
dfb92060f194ada02d440d791b6fecbc
function reload = reload_factory(strategy, base, peak, opt) % RELOAD_FACTORY builds a parameterized reload strategy % % The control strategy must be parameterized with a few constants, i.e. % storage dimensions, and the backward integral. To reduce the number of % inputs and to avoid overloading functions, this function generates and % returns the concrete control strategy function. % % RELOAD = RELOAD_FACTORY(STRATEGY, BASE, OPT) % % The returned function has the form % ([pwr_base, pwr_peak]) = reload(pwr_in, bw_int, [enrgy_base, enrgy_peak]) % where the input parameters a usually explicit functions of time t (in % case signal type == 'fhandle') or step i (in case signal type == 'linear' % or 'step') % % See also: CONTROL_FACTORY, SYNC_FACTORY, SIM_OPERATION. if strcmpi(strategy, 'inter') request = inter_request_factory(peak.power, opt); elseif strcmpi(strategy, 'nointer') request = nointer_request_factory(peak.power, opt); else error('HYBRID:control:invalid_input', ... ['The provided signal type ''%s'' is unknown, must be\n', ... '''fhandle'', ''step'' or ''linear'''], sigtype) end base_pwr_out = @(pwr, bw_int, enrgy) ... sat(pwr + request(pwr, bw_int, enrgy(2)), base.power); peak_pwr_out = @(pwr, bw_int, enrgy) ... pwr - base_pwr_out(pwr, bw_int, enrgy); reload = @(pwr, bw_int, enrgy) [base_pwr_out(pwr, bw_int, enrgy); peak_pwr_out(pwr, bw_int, enrgy)]; end %% LOCAL FUNCTIONS function request_fcn = inter_request_factory(peak_pwr_cap, opt) grad = opt.tanh_sim; if grad request_fcn = @(pwr, peak_enrgy, bw_int) ... -peak_pwr_cap.*tanh(grad*(peak_enrgy - bw_int)); else request_fcn = @(pwr, peak_enrgy, bw_int) ... -peak_pwr_cap.*(peak_enrgy > bw_int) + ... 0 .*(peak_enrgy == bw_int) + ... peak_pwr_cap .*(peak_enrgy < bw_int); end end % TODO correct this function adequately to top function function request_fcn = nointer_request_factory(peak_pwr_cap, opt) grad = opt.tanh_sim; if grad % request_fcn = @(pwr, peak_enrgy, bw_int) ... % max(min(0, pwr), -peak_pwr_cap).* ... % tanh(grad*(peak_enrgy - bw_int)).* ... % (peak_enrgy <= bw_int) + ... % min(max(0, pwr), peak_pwr_cap).* ... % tanh(grad*(peak_enrgy - bw_int)).* ... % (peak_enrgy > bw_int); request_fcn = @(pwr, peak_enrgy, bw_int) ... -min(abs(pwr), peak_pwr_cap).* ... tanh(grad*(peak_enrgy - bw_int)).* ... (sign(peak_enrgy - bw_int) == sign(pwr)); else % request_fcn = @(pwr, peak_enrgy, bw_int) ... % max(min(0, pwr), -peak_pwr_cap).* ... % (peak_enrgy > bw_int) + ... % 0.* ... % (peak_enrgy == bw_int) + ... % min(max(0, pwr), peak_pwr_cap).* ... % (peak_enrgy < bw_int); request_fcn = @(pwr, peak_enrgy, bw_int) ... max(-pwr, -peak_pwr_cap).* ... (peak_enrgy > bw_int & pwr > 0) + ... min(-pwr, peak_pwr_cap).* ... (peak_enrgy < bw_int & pwr < 0); end end
github
s-guenther/hybrid-master
gen_sig_linear.m
.m
hybrid-master/src/_gen_signal/gen_sig_linear.m
1,947
utf_8
d4a30ced2e0841bf58d9043319a0c2f8
function signal = gen_sig_linear(time, val, opt) % GEN_SIG_LINEAR specialized fcn of gen_signal for fhandles % % Generates SIGNAL struct for piecewise linear function input. % % SIGNAL = GEN_SIG_STEP(TIME, VAL, OPT) where TIME and VAL are vector value % pairs describing the function and OPT the options struct obtained from % HYBRIDSET. % % Note: This function inserts zero crossing points into original vector % pair. This is done to simplify the analytic equations for solving. % % See also GEN_SIGNAL. verbose(opt.verbose, 1, ... 'Generating signal of type ''step''.') [tt, xx] = add_zero_crossings(time, val); signal.type = 'linear'; signal.time = tt; signal.val = xx; signal.period = tt(end); signal.amplitude = max(abs(xx)); signal.int = cumtrapz(tt, xx); signal.maxint = max(signal.int); signal.rms = root_mean_square(signal); signal.arv = average_rectified_value(signal); signal.form = signal.rms/signal.arv; signal.crest = signal.amplitude/signal.rms; end %% LOCAL FUNCTIONS function rms = root_mean_square(signal) % RMS implementation for nonuniform step functions % TODO is function correct? --> partly % TODO function will fail if there are parts with slope of zero tt = signal.time; xx = signal.val; TT = signal.period; % integral of (mt + n)^2 is (mt + n)^3/3m % definite integral is ((m*t2 + n)^3 - (m*t1 + n)^3)/3m % find m and n for each timestep % m = (x2 - x1)/(t2 - t1) % n = x1 - m*t1 mm = (xx(2:end) - xx(1:end-1))./(tt(2:end) - tt(1:end-1)); nn = xx(1:end-1) - mm.*tt(1:end-1); sepints = ((mm.*tt(2:end) + nn).^3 - ... (mm.*tt(1:end-1) + nn).^3)./(3*mm); rms = sqrt(1/TT*sum(sepints)); end function arv = average_rectified_value(signal) % ARV implementation for nonuniform step functions % TODO is function correct? tt = signal.time; xx = abs(signal.val); TT = signal.period; arv = 1/TT*trapz(tt, xx); end
github
s-guenther/hybrid-master
gen_sig_fhandle.m
.m
hybrid-master/src/_gen_signal/gen_sig_fhandle.m
2,740
utf_8
fb46f67dd5464efdf0e1274acd00781a
function signal = gen_sig_fhandle(fcn, period, opt) % GEN_SIG_FHANDLE specialized fcn of gen_signal for fhandles % % Generates SIGNAL struct for function handle input. % % SIGNAL = GEN_SIG_FHANDLE(FCN, PERIOD, OPT) where FCN is a function % handle, PERIOD the period of the function and OPT the options struct % obtained from HYBRIDSET. % % See also GEN_SIGNAL. verbose(opt.verbose, 1, ... 'Generating signal of type ''fhandle''.') signal.type = 'fhandle'; signal.fcn = fcn; signal.period = period; % search maximum amplitude with fminbnd verbose(opt.verbose, 2, ... 'Find maximum amplitude via fminbnd.') [~, minamp, foundmin] = fminbnd(fcn, 0, period, opt.optimset); [~, maxamp, foundmax] = fminbnd(@(x) -fcn(x), 0, period, opt.optimset); if ~foundmin || ~foundmax minamp = 0; maxamp = 0; warning('HYBRID:sig:fminbnderr', ... 'Unable to find amplitude of fcn via fminbnd.') end % Find maximum amplitude with sampling signal as fminbnd may only find % local maximum maxsample = max(abs(fcn(linspace(0, period, opt.ampl_sample)))); signal.amplitude = max(maxsample, -min([minamp, maxamp])); % integrate signal to get energy within signal % TODO test if interpolation is neccessary to find maximum verbose(opt.verbose, 2, ... 'Find max integral via ode integration.') odesol = opt.continuous_solver; [t, yout] = odesol(@(tt, xx) fcn(tt), [0 period], 0, opt.odeset); signal.int = @(tt) interp1(t, yout, tt, opt.interint); signal.maxint = max(yout); verbose(opt.verbose, 2, ... 'Calculate Signal parameters rms, arv, form, crest.') signal.rms = root_mean_square(signal, opt); signal.arv = average_rectified_value(signal, opt); signal.form = signal.rms/signal.arv; signal.crest = signal.amplitude/signal.rms; end %% LOCAL FUNCTIONS % TODO put identical function bodies into one function % TODO use 'integral' instead of 'ode'? function rms = root_mean_square(signal, opt) % RMS implementation for continuous functions/function handles squared_fcn = @(t) signal.fcn(t).^2; odesol = opt.continuous_solver; [~, y] = odesol(@(t, y) squared_fcn(t), ... [0 signal.period], ... 0, ... opt.odeset); solved_integral = y(end) - y(1); rms = sqrt(solved_integral/signal.period); end function arv = average_rectified_value(signal, opt) % ARV implementation for continuous functions/function handles rect_fcn = @(t) abs(signal.fcn(t)); odesol = opt.continuous_solver; [~, y] = odesol(@(t, y) rect_fcn(t), ... [0 signal.period], ... 0, ... opt.odeset); solved_integral = y(end) - y(1); arv = solved_integral/signal.period; end
github
s-guenther/hybrid-master
gen_sig_step.m
.m
hybrid-master/src/_gen_signal/gen_sig_step.m
1,278
utf_8
6cdf2054c2c27b4040e890e51eeddb61
function signal = gen_sig_step(time, val, opt) % GEN_SIG_STEP specialized fcn of gen_signal for step functions % % Generates SIGNAL struct for step function input. % % SIGNAL = GEN_SIG_STEP(TIME, VAL, OPT) where TIME and VAL are vector value % pairs describing the function and OPT the options struct obtained from % HYBRIDSET. % % See also GEN_SIGNAL. verbose(opt.verbose, 1, ... 'Generating signal of type ''linear''.') signal.type = 'step'; signal.time = time; signal.val = val; signal.period = time(end); signal.amplitude = max(abs(val)); signal.int = cumsum(diff([0; time]).*val); signal.maxint = max(signal.int); signal.rms = root_mean_square(signal); signal.arv = average_rectified_value(signal); signal.form = signal.rms/signal.arv; signal.crest = signal.amplitude/signal.rms; end %% LOCAL FUNCTIONS function rms = root_mean_square(signal) % RMS implementation for nonuniform step functions % TODO is function correct? tt = signal.time; xx = signal.val; TT = signal.period; rms = sqrt(1/TT*xx'.^2*[0; diff(tt)]); end function arv = average_rectified_value(signal) % ARV implementation for nonuniform step functions tt = signal.time; xx = signal.val; TT = signal.period; arv = 1/TT*abs(xx')*[0; diff(tt)]; end
github
vvanirudh/list_prediction_motion_planning-master
train_mcsvm.m
.m
list_prediction_motion_planning-master/cs_classification/utils/train_mcsvm.m
2,278
utf_8
df5d75cc52cd6024ef1997a07a68f25c
function model = train_mcsvm(features,costs,varargin) % model = TRAIN_MCSVM(features,costs) % model = TRAIN_MCSVM(features,costs,lambda) % model = TRAIN_MCSVM(features,costs,lambda,bw) % features is num_instances x dim_features % costs is num_instances x num_classes % lambda is regularization constant % default parameters if nargin == 2 lambda = 1; kernelParams.h = 1; end if nargin > 2 lambda = varargin{1}; end if nargin > 3 kernelParams.h = varargin{2}; end num_instances = size(features,1); num_classes = size(costs,2); classes = classes_from_values(1-costs); I = eye(num_classes); J = ones(num_classes); K = pdist2(features,features,@(x,y) kernelRBF(x,y,kernelParams)); eigK = eig(K); M = hinge_coeff_matrix(classes,num_classes); Y = reshape(M,numel(M),1); % Y in 4.41 of Lee num_alpha = length(Y); e = ones(num_instances,1); % inputs to quadprog problem.H = kron(I-J/num_classes,K); problem.f = num_instances*lambda*Y; problem.lb = 0*ones(num_alpha,1); problem.ub = reshape(costs,numel(costs),1); problem.Aeq = kron(I-J/num_classes,e)'; problem.beq = 0*ones(num_classes,1); problem.solver = 'quadprog'; problem.options = optimoptions('quadprog','Algorithm','interior-point-convex','Display','off'); alphaStack = quadprog(problem); % get primal from dual alphaMat = reshape(alphaStack,num_instances,num_classes); colsum = sum(alphaMat,2)/num_classes; % cMat is num_classes x num_instances cMat = bsxfun(@minus,alphaMat,colsum); cMat = -cMat/(num_instances*lambda); b = zeros(num_classes,1); % get bias terms for j = 1:num_classes flag = (0 < alphaMat(:,j)) & (alphaMat(:,j) < costs(:,j)); instances_id = find(flag); if isempty(instances_id) error('HOW ELSE DO I CALCULATE B FROM DUAL?'); end id = instances_id(1); b(j) = M(id,j)-dot(K(:,id),cMat(:,j)); end % construct model model.num_classes = num_classes; model.features = features; model.cMat = cMat; model.b = b; model.kernel = @kernelRBF; model.kernelParams = kernelParams; end function M = hinge_coeff_matrix(y,num_classes) % y is a vector of classes % M is the matrix with ith row y_i as in 4.4 of Lee n = length(y); M = zeros(n,num_classes); for i = 1:n M(i,y(i)) = 1; rest = setdiff(1:num_classes,y(i)); M(i,rest) = -1/(num_classes-1); end end
github
vvanirudh/list_prediction_motion_planning-master
train_multi_linear_subgradient_primal.m
.m
list_prediction_motion_planning-master/cs_classification/utils/train_multi_linear_subgradient_primal.m
3,321
utf_8
8091a92a9dce59656ea593d60fd042ef
function [w, obj_vec] = train_multi_linear_subgradient_primal(features,costs,lambda,w0) %TRAIN_LINEAR_SCORER % % weights = TRAIN_LINEAR_SCORER(features,costs,lambda) % % features - Cell array of length n. features{i} is L x d. % costs - Array of size N x L. % lambda - Regularization constant. % % w - d x L % with gamma = hinge(1+s) % assumes bias has been added to features! N = length(features); d = size(features{1},2); L = size(features{1},1); for i = 1:N for j = 1:L F{j}(:,i) = features{i}(j,:)'; end end if (nargin <= 3) w0 = zeros(d,L); end w = w0; % assert(check_implementation(),'IMPLEMENTATION CHECK FAILED'); % optimize w_hist{1} = w; num_iter = 1e2; [obj,omega] = calc_objective(w,F,costs,lambda); obj_vec = obj; for i = 1:num_iter sg = calc_subgrad(w,F,costs,omega,lambda); step = 1e-4; w = w-step*sg; [obj,omega] = calc_objective(w,F,costs,lambda); obj_vec = [obj_vec obj]; w_hist{end+1} = w; end [~,min_id] = min(obj_vec); w = w_hist{min_id}; end function [obj,omega] = calc_objective(w,F,costs,lambda) % costs is N x L L = length(F); N = size(costs,1); omega = zeros(size(costs)); u = zeros(L,N); for j = 1:L u(j,:) = w(:,j)'*F{j}; end mean_u = mean(u,1); for j = 1:L omega(:,j) = 1+u(j,:)-mean_u; end omega = hinge_loss(omega); tmp_mat = costs.*omega; % adding bias or not? w_vec = w(1:end-1,:); w_vec = w_vec(:); % w_vec = w(:); obj = sum(tmp_mat(:))+0.5*lambda*norm(w_vec)^2; end function [obj,omega] = calc_objective_brute(w,features,costs,lambda) omega = zeros(size(costs)); [N,L] = size(costs); obj = 0; for i = 1:N for j = 1:L tmp = 1+features{i}(j,:)*w(:,j); tmp2 = 0; for l = 1:L tmp2 = tmp2+features{i}(l,:)*w(:,l); end tmp = tmp-tmp2/L; tmp = hinge_loss(tmp); omega(i,j) = tmp; obj = obj+costs(i,j)*tmp; end end % adding bias or not? w_vec = w(1:end-1,:); w_vec = w_vec(:); % w_vec = w(:); obj = obj+0.5*lambda*norm(w_vec)^2; end function sg = calc_subgrad(w,F,costs,omega,lambda) % omega is N x L % w is d x L % sg is d x L tmp_mat = costs.*omega; sg = zeros(size(w)); [d,L] = size(w); c = reshape(tmp_mat,numel(tmp_mat),1); for j = 1:L sg_j = F{j}*tmp_mat(:,j); G_j = repmat(F{j},1,L); sg_j = sg_j-G_j*c/L; % take bias into account sg_j(1:end-1) = sg_j(1:end-1)+lambda*w(1:end-1,j); sg(:,j) = sg_j; end end function sg = calc_subgrad_brute(w,features,costs,omega,lambda) % omega is N x L % w is d x L % sg is d x L sg = zeros(size(w)); [d,L] = size(w); [N,L] = size(omega); for k = 1:L sg_k = zeros(d,1); for i = 1:N sg_k = sg_k+costs(i,k)*omega(i,k)*features{i}(k,:)'; term = 0; for j = 1:L term = term+costs(i,j)*omega(i,j)*features{i}(k,:)'; end sg_k = sg_k-term/L; end sg_k(1:end-1) = sg_k(1:end-1)+lambda*w(1:end-1,k); sg(:,k) = sg_k; end end function res = check_implementation() % check calculation of objective and subgrad w = rand(d,L); [obj1,omega1] = calc_objective(w,F,costs,lambda); [obj2,omega2] = calc_objective_brute(w,features,costs,lambda); res1 = isequal(obj1,obj2); sg1 = calc_subgrad(w,F,costs,omega1,lambda); sg2 = calc_subgrad_brute(w,features,costs,omega2,lambda); res2 = isqeual(sg1,sg2); res = res1 && res2; end
github
vvanirudh/list_prediction_motion_planning-master
train_multi_linear_primal_sg_hinge.m
.m
list_prediction_motion_planning-master/cs_classification/utils/train_multi_linear_primal_sg_hinge.m
1,912
utf_8
41e7a8a6e94d75bf6430a2ead4915adb
function [w, obj, wset] = train_multi_linear_primal_sg_hinge(features,losses,lambda, choice, w0) %TRAIN_LINEAR_SCORER % % weights = TRAIN_LINEAR_SCORER(features,losses,lambda) % % features - Array size [d,N] % losses - Array of size [N,L] % lambda - Regularization constant. % % weights - Vector of size [dL,1] [N,L] = size(losses); d = size(features,1); if nargin < 5 w0 = zeros(d*L,1); end w = w0; wset = w; obj = []; num_iter = 1000; for i = 1:num_iter w_matrix = reshape(w,d,L); % center weights w_matrix_centered = bsxfun(@minus,w_matrix,mean(w_matrix,2)); % [d,L] argument = features'*w_matrix_centered; % [N,L] if(strcmp(choice,'hinge')) surrogate_fn = hinge_fn(argument); %hinged_argument gradient_fn = (1+argument) > 0; %flag elseif(strcmp(choice,'square')) surrogate_fn = (1+argument).^2; gradient_fn = 2*(1 + argument); else error('No surrogate loss defined'); end surrogate_argument = losses.*surrogate_fn; surrogate_gradient = losses.*gradient_fn; % build up subgradient subgrad_matrix = zeros(d,L); for j = 1:L subgrad_matrix(:,j) = features*surrogate_gradient(:,j); end subgrad_matrix = bsxfun(@minus,subgrad_matrix,mean(subgrad_matrix,2)); % regularization contribution subgrad_matrix = subgrad_matrix+lambda*w_matrix; subgrad = reshape(subgrad_matrix,d*L,1); % calc objective current_obj_1 = surrogate_argument; current_obj_1 = sum(current_obj_1(:)); current_obj_2 = 0.5*lambda*sum(w.^2); current_obj = current_obj_1+current_obj_2; obj(end+1) = current_obj; % update w step = 1e-5; w = w-step*subgrad; wset = [wset w]; end w = reshape(w,d,L); end function hinged_argument = hinge_fn(argument) hinged_argument = 1+argument; hinged_argument(hinged_argument < 0) = 0; end
github
vvanirudh/list_prediction_motion_planning-master
train_linear_primal_sg.m
.m
list_prediction_motion_planning-master/cs_classification/utils/train_linear_primal_sg.m
1,874
utf_8
65f505389ec8269371a51099edd5abca
function [w, obj, wset] = train_linear_primal_sg(features,costs, lambda, surrogate_loss, w0) %TRAIN_LINEAR_SCORER % % weights = TRAIN_LINEAR_SCORER(features,costs,lambda) % % features - Cell array of length N. features{i} is [L,d] % costs - Array of size [N,L] % lambda - Regularization constant. % % weights - Vector of size [d,1] % with gamma = hinge(1+s) n = length(features); dim_features = size(features{1},2); num_classes = size(features{1},1); % Wrap up f f = []; for i = 1:n f_e = features{i}; f_hat = bsxfun(@minus,f_e,mean(f_e)); % normalize feautures f = [f; f_hat]; end % Wrap up c c = reshape(costs', [], 1); %Criterion if (strcmp(surrogate_loss, 'hinge')) g = @(w) c'*hinge_loss(f*w) + 0.5*lambda*w'*w; nonsmooth_grad = @(w) hinge_comp_grad(w, f, c); elseif (strcmp(surrogate_loss, 'square')) g = @(w) c'*((1 + f*w).^2) + 0.5*lambda*w'*w; nonsmooth_grad = @(w) squared_grad(w, f, c); else error('No surrogate loss specified'); end % g = @(w) c'*abs(1+f*w) + 0.5*lambda*w'*w; % nonsmooth_grad = @(w) l1_comp_grad(w, f, c); % g = @(w) c'*((hinge_loss(f*w)).^2) + 0.5*lambda*w'*w; % nonsmooth_grad = @(w) squared_hinge_comp_grad(w, f, c); num_iter = 1000; if (nargin <= 4) w0 = zeros(dim_features, 1); end w = w0; wset = w; obj = g(w); for i = 1:num_iter grad = nonsmooth_grad(w) + lambda*w; step = 1e-4;%(2e-4)/sqrt(i); w = w - step*grad; wset = [wset w]; obj = [obj g(w)]; end [~,idx] = min(obj); w = wset(:, idx); end function grad = hinge_comp_grad(w, f, c) v = 1 + f*w; c(v<=0) = 0; grad = f'*c; end function grad = l1_comp_grad(w, f, c) v = 1 + f*w; c = c.*sign(v); grad = f'*c; end function grad = squared_hinge_comp_grad(w, f, c) v = 1 + f*w; c(v<=0) = 0; c = c.*v*2; grad = f'*c; end function grad = squared_grad(w, f, c) v = 1 + f*w; c = c.*v*2; grad = f'*c; end
github
vvanirudh/list_prediction_motion_planning-master
train_linear_kernelized_dual_pgd.m
.m
list_prediction_motion_planning-master/cs_classification/utils/train_linear_kernelized_dual_pgd.m
2,318
utf_8
d49326557cc681dfad05808adaf1dac5
function [predictor, obj_vec, stats] = train_linear_kernelized_dual_pgd(arg1, c, lambda, kernel_params, alpha0) % linear kernelized dual pgd if size(arg1,2) == length(c) % arg1 is Q % assumes used same kernel_params to generate Q Q = arg1; stats.Q_time = 0; else % arg1 is F_hat F_hat = arg1; t1 = tic(); Q = calc_Q(F_hat,kernel_params); stats.Q_time = toc(t1); end if (nargin <= 4) alpha0 = zeros(numel(c),1); end alpha = alpha0; % negative of objective g = @(alpha) -((0.5/lambda)*(alpha'*Q*alpha) - ones(size(alpha))'*alpha); % objective g_m = @(alpha) -g(alpha); % primal h = @(alpha) c'*max(0, 1 - (1/lambda)*Q*alpha) + (0.5/lambda)*(alpha'*Q*alpha); max_iter = 100; obj_vec = []; beta = 0.9; v = alpha; % threshold terminating condition eps = 1e-6; % time for operations stats.max_iter = max_iter; [stats.grad_time,stats.backtracks,stats.total_backtrack_time] = deal(zeros(1,stats.max_iter)); stats.run_iter = 0; obj_old = g_m(alpha); t = 1; for i = 1:max_iter stats.run_iter = stats.run_iter+1; fprintf('Iteration %d\n',i); % stepsize % in accelerated can use t from previous iteration %t = 1; t1 = tic(); grad = (Q*v)/lambda - 1; stats.grad_time(i) = toc(t1); % gradient step + projection alpha_plus = min(c, max(0, v - t*grad)); % backtracking backtrack_count = 0; t1 = tic(); while (g_m(alpha_plus) >= g_m(v) + grad'*(alpha_plus - v) ... + (1/(2*t))*(alpha_plus-v)'*(alpha_plus -v)) t = beta*t; alpha_plus = min(c, max(0, v - t*grad)); backtrack_count = backtrack_count+1; end stats.backtracks(i) = backtrack_count; stats.total_backtrack_time(i) = toc(t1); alpha_prev = alpha; alpha = alpha_plus; v = alpha + ((i-1)/(i+2))*(alpha - alpha_prev); obj = g_m(alpha); obj_vec = [obj_vec; obj]; % objective doesn't change by much, break if abs(obj-obj_old)/abs(obj_old) < eps break; end obj_old = obj; end % create predictor predictor.alpha = alpha; predictor.F_hat = F_hat; predictor.lambda = lambda; predictor.kernel_params = kernel_params; end function Q = calc_Q(F_hat,kernel_params) % F_hat is LN x d % Q is LN x LN Q = pdist2(F_hat,F_hat,@(x,y) kernelRBF(x,y,kernel_params)); end
github
vvanirudh/list_prediction_motion_planning-master
createcircle.m
.m
list_prediction_motion_planning-master/matlab_environment_generation/utils/createcircle.m
6,672
utf_8
99e93d3bceb625549153e5148f5dd111
function [Xpoints, Ypoints] = createcircle(varargin) % CREATECIRCLE Create a circle with the mouse % [X, Y] = createcircle(N) lets you create a circle with N points % in the current figure. Use the mouse to indicate the center and % adjust the radius. Press ENTER to confirm the shape and output % the X and Y values. The N parameter is optional. Default 20. % N = 3 can be used to draw triangles, N = 4 to draw squares etc. % % Example: % imshow('westconcordaerial.png'); % [X,Y] = createcircle(4); % % J.A. Disselhorst. % Loosely based on GETRECT and GETLINE (c) The MathWorks, Inc global CCaxes CCfig CCline1 NOP CCline2 if (nargin == 0) NOP = 20 + 1; % Default number of points elseif isnumeric(varargin{1}) NOP = round(varargin{1}+1); % User selected number of points elseif ischar(varargin{1}) feval(varargin{:}); % Subfunctions return; end % -Save state of figure, and adjust---------------------- CCaxes = gca; CCfig = ancestor(CCaxes, 'figure'); old_db = get(CCfig, 'DoubleBuffer'); state = uisuspend(CCfig); original_modes = get(CCaxes, {'XLimMode', 'YLimMode', 'ZLimMode'}); set(CCfig, 'Pointer', 'crosshair', ... 'WindowButtonDownFcn', 'createcircle(''ButtonDown'');','DoubleBuffer','on'); set(CCaxes,'XLimMode','manual', ... 'YLimMode','manual', ... 'ZLimMode','manual'); figure(CCfig); % Line 1: guideline, Line 2: circle ------------------ CCline1 = line('Parent', CCaxes, ... 'XData', [0 0], ... 'YData', [0 0], ... 'Visible', 'off', ... 'Clipping', 'off', ... 'Color', 'g', ... 'LineStyle', ':', ... 'LineWidth', 1); CCline2 = line('Parent', CCaxes, ... 'XData', zeros(1,NOP), ... 'YData', zeros(1,NOP), ... 'Visible', 'off', ... 'Clipping', 'off', ... 'Color', 'g', ... 'LineStyle', ':', ... 'LineWidth', 1); errCatch = 0; %Wait for the function to complete. try waitfor(CCline2, 'UserData', 'Completed'); catch errCatch = 1; end if (errCatch == 1) % error errStatus = 'trap'; elseif (~ishandle(CCline2) || ... ~strcmp(get(CCline2, 'UserData'), 'Completed')) errStatus = 'unknown'; else %succes. errStatus = 'ok'; x = get(CCline2, 'XData'); y = get(CCline2, 'YData'); end % Delete the animation objects if (ishandle(CCline1)) delete(CCline1); end if (ishandle(CCline2)) delete(CCline2); end % Restore the figure state if (ishandle(CCfig)) uirestore(state); set(CCfig, 'DoubleBuffer', old_db); if ishandle(CCaxes) set(CCaxes, {'XLimMode','YLimMode','ZLimMode'}, original_modes); end end %clear the globals clear CCaxes CCfig CCline1 NOP CCline2 % Depending on the error status, return the answer or generate % an error message. switch errStatus case 'ok' % Return the answer Xpoints = x(1:end-1); Ypoints = y(1:end-1); case 'trap' % An error was trapped during the waitfor eid = 'Images:createcircle:interruptedMouseSelection'; error(eid, '%s', 'Interruption during mouse selection.'); case 'unknown' % User did something to cause the rectangle drag to % terminate abnormally. For example, we would get here % if the user closed the figure in the drag. eid = 'Images:createcircle:interruptedMouseSelection'; error(eid, '%s', 'Interruption during mouse selection.'); end function ButtonDown % the user clicked global CCaxes CCfig CCline1 CCline2 point = get(CCaxes,'CurrentPoint'); set(CCline1, 'XData', [point(1,1) point(1,1)], ... 'YData', [point(1,2),point(1,2)], ... 'visible','on', ... 'Color', 'r', ... 'LineStyle', ':', ... 'LineWidth', 1); set(CCline2,'visible','on',... 'Color', 'r', ... 'LineStyle', ':', ... 'LineWidth', 1); set(CCfig, 'WindowButtonMotionFcn', 'createcircle(''ButtonMotion'');', ... 'WindowButtonUpFcn', 'createcircle(''ButtonUp'');'); function ButtonUp % the drawing is complete global CCaxes CCfig CCline1 NOP CCline2 xdata = get(CCline1, 'XData'); ydata = get(CCline1, 'YData'); point = get(CCaxes,'CurrentPoint'); xdata(2) = point(1,1); ydata(2) = point(1,2); set(CCline1, 'XData', xdata, 'YData',ydata,'visible','off'); set(CCfig, 'WindowButtonMotionFcn', '', ... 'WindowButtonUpFcn', '','KeyPressFcn','createcircle(''KeyPress'');'); xdif = xdata(2)-xdata(1); ydif = ydata(2)-ydata(1); THETA=linspace(0+atan2(ydif,xdif),2*pi+atan2(ydif,xdif),NOP); % Create the circle RHO=ones(1,NOP)*sqrt(xdif^2+ydif^2); [X,Y] = pol2cart(THETA,RHO); X=X+xdata(1); Y=Y+ydata(1); set(CCline2, 'XData', X, 'YData',Y,'visible','on', ... 'Color', [1 .5 .2], ... 'LineStyle', '-', ... 'LineWidth', 2); function ButtonMotion % the user moves the mouse, after clicking global CCaxes CCline1 NOP CCline2 point = get(CCaxes,'CurrentPoint'); xdata = get(CCline1, 'XData'); ydata = get(CCline1, 'YData'); point = get(CCaxes,'CurrentPoint'); xdata(2) = point(1,1); ydata(2) = point(1,2); set(CCline1, 'XData', xdata, 'YData',ydata); xdif = xdata(2)-xdata(1); ydif = ydata(2)-ydata(1); THETA=linspace(0+atan2(ydif,xdif),2*pi+atan2(ydif,xdif),NOP); RHO=ones(1,NOP)*sqrt(xdif^2+ydif^2); [X,Y] = pol2cart(THETA,RHO); X=X+xdata(1); Y=Y+ydata(1); set(CCline2, 'XData', X, 'YData',Y); function KeyPress global CCfig CCline2 key = get(CCfig, 'CurrentCharacter'); if (key==char(13)) | (key==char(3)) % enter and return keys % return control to line after waitfor set(CCline2, 'UserData', 'Completed'); end
github
vvanirudh/list_prediction_motion_planning-master
p_poly_dist.m
.m
list_prediction_motion_planning-master/matlab_environment_generation/utils/p_poly_dist.m
3,034
utf_8
122103a78032c09db450eff77e131b3d
%******************************************************************************* % function: p_poly_dist % Description: distance from point to polygon whose vertices are specified by the % vectors xv and yv % Input: % x - point's x coordinate % y - point's y coordinate % xv - vector of polygon vertices x coordinates % yv - vector of polygon vertices x coordinates % Output: % d - distance from point to polygon (defined as a minimal distance from % point to any of polygon's ribs, positive if the point is outside the % polygon and negative otherwise) % x_poly: x coordinate of the point in the polygon closest to x,y % y_poly: y coordinate of the point in the polygon closest to x,y % % Routines: p_poly_dist.m % Revision history: % 03/31/2008 - return the point of the polygon closest to x,y % - added the test for the case where a polygon rib is % either horizontal or vertical. From Eric Schmitz. % - Changes by Alejandro Weinstein % 7/9/2006 - case when all projections are outside of polygon ribs % 23/5/2004 - created by Michael Yoshpe % Remarks: %******************************************************************************* function [d,x_poly,y_poly] = p_poly_dist(x, y, xv, yv) % If (xv,yv) is not closed, close it. xv = xv(:); yv = yv(:); Nv = length(xv); if ((xv(1) ~= xv(Nv)) || (yv(1) ~= yv(Nv))) xv = [xv ; xv(1)]; yv = [yv ; yv(1)]; % Nv = Nv + 1; end % linear parameters of segments that connect the vertices % Ax + By + C = 0 A = -diff(yv); B = diff(xv); C = yv(2:end).*xv(1:end-1) - xv(2:end).*yv(1:end-1); % find the projection of point (x,y) on each rib AB = 1./(A.^2 + B.^2); vv = (A*x+B*y+C); xp = x - (A.*AB).*vv; yp = y - (B.*AB).*vv; % Test for the case where a polygon rib is % either horizontal or vertical. From Eric Schmitz id = find(diff(xv)==0); xp(id)=xv(id); clear id id = find(diff(yv)==0); yp(id)=yv(id); % find all cases where projected point is inside the segment idx_x = (((xp>=xv(1:end-1)) & (xp<=xv(2:end))) | ((xp>=xv(2:end)) & (xp<=xv(1:end-1)))); idx_y = (((yp>=yv(1:end-1)) & (yp<=yv(2:end))) | ((yp>=yv(2:end)) & (yp<=yv(1:end-1)))); idx = idx_x & idx_y; % distance from point (x,y) to the vertices dv = sqrt((xv(1:end-1)-x).^2 + (yv(1:end-1)-y).^2); if(~any(idx)) % all projections are outside of polygon ribs [d,I] = min(dv); x_poly = xv(I); y_poly = yv(I); else % distance from point (x,y) to the projection on ribs dp = sqrt((xp(idx)-x).^2 + (yp(idx)-y).^2); [min_dv,I1] = min(dv); [min_dp,I2] = min(dp); [d,I] = min([min_dv min_dp]); if I==1, %the closest point is one of the vertices x_poly = xv(I1); y_poly = yv(I1); elseif I==2, %the closest point is one of the projections idxs = find(idx); x_poly = xp(idxs(I2)); y_poly = yp(idxs(I2)); end end if(inpolygon(x, y, xv, yv)) d = -d; end
github
vvanirudh/list_prediction_motion_planning-master
conseqopt_features.m
.m
list_prediction_motion_planning-master/conseqopt/utils/conseqopt_features.m
3,432
utf_8
1615ef706dffbc5df66cd54131212465
function features = conseqopt_features(data,S,choices) % data is in common format % S is [N,K] % choices: struct with fields % ('append_lib_contexts','append_down_levels','append_type') % features is cell array length N. features{i} is [L,d] % this function is for data with environment + element features % does not make sense for data with environment-only features assert(isfield(data(1),'query_contexts'),'conseqopt_features:format_error', ... 'data requires field query_contexts'); [N,K] = size(S); features = cell(1,N); L = length(data(1).costs); for i = 1:N if choices.append_lib_contexts features{i} = [data(i).query_contexts data(i).lib_contexts]; else features{i} = [data(i).query_contexts]; end if choices.append_down_levels switch choices.append_type case 'differencing' features{i} = append_features_differencing(data(i),features{i},S(i,:),choices); case 'averaging' features{i} = append_features_averaging(data(i),features{i},S(i,:),choices); otherwise error('conseqopt_features:invalid_choice', ... 'append_type \in \{differencing,averaging\}'); end end % add bias features{i} = [features{i} ones(L,1)]; end end function features_i = append_features_differencing(data_i,features_i,S_i,choices) % subscript i emphasizes that variables are for a single environment % from conseqopt paper % append difference with features of past elements K = length(S_i); diff_features = []; for j = 1:K % no prediction, since environment already classified correctly if S_i(j) == 0 diff_features = [diff_features zeros(size(features_i))]; continue; end if choices.append_lib_contexts features_past_slot = [data_i.query_contexts(S_i(j),:) data_i.lib_contexts(S_i(j),:)]; else features_past_slot = [data_i.query_contexts(S_i(j),:)]; end diff_features = [diff_features bsxfun(@minus,features_i,features_past_slot)]; end features_i = [features_i diff_features]; end function features_i = append_features_averaging(data_i,simple_features_i,S_i,choices) % subscript i emphasizes that variables are for a single environment % from scp paper K = length(S_i); [L,d_simple] = size(simple_features_i); % first level, nothing to average over if K == 0 features_i = [simple_features_i zeros(L,2*d_simple)]; return; end % previous slot features % simple are averaged and appended prev_slot_simple_features = zeros(K,d_simple); for k = 1:K if choices.append_lib_contexts simple_features_k = [data_i.query_contexts(S_i(k),:) data_i.lib_contexts(S_i(k),:)]; else simple_features_k = [data_i.query_contexts(S_i(k),:)]; end prev_slot_simple_features(k,:) = simple_features_k; end % very inefficient features_i = zeros(L,3*d_simple); for j = 1:L diff_features = bsxfun(@minus,prev_slot_simple_features,simple_features_i(j,:)); abs_diff_features = abs(diff_features); % size [K,d1]. min_abs_diff_features = min(abs_diff_features,[],1); % [1,d1] mean_abs_diff_features = mean(abs_diff_features,1); features_i(j,:) = [simple_features_i(j,:) min_abs_diff_features mean_abs_diff_features]; end end
github
vvanirudh/list_prediction_motion_planning-master
linspaceNDim.m
.m
list_prediction_motion_planning-master/chomp/utils/linspaceNDim.m
2,585
utf_8
78ae81dcc1c906b50dc5a0054ff0d366
function y = linspaceNDim(d1, d2, n) %LINSPACENDIM Linearly spaced multidimensional matrix. % LINSPACENDIM(d1, d2) generates a multi-dimensional % matrix of 100 linearly equally spaced points between % each element of matrices d1 and d2. % % LINSPACENDIM(d1, d2, N) generates N points between % each element of matrices X1 and X2. % % Example: % d1 = rand(3, 2, 4); d2 = rand(size(d1)); n = 10; % % y = linspaceNDim(d1, d2, n) returns a multidimensional matrix y of % size (3, 2, 4, 10) % % % Class support for inputs X1,X2: % float: Multidimensional matrix, vector, double, single % % Steeve AMBROISE --> [email protected] % % $ Date: 2009/01/29 21:00:00 GMT $ % $ revised Date: 2009/02/02 18:00:00 GMT $ % Bug fixed for singleton dimensions that occur when d1 or d2 % are empty matrix, scalar or vector. % % if nargin == 2 n = 100; end n = double(n); d1 = squeeze(d1); d2 = squeeze(d2); if ndims(d1)~= ndims(d2) || any(size(d1)~= size(d2)) error('d1 and d2 must have the same number of dimension and the same size'), end NDim = ndims(d1); %%%%%%%% To know if the two first dimensions are singleton dimensions if NDim==2 && any(size(d1)==1) NDim = NDim-1; if all(size(d1)==1) NDim = 0; end end pp = (0:n-2)./(floor(n)-1); Sum1 = TensorProduct(d1, ones(1,n-1)); Sum2 = TensorProduct((d2-d1), pp); y = cat(NDim+1, Sum1 + Sum2, shiftdim(d2, size(d1, 1)==1 )); %%%%% An old function that I wrote to replace the built in Matlab function: %%%%% KRON function Z = TensorProduct(X,Y) % Z = TensorProduct(X,Y) returns the REAL Kronecker tensor product of X and Y. % The result is a multidimensional array formed by taking all possible products % between the elements of X and those of Y. % % If X is m-by-n and Y is p-by-q-by-r, then kron(X,Y) % is m-by-p-by-n-by-q-by-r. % % X and Y are multidimensional matrices % of any size and number of dimensions % % E.g. if X is of dimensions (4, 5, 3) and Y of dimension (3, 1, 7, 4) % TensorProduct(X, Y) returns a multidimensional matrix Z of dimensions: % (4, 5, 3, 3, 7, 4) % % $ Date: 2001/11/09 10:20:00 GMT $ % % Steeve AMBROISE --> [email protected] % sX=size(X);sY=size(Y); ndim1=ndims(X);ndim2=ndims(Y); indperm=[ndim2+1:ndim1+ndim2,1:ndim2]; % to remove all singleton dimensions Z=squeeze(repmat(X,[ones(1,ndims(X)),sY]).*... permute(repmat(Y,[ones(1,ndims(Y)),sX]),indperm));
github
vvanirudh/list_prediction_motion_planning-master
v2struct.m
.m
list_prediction_motion_planning-master/chomp/utils/v2struct_2011_09_12/v2struct.m
16,311
utf_8
77b042ae8b342c50880cf0e543b7bd27
%% v2struct % v2struct Pack/Unpack Variables to/from a scalar structure. function varargout = v2struct(varargin) %% Description % v2struct has dual functionality in packing & unpacking variables into structures and % vice versa, according to the syntax and inputs. % % Function features: % * Pack variables to structure with enhanced field naming % * Pack and update variables in existing structure % * Unpack variables from structure with enhanced variable naming % * Unpack only specific fields in a structure to variables % * Unpack without over writing existing variables in work space % % In addition to the obvious usage, this function could by highly useful for example in % working with a function with multiple inputs. Packing variables before the call to % the function, and unpacking it in the beginning of the function will make the function % call shorter, more readable, and you would not have to worry about arguments order any % more. Moreover you could leave the function as it is and you could pass same inputs to % multiple functions, each of which will use its designated arguments placed in the % structure. % %% Syntax % Pack % S = v2struct % S = v2struct(x,y,z,...) % S = v2struct(fieldNames) % S = v2struct(A,B,C,..., fieldNames) % S = v2struct(x,..., nameOfStruct2Update, fieldNames) % v2struct % v2struct(x,y,z,...) % v2struct(fieldNames) % v2struct(A,B,C,..., fieldNames) % v2struct(x,..., nameOfStruct2Update, fieldNames) % % Unpack % v2struct(S) % [a,b,c,...] = v2struct(S) % v2struct(S,fieldNames) % [a,b,c,...] = v2struct(S,fieldNames) % %% Inputs & Outputs % Pack - inputs % x,y,z,... - any variable to pack. can be replaced by fieldNames below. % nameOfStruct2Update - optional, name of structure to update if desired. % fieldNames - optional, cell array of strings, which must include a cell % with the string 'fieldNames' and must be the last input. % Pack - outputs % S - the packed structure. If there is no output argument then a structure named % Sv2struct would be created in the caller workspace. % % Unpack - inputs % S - name of structure to be unpacked. % fieldNames - optional, cell array of strings, which must include a cell with the % string 'fieldNames' and must be the last input. % Unpack - outputs % a,b,c,... - variables upacked from the structure. % if there are no output arguments then variables would be created in % the caller workspace with naming according to name of inputs. % %% Examples % % see 'Usage example' section below for convenient presentation of these examples. % % % NOTE: whenever using filedNames cell array please note the following % % 1. fieldNames cell array must include a cell with the string 'fieldNames' % % 2. fieldNames cell array input must be the last input. % % % Pack % x = zeros(3); x2 = ones(3); y = 'Testing123'; z = cell(2,3); % fieldNames1 = {'fieldNames', 'x', 'y', 'z'}; % fieldNames2 = {'fieldNames', 'a', 'b', 'c'}; % fieldNames3 = {'fieldNames', 'x'}; % nameOfStruct2Update = 'S'; % % % The four examples below return structure S with same values however the % % structure's field names are defined differently in every syntax. % % Example 1. % % structure field names defined by variables names. % S = v2struct(x,y,z) % % Example 2. % % structure field names defined according to the cell array fieldNames. % % NOTE: variables with the names in fieldNames1 must exist in the caller workspace. % S = v2struct(fieldNames1) % % Example 3. % % same as #1. but arguments are passed explicitly % S = v2struct(zeros(3), 'Testing123', cell(2,3), fieldNames1) % % Example 4. % % field names defined by content of fieldNames2 while % % the values are set according to the passed arguments. In this case the structure % % S returned would be: S.a=x, S.b=y, S.c=z % S = v2struct(x,y,z, fieldNames2) % % % Example 5. % % update structure S. The fields that would be updated are according to content % % of fieldNames3. Note that you must pass a variable with the name % % 'nameOfStruct2Update' placed before 'fieldNames3'. This variable should contain % % the name of the structure you want to update as a string. Also note that if you % % set an output structure name which is different than the one stated in % % nameOfStruct2Update a new structure would be created and the structure that was % % meant to be updated would not get updated. % S.oldField = 'field to be saved for future use' % S = v2struct(x2, nameOfStruct2Update, fieldNames3) % % % Example 6. % % pack all variables in caller workspace. Call without input arguments. % S = v2struct % % % The following examples return the same results as the examples above but the % % structure would be returned with the default name 'Sv2struct'. Be cautious as % % this might lead to overriding of arguments. % % Example 7. % v2struct(x,y,z) % % Example 8. % v2struct(fieldNames1) % % Example 9. % v2struct(zeros(3), 'Testing123', cell(2,3), fieldNames1) % % Example 10. % v2struct(x,y,z, fieldNames2) % % Example 11. % S.oldField = 'field to be saved for future use' % v2struct(x2, nameOfStruct2Update, fieldNames3) % % Example 12. % v2struct % % % Unpack % clear S x x2 y z fieldNames1 fieldNames2 fieldNames3 nameOfStruct2Update % S.x = zeros(3); S.y = 'Testing123'; S.z = cell(2,3); % fieldNames3 = {'fieldNames','x','z'}; % % % Example 1. % % This example creates or overwrites variables x, y, z in the caller with the % % contents of the corresponding named fields. % v2struct(S) % % % Example 2. % % This example assigns the contents of the fields of the scalar structure % % S to the variables a,b,c rather than overwriting variables in the caller. If % % there are fewer output variables than there are fields in S, the remaining fields % % are not extracted. % [a,b,c] = v2struct(S) % % % Example 3. % % This example creates or overwrites variables x and z in the caller with the % % contents of the corresponding named fields. % v2struct(S, fieldNames3) % % % Example 4. % % This example assigns the contents of the fields 'x' and 'z' defined by % % fieldNames3 of the scalar structure S to the variables a and b rather than % % overwriting variables in the caller. If there are fewer output variables than % % there are fields in S, the remaining fields are not extracted. % [a,b] = v2struct(S, fieldNames3) % % % This example unpacks variables 'y' and 'z' only without overwriting variable 'x'. % % NOTE the addition of the field named 'avoidOverWrite' to the structure to be % % unpacked. This is mandatory in order to make this functionality work. The % % contents of this field can be anything, it does not matter. % S.avoidOverWrite = ''; % x = 'do not overwrite me'; % v2struct(S) % %% Usage example (includes sub-functions) % 1. run attached v2structDemo1.m file for on screen presentation of examples. % 2. run attached v2structDemo2.m file and read comments in file for a suggestion of % how to use v2struct in managing input to other functions with improved usability. % %% Revision history % 2011-05-19, Adi N., Creation % 2011-05-29, Adi N., Update structure added, some documentation and demo function changes % 2011-06-02, Adi N., Fixed updating structure functionality % 2011-06-05, Adi N., Added functionality: avoid overwritring existing variables, added % unpacking examples to demo1 .m file. % 2011-06-30, Adi N., fieldNames usage corrected, now must include a specific string to % be triggered. Documentation enhanced. Code tweaked. % 2011-07-14, Adi N., Fixed bug in packing with variables only % 2011-08-14, Adi N., Clarified warning and error when packing/unpacking with % fieldNames. % 2011-09-12, Adi N., Added easy packing of all variables in caller workspace (thanks % to Vesa Lehtinen for the suggestion), fixed bug in warning % handling in packing case, edited comments. % % Inspired by the function: mmv2truct - D.C. Hanselman, University of Maine, Orono, ME % 04469 4/28/99, 9/29/99, renamed 10/19/99 Mastering MATLAB 5, Prentice Hall, % ISBN 0-13-858366-8 % parse input for field names if isempty(varargin) gotCellArrayOfStrings = false; toUnpackRegular = false; toUnpackFieldNames = false; gotFieldNames = false; else gotCellArrayOfStrings = iscellstr(varargin{end}); toUnpackRegular = (nargin == 1) && isstruct(varargin{1}); if toUnpackRegular fieldNames = fieldnames(varargin{1})'; nFields = length(fieldNames); end gotFieldNames = gotCellArrayOfStrings & any(strcmpi(varargin{end},'fieldNames')); if gotFieldNames fieldNamesRaw = varargin{end}; % indices of cells with actual field names, leaving out the index to 'fieldNames' cell. indFieldNames = ~strcmpi(fieldNamesRaw,'fieldNames'); fieldNames = fieldNamesRaw(indFieldNames); nFields = length(fieldNames); end toUnpackFieldNames = (nargin == 2) && isstruct(varargin{1}) && gotFieldNames; end % Unpack if toUnpackRegular || toUnpackFieldNames struct = varargin{1}; assert(isequal(length(struct),1) , 'Single input nust be a scalar structure.'); CallerWS = evalin('caller','whos'); % arguments in caller work space % update fieldNames according to 'avoidOverWrite' flag field. if isfield(struct,'avoidOverWrite') indFieldNames = ~ismember(fieldNames,{CallerWS(:).name,'avoidOverWrite'}); fieldNames = fieldNames(indFieldNames); nFields = length(fieldNames); end if toUnpackRegular % Unpack with regular fields order if nargout == 0 % assign in caller for iField = 1:nFields assignin('caller',fieldNames{iField},struct.(fieldNames{iField})); end else % dump into variables for iField = 1:nargout varargout{iField} = struct.(fieldNames{iField}); end end elseif toUnpackFieldNames % Unpack with fields according to fieldNames if nargout == 0 % assign in caller, by comparing fields to fieldNames for iField = 1:nFields assignin('caller',fieldNames{iField},struct.(fieldNames{iField})); end else % dump into variables assert( isequal(nFields, nargout) , ['Number of output arguments',... ' does not match number of field names in cell array']); for iField = 1:nFields varargout{iField} = struct.(fieldNames{iField}); end end end % Pack else % build cell array of input names CallerWS = evalin('caller','whos'); inputNames = cell(1,nargin); for iArgin = 1:nargin inputNames{iArgin} = inputname(iArgin); end nInputs = length(inputNames); % look for 'nameOfStruct2Update' variable and get the structure name if ~any(strcmpi(inputNames,'nameOfStruct2Update')) % no nameOfStruct2Update nameStructArgFound = false; validVarargin = varargin; else % nameOfStruct2Update found nameStructArgFound = true; nameStructArgLoc = strcmp(inputNames,'nameOfStruct2Update'); nameOfStruct2Update = varargin{nameStructArgLoc}; % valid varargin with just the inputs to pack and fieldNames if exists validVarargin = varargin(~strcmpi(inputNames,'nameOfStruct2Update')); % valid inputNames with just the inputs name to pack and fieldNames if exists inputNames = inputNames(~strcmpi(inputNames,'nameOfStruct2Update')); nInputs = length(inputNames); % copy structure from caller workspace to enable its updating if ismember(nameOfStruct2Update,{CallerWS(:).name}) % verify existance S = evalin('caller',nameOfStruct2Update); else error(['Bad input. Structure named ''',nameOfStruct2Update,... ''' was not found in workspace']) end end % when there is no input or the input is only variables and perhaps % also nameOfStruct2Update if ~gotFieldNames % no input, pack all of variables in caller workspace if isequal(nInputs, 0) for iVar = 1:length(CallerWS) S.(CallerWS(iVar).name) = evalin('caller',CallerWS(iVar).name); end % got input, check input names and pack else for iInput = 1:nInputs if gotCellArrayOfStrings % called with a cell array of strings errMsg = sprintf(['Bad input in cell array of strings.'... '\nIf you want to pack (or unpack) using this cell array as'... ' designated names'... '\nof the structure''s fields, add a cell with the string'... ' ''fieldNames'' to it.']); else errMsg = sprintf(['Bad input in argument no. ', int2str(iArgin),... ' - explicit argument.\n'... 'Explicit arguments can only be called along with a matching'... '\n''fieldNames'' cell array of strings.']); end assert( ~isempty(inputNames{iInput}), errMsg); S.(inputNames{iInput}) = validVarargin{iInput}; end % issue warning for possible wrong usage when packing with an input of cell array of % strings as the last input without it containing the string 'fieldNames'. if gotCellArrayOfStrings name = inputNames{end}; % input contains structure and a cell array of strings if (nargin == 2) && isstruct(varargin{1}) msgStr = [inputNames{1},''' and ''',inputNames{2},''' were']; % input contains any arguments with an implicit cell array of strings else msgStr = [name, ''' was']; end warnMsg = ['V2STRUCT - ''%s packed in the structure.'... '\nTo avoid this warning do not put ''%s'' as last v2struct input.'... '\nIf you want to pack (or unpack) using ''%s'' as designated names'... ' of the'... '\nstructure''s fields, add a cell with the string ''fieldNames'' to'... ' ''%s''.']; fprintf('\n') warning('MATLAB:V2STRUCT:cellArrayOfStringNotFieldNames',warnMsg,msgStr,... name,name,name) end end % fieldNames cell array exists in input elseif gotFieldNames nVarToPack = length(varargin)-1-double(nameStructArgFound); if nVarToPack == 0 % no variables to pack for iField = 1:nFields S.(fieldNames{iField}) = evalin('caller',fieldNames{iField}); end % else - variables to pack exist % check for correct number of fields vs. variables to pack elseif ~isequal(nFields,nVarToPack) error(['Bad input. Number of strings in fieldNames does not match',... 'number of input arguments for packing.']) else for iField = 1:nFields S.(fieldNames{iField}) = validVarargin{iField}; end end end % if ~gotFieldNames if nargout == 0 assignin( 'caller', 'Sv2struct',S ); else varargout{1} = S; end end % if nargin
github
janhon3n/PCA-ICA-master
plotMatrix.m
.m
PCA-ICA-master/src/plotMatrix.m
598
utf_8
c0c7a0e3c5349d4698cf50b6c9fe466e
% Plots the individual rows of the given matrix using subplot() % % Parameters: % mat - the matrix % rowCount - the amount of rows in the subplot % colCount - the amount of rows to draw from the matrix, each to % different column of the subplot % row - the row of subplot to draw the rows of the matrix % function [] = plotMatrix(mat, rowCount, colCount, row, titl) [r, c] = size(mat); e = min([colCount, r]); for i = 1:e subplot(rowCount,colCount,(row-1) * colCount + i); plot(mat(i,:)); title(strcat(titl, {' '}, num2str(i))); end end
github
janhon3n/PCA-ICA-master
calculateDifference.m
.m
PCA-ICA-master/src/calculateDifference.m
622
utf_8
f41c2289cabefb09cdbfc79211aa6161
% Calculates the difference between two vectors. % The diffenrece is the euclidean distance between the vectors. % It is calculated with the formula Sqrt((a1 - b1)^2 + (a2 - b2)^2 + .... + (an - bn)^2) % % Parameters: % vec1 - first vector % vec2 - second vector % % Returns: % diff - The difference between the vectors % function [diff] = calculateDifference(vec1, vec2) if length(vec1) ~= length(vec2) error('Vectors must have the same length.'); else diff = 0; for i = 1:length(vec1) diff = diff + (vec1(i) - vec2(i))^2; end diff = sqrt(diff); end end
github
janhon3n/PCA-ICA-master
findClosest.m
.m
PCA-ICA-master/src/findClosest.m
1,177
utf_8
c406770a8d9e7632f9ac83852ad28656
% Finds the row of the given matrix that is closest to the given vector % Also checks inversed versions of each rows (each sample *= -1) % % Parameters: % mat - The matrix % vec - The vector % % Returns: % index - The index of the row that is closest to the given vector % inverse - True if the row is inversed, False if not % row - the closest row in mat, inversed if closest that way % function [index, inverse, row] = findClosest(mat, vec) [r, c] = size(mat); if length(vec) ~= c error('Vector length and matrix column count do not match.'); else min = calculateDifference(mat(1,:), vec); inverse = 0; index = 1; row = mat(1,:); for i = 2:r dif = calculateDifference(mat(i,:), vec); if(dif < min) min = dif; index = i; row = mat(i, :); end end for i = 1:r dif = calculateDifference(mat(i,:), vec * -1); if(dif < min) min = dif; index = i; inverse = 1; row = mat(i, :) * -1; end end end end
github
janhon3n/PCA-ICA-master
matchMatrices.m
.m
PCA-ICA-master/src/matchMatrices.m
1,016
utf_8
86f27329713114cb706c68d61f6660d7
% Matches the rows in the second matrix with the rows of the first one % by finding the ones that are closest to each other in terms of euclidean % distance. % If matrices row counts dont match, add all zero rows to mat2 % % Parameters: % mat1 - first matrix, the one that will be sorted % mat2 - second matrix % rows - the amount of rows to sort, starting with 1 % % Returns: % mat - sorted version of mat2 % function [mat] = matchMatrices(mat1, mat2, rows) mat = mat2; [r, c] = size(mat); [r2, c2] = size(mat1); while r2 > r r = r + 1; mat(r, :) = zeros(1, c); end for i = rows:-1:1 % start from the end row => priorisize the first rows [index, inverse, row] = findClosest(mat1, mat(i, :)); % find the index of the closest row temp = mat(i, :); % swap the rows mat(i, :) = mat(index, :); mat(index, :) = temp; if inverse == 1 % if inverse then inverse the row mat(i, :) = mat(i, :) * -1; end end end
github
summitgao/SAR_Change_Detection_GarborPCANet-master
HashingHist.m
.m
SAR_Change_Detection_GarborPCANet-master/Utils/HashingHist.m
3,013
utf_8
06398464aee5f4b8b4ab10e202035881
function [f BlkIdx] = HashingHist(PCANet,ImgIdx,OutImg) % Output layer of PCANet (Hashing plus local histogram) % ========= INPUT ============ % PCANet PCANet parameters (struct) % .PCANet.NumStages % the number of stages in PCANet; e.g., 2 % .PatchSize % the patch size (filter size) for square patches; e.g., 3, 5, 7 % only a odd number allowed % .NumFilters % the number of filters in each stage; e.g., [16 8] means 16 and % 8 filters in the first stage and second stage, respectively % .HistBlockSize % the size of each block for local histogram; e.g., [10 10] % .BlkOverLapRatio % overlapped block region ratio; e.g., 0 means no overlapped % between blocks, and 0.3 means 30% of blocksize is overlapped % ImgIdx Image index for OutImg (column vector) % OutImg PCA filter output before the last stage (cell structure) % ========= OUTPUT =========== % f PCANet features (each column corresponds to feature of each image) % BlkIdx index of local block from which the histogram is compuated % ========= CITATION ============ % T.-H. Chan, K. Jia, S. Gao, J. Lu, Z. Zeng, and Y. Ma, % "PCANet: A simple deep learning baseline for image classification?" submitted to IEEE TPAMI. % ArXiv eprint: http://arxiv.org/abs/1404.3606 % Tsung-Han Chan [[email protected]] % Please email me if you find bugs, or have suggestions or questions! addpath('./Utils') NumImg = max(ImgIdx); f = cell(NumImg,1); map_weights = 2.^((PCANet.NumFilters(end)-1):-1:0); % weights for binary to decimal conversion for Idx = 1:NumImg Idx_span = find(ImgIdx == Idx); Bhist = cell(length(Idx_span),1); NumImginO = length(Idx_span)/PCANet.NumFilters(end); % the number of feature maps in "\cal O" for i = 1:NumImginO T = zeros(size(OutImg(Idx_span(1)))); for j = 1:PCANet.NumFilters(end) T = T + map_weights(j)*Heaviside(OutImg{Idx_span(PCANet.NumFilters(end)*(i-1)+j)}); % weighted combination; hashing codes to decimal number conversion OutImg{Idx_span(PCANet.NumFilters(end)*(i-1)+j)} = []; end Bhist{i} = sparse(histc(im2col_general(T,PCANet.HistBlockSize,... round((1-PCANet.BlkOverLapRatio)*PCANet.HistBlockSize)),(0:2^PCANet.NumFilters(end)-1)')); % calculate histogram for each local block in "T" Bhist{i} = bsxfun(@times, Bhist{i}, ... 2^PCANet.NumFilters(end)./sum(Bhist{i})); % to ensure that sum of each block-wise histogram is equal end f{Idx} = vec([Bhist{:}]); end f = [f{:}]; BlkIdx = kron(ones(NumImginO,1),kron((1:size(Bhist{1},2))',ones(size(Bhist{1},1),1))); %------------------------------- function X = Heaviside(X) % binary quantization X = sign(X); X(X<=0) = 0; function x = vec(X) % vectorization x = X(:);
github
fspaolo/tmdtoolbox-master
tmd_mk_submodel.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_mk_submodel.m
4,488
utf_8
3515cb4a6c75e450cd059cfa27bbf833
% function to make a submodel from a model ModName (TMD format) % calculated on bathymetry grid Gridname % % usage: % ()=tmd_mk_submodel(Name_old,Name_new,limits); % % PARAMETERS % % INPUT % Name_old - ROOT in "DATA/Model_ROOT" control file for EXISTING % tidal model. File Model_* consists of lines: % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in TMD format % % Name_new - root in "DATA/Model_root" control file for SUBMODEL of % tidal model. The submodel is defined by % limits - [lon1,lon2,lat1,lat2] OR [x1 x2 y1 y2] for a model in km; % might be slightly CHANGED to adjust to original model grid % % OUTPUT: % % in TMD/DATA % Model_<Name_new> - control file of 3 or 4 lines % (as in old) % h.<Name_new> - elevation file % UV.<Name_new> - transports file % grid_<Name_new> - grid file % % sample call: % % tmd_mk_submodel('AntPen','AntPen1',[290,300,-70,-60]); % % TMD release 2.02: 21 July 2010 % function []=tmd_mk_submodel(Name_old,Name_new,lims); slash='/'; MACH=computer; if MACH(1:5)=='PCWIN',slash='\';end w=what('TMD');funcdir=[w.path slash 'FUNCTIONS']; path(path,funcdir); [hname,gname,Fxy_ll]=rdModFile(['DATA' slash 'Model_' Name_old],1); if isempty(hname)>0,return;end [uname,gname,Fxy_ll]=rdModFile(['DATA' slash 'Model_' Name_old],2); if isempty(uname)>0,return;end cons=rd_con(hname); [nc,i4]=size(cons); cid=reshape(cons',1,nc*i4); % if isempty(Fxy_ll), % adjust silly lim input while max(lims(1:2))>360,lims(1:2)=lims(1:2)-360;end lims(3)=max(-90,lims(3));lims(4)=min(90,lims(4)); end % [xy_lim,hz,mz,iob,dt]=grd_in(gname);xy_lim=xy_lim'; if(isempty(Fxy_ll)) disp('Grid limits on old file are ...') disp([num2str(xy_lim) ' degrees.']) glob=0; if xy_lim(2)-xy_lim(1)>=360, disp('Grid is GLOBAL');glob=1; end else disp('Grid limits on old file are ...') disp([num2str(xy_lim) ' km.']) end % check limits if ((xy_lim(1)<=lims(1) && xy_lim(2)>=lims(2)) || glob) &&... xy_lim(3)<=lims(3) && xy_lim(4)>=lims(4), [n,m]=size(hz); [x,y]=XY(xy_lim,n,m); stx=x(2)-x(1);sty=y(2)-y(1); if glob && lims(1)<xy_lim(1), i1=find(x>=180);i2=find(x<180); x=[x(i1)-360,x(i2)]; xy_lim(1)=x(1)-stx/2;xy_lim(2)=x(end)+stx/2; if xy_lim(1)<=lims(1) && xy_lim(2)>=lims(2), hz=[hz(i1,:);hz(i2,:)]; else fprintf('Can not adjust global model for requested limits\n'); fprintf('Adjusted %s limits: %10.4f %10.4f %10.4f %10.4f\n',... Name_old,xy_lim); fprintf('Your limits: %10.4f %10.4f %10.4f %10.4f\n',lims); return end end i1=min(find(x>=lims(1))); i2=max(find(x<=lims(2))); j1=min(find(y>=lims(3))); j2=max(find(y<=lims(4))); new_lims=[x(i1)-stx/2,x(i2)+stx/2,... y(j1)-sty/2,y(j2)+sty/2]; n1=i2-i1+1;m1=j2-j1+1; hz1=hz(i1:i2,j1:j2);mz1=mz(i1:i2,j1:j2); else fprintf('Requested limits are out of Model area\n'); fprintf('%s limits: %10.4f %10.4f %10.4f %10.4f\n',... Name_old,xy_lim); fprintf('Your limits: %10.4f %10.4f %10.4f %10.4f\n',lims); return end % cname1=['DATA' slash 'Model_' Name_new]; gname1=['grid_' Name_new]; hname1=['h.' Name_new]; uname1=['UV.' Name_new]; fprintf('Writing control file %s\n',cname1); fid=fopen(cname1,'w'); fprintf(fid,'%s\n',hname1); fprintf(fid,'%s\n',uname1); fprintf(fid,'%s\n',gname1); if isempty(Fxy_ll)==0, fprintf(fid,'%s\n',Fxy_ll); end fclose(fid); fprintf('Writing grid file DATA%s%s...', slash,gname1); grd_out(['DATA/' gname1],new_lims,hz1,mz1,[],dt); fprintf('done\n'); % fprintf('Reading elevation file %s\n',hname); H=zeros(n1,m1,nc); for ic=1:nc [h1,th_lim,ph_lim]=h_in(hname,ic); H(:,:,ic)=h1(i1:i2,j1:j2); fprintf('Constituent %s done\n',cons(ic,:)); end fprintf('Writing elevation file DATA%s%s...',slash,hname1); new_lims h_out(['DATA' slash hname1],H,new_lims(3:4),new_lims(1:2),cid); fprintf('done\n'); fprintf('Reading transports file %s\n',uname); U=zeros(n1,m1,nc);V=U; for ic=1:nc [u1,v1,th_lim,ph_lim]=u_in(uname,ic); U(:,:,ic)=u1(i1:i2,j1:j2);V(:,:,ic)=v1(i1:i2,j1:j2); fprintf('Constituent %s done\n',cons(ic,:)); end fprintf('Writing transport file DATA%s%s...',slash,uname1); uv_out(['DATA' slash uname1],U,V,new_lims(3:4),new_lims(1:2),cid); fprintf('done\n'); return
github
fspaolo/tmdtoolbox-master
tmd_get_ellipse.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_get_ellipse.m
1,999
utf_8
64167f02369b2a1527a5cc6ef71e8b9d
% function to extract tidal ellipse grids from a model % % usage: % [x,y,umaj,umin,uphase,uincl]=tmd_get_ellipse(Model,cons); % % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % cons - tidal constituent given as char* % % output: % umaj,umin - major and minor ellipse axis (cm/s) % uphase, uincl - ellipse phase and inclination degrees GMT % x,y - grid coordinates % % sample call: % [x,y,umaj,umin,uphase,uincl]=tmd_get_ellipse('DATA/Model_Ross_prior','k1'); % % TMD release 2.02: 21 July 2010 % function [x,y,umaj,umin,uphase,uincl]=tmd_get_ellipse(Model,cons); w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); [ModName,GridName,Fxy_ll]=rdModFile(Model,2); [Flag]=checkTypeName(ModName,GridName,'u'); if Flag>0,return;end % [ll_lims,hz,mz,iob]=grd_in(GridName); [n,m]=size(hz); [x,y]=XY(ll_lims,n,m); stx=x(2)-x(1); sty=y(2)-y(1); conList=rd_con(ModName); [nc,dum]=size(conList); cons=deblank(lower(cons)); bcon=deblank(cons(end:-1:1)); cons=bcon(end:-1:1); lc=length(cons); k0=0; for k=1:nc if cons==conList(k,1:lc),ic=k;else k0=k0+1;end end if k0==nc, fprintf('No constituent %s in %s\n',cons,ModName); return end % [U,V,th_lim,ph_lim]=u_in(ModName,ic); [nn,mm]=size(U);if check_dim(Model,n,m,nn,mm)==0,return;end % Extrapolate U and V on z-grid since U,V nodes are on different grids U1=[U(1,:); 0.5*(U(1:end-1,:)+U(2:end,:))]; V1=[V(:,1), 0.5*(V(:,1:end-1)+V(:,2:end))]; ut=U1./max(hz,10)*100.*mz;vt=V1./max(hz,10)*100.*mz; [umaj,umin,uincl,uphase]=TideEl(ut,vt); %% Cut off 0.1% of too big values %umax=max(max(umaj)); %ii=0;L=floor(sum(sum(mz))/1000); %k=1; %while length(ii)<L, % umax=0.9*umax; % ii=find(umaj>umax); %end %umaj(ii)=umax; umaj=umaj';umin=umin';uincl=uincl';uphase=uphase'; return
github
fspaolo/tmdtoolbox-master
tmd_tide_pred_par.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_tide_pred_par.m
5,370
utf_8
ccf2959b9011ed5fb8cad216598f7c3a
%%%% Predict tidal time series in a given locations at given times %%%% using tidal model from a file % USAGE: % [TS,ConList]=tmd_tide_pred(Model,SDtime,lat,lon,ptype,Cid); % % PARAMETERS % Input: % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % SDtime - vector of times expressed in serial days: % see 'help datenum' in matlab % % lat,lon - coordinates in degrees; % Depending on size of SDtime,lat,lon 3 functional modes possible: % % "Time series": SDtime(N,1),lon(1,1),lat(1,1) % "Drift Track": SDtime(N,1),lon(N,1),lat(N,1) % "Map" : SDtime(1,1),lon(N,M),lat(N,M) % % ptype - char*1 - one of % 'z' - elevation (m) % 'u','v' - velocities (cm/s) % 'U','V' - transports (m^2/s); % Cid - indices of consituents to include (<=nc); if given % then included constituents are: conList(Cid,:), % NO minor constituents inferred; % if Cid=[] (or not given), ALL model constituents % included, minor constituents inferred if possible % % Ouput: TS(N) or TS(N,M) - predicted time series or map % conList(nc,4) - list of ALL model % constituents (char*4) % % Dependencies: 'Fxy_ll',h_in,u_in,grd_in,XY,rd_con,BLinterp, tmd_extract_HC % harp1,constit,nodal,checkTypeName % % Sample calls: % % SDtime=[floor(datenum(now)):1/24:floor(datenum(now))+14]; % [z,conList]=tmd_tide_pred('DATA/Model_Ross_prior',SDtime,-73,186,'z'); % ConList([5,6])= % k1 % o1 % [z1,conList]=tmd_tide_pred('DATA/Model_Ross_prior',SDtime,-73,186,'z',[5,6]); % % TMD release 2.02: 21 July 2010 % function [TS,conList]=tmd_tide_pred(Model,SDtime,lat,lon,ptype,Cid); TS=[];conList=[]; w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); if ptype=='z',k=1;else k=2;end [ModName,GridName,Fxy_ll]=rdModFile(Model,k); [Flag]=checkTypeName(ModName,GridName,ptype); if Flag>0,return;end TimeSeries=0;DriftTrack=0;TMap=0; [N,M]=size(lat); n1=N*M; [k1,k2]=size(lon);n2=k1*k2; [k1,k2]=size(SDtime);n3=k1*k2; % if n1==n2, if n1==1 & n3>1, TimeSeries=1; fprintf('MODE: Time series\n'); SDtime=reshape(SDtime,n3,1); elseif n1==n3 & n1>1, DriftTrack=1;N=n1; % make sure all dimensions correspond SDtime=reshape(SDtime,N,1); lat=reshape(lat,N,1); lon=reshape(lon,N,1); fprintf('MODE: Drift Track\n'); elseif n3==1, TMap=1;lon=reshape(lon,N,M); if N==1, lon=lon';lat=lat';N=M;M=1;end fprintf('MODE: Map\n'); else fprintf('WRONG CALL: lengths of vectors lat,lon, SDtime INCONSISTENT:\n'); fprintf('Sizes MUST correspond to one of modes:\n'); fprintf(' 1. Time series: SDtime(N,1),lon(1,1),lat(1,1)\n'); fprintf(' 2. Drift Track: SDtime(N,1),lon(N,1),lat(N,1)\n'); fprintf(' 3. Map: SDtime(1,1),lon(N,M),lat(N,M)\n'); return end else fprintf('WRONG CALL: lengths of vectors lat,lon are different:\n'); return end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% tic fprintf('Reading %s and extracting HC...',ModName); if nargin>5, [amp,pha,D,conList]=tmd_extract_HC(Model,lat,lon,ptype,Cid); else [amp,pha,D,conList]=tmd_extract_HC(Model,lat,lon,ptype); end toc cph= -i*pha*pi/180; hc = amp.*exp(cph); hc=squeeze(hc); [nc,dum]=size(conList); % nc here is # of ALL constituents in the model if conList(1:4)=='stop',TS=NaN;return;end fprintf('Done extracting HC\n'); d0=datenum(1992,1,1); % corresponds to 48622mjd d1=SDtime; time=d1-d0; fprintf('Predicting tide ...\n'); % if nargin<=5, fprintf('Minor constituents inferred\n'); if TimeSeries==1, TS=harp1(time,hc,conList); dh = InferMinor(hc,conList,SDtime); TS=TS+dh; elseif DriftTrack==1, %for k=1:N parfor k=1:N TS(k)=harp1(time(k),hc(:,k),conList); dh = InferMinor(hc(:,k),conList,SDtime(k)); TS(k)=TS(k)+dh; end else % Map %for k=1:nc parfor k=1:nc hci(:,:,k)=hc(k,:,:); end TS=harp(time,hci,conList); dh=InferMinor(hc,conList,SDtime); if ndims(hci)~=ndims(hc),dh=dh';end TS=TS+dh; end else if isempty(Cid)==0, Cid(find(Cid<1))=1;Cid(find(Cid>nc))=nc; if TimeSeries==1, TS=harp1(time,hc,conList(Cid,:)); elseif DriftTrack==1, %for k=1:N parfor k=1:N TS(k)=harp1(time(k),hc(:,k),conList(Cid,:)); end else % Map if nc>1, %for k=1:length(Cid) parfor k=1:length(Cid) hci(:,:,k)=hc(k,:,:); end else hci=hc; end TS=harp(time,hci,conList(Cid,:)); end else % same as above Cid=[]: all constituents included fprintf('Minor constituents inferred\n'); if TimeSeries==1, TS=harp1(time,hc,conList); dh = InferMinor(hc,conList,SDtime); TS=TS+dh; elseif DriftTrack==1, %for k=1:N parfor k=1:N TS(k)=harp1(time(k),hc(:,k),conList); dh = InferMinor(hc(:,k),conList,SDtime(k)); TS(k)=TS(k)+dh; end else % Map %for k=1:nc parfor k=1:nc hci(:,:,k)=hc(k,:,:); end TS=harp(time,hci,conList); dh=InferMinor(hc,conList,SDtime); TS=TS+dh; end end end fprintf('done\n'); return
github
fspaolo/tmdtoolbox-master
TMD_setcaxis.m
.m
tmdtoolbox-master/tmd_toolbox/TMD_setcaxis.m
749
utf_8
3e6d6a57de0807246970f9744c3d147c
% function to set "good" caxis on current axis % n - degree of 10 to round % psn - -1/0/1; -1 negative, 0 symmetric, 1 positive % ha - array to plot % pct - % of higher amplitudes points to cut off % set NaNs/0 in ha first for land nodes % % usage: TMD_setcaxis(n,psn,ha,pct); % function []=TMD_setcaxis(n,psn,ha,pct); icax=0;% cut off 20% of higher amplitudes cax=caxis; camax=cax(2)*(1.-pct/100.); if psn>0, % positive cax(2)=min(floor(cax(2)*10^n)/10^n,camax); cax(1)=-cax(2)/30; elseif psn==0, % symmetric c1=floor(0.5*(abs(cax(1))+abs(cax(2)))*10^n)/10^n; cax=[-min(c1,camax),min(c1,camax)]; elseif psn==-1, % negative cax(1)=max(-camax,ceil(cax(1)*10^n)/10^n); cax(2)=-cax(1)/30; end if cax==[0,0],cax=[0,10^(-n)];end caxis(cax); return
github
fspaolo/tmdtoolbox-master
TMD_cor_date.m
.m
tmdtoolbox-master/tmd_toolbox/TMD_cor_date.m
243
utf_8
7b4c460de1d19122eb4d1411596919d5
% check/correct date function [yy,mm,dd]=TMD_cor_date(yy,mm,dd,uT); a=datevec(datenum(yy,mm,dd,0,0,0)); if a(1)==yy & a(2)==mm & a(3)==dd, return; else yy=a(1);mm=a(2);dd=a(3); end for it=1:3 set(uT(it),'String',int2str(a(it))); end return
github
fspaolo/tmdtoolbox-master
tmd_tide_pred.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_tide_pred.m
5,253
utf_8
ba666dd4135d7166ac671817ef95090f
%%%% Predict tidal time series in a given locations at given times %%%% using tidal model from a file % USAGE: % [TS,ConList]=tmd_tide_pred(Model,SDtime,lat,lon,ptype,Cid); % % PARAMETERS % Input: % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % SDtime - vector of times expressed in serial days: % see 'help datenum' in matlab % % lat,lon - coordinates in degrees; % Depending on size of SDtime,lat,lon 3 functional modes possible: % % "Time series": SDtime(N,1),lon(1,1),lat(1,1) % "Drift Track": SDtime(N,1),lon(N,1),lat(N,1) % "Map" : SDtime(1,1),lon(N,M),lat(N,M) % % ptype - char*1 - one of % 'z' - elevation (m) % 'u','v' - velocities (cm/s) % 'U','V' - transports (m^2/s); % Cid - indices of consituents to include (<=nc); if given % then included constituents are: conList(Cid,:), % NO minor constituents inferred; % if Cid=[] (or not given), ALL model constituents % included, minor constituents inferred if possible % % Ouput: TS(N) or TS(N,M) - predicted time series or map % conList(nc,4) - list of ALL model % constituents (char*4) % % Dependencies: 'Fxy_ll',h_in,u_in,grd_in,XY,rd_con,BLinterp, tmd_extract_HC % harp1,constit,nodal,checkTypeName % % Sample calls: % % SDtime=[floor(datenum(now)):1/24:floor(datenum(now))+14]; % [z,conList]=tmd_tide_pred('DATA/Model_Ross_prior',SDtime,-73,186,'z'); % ConList([5,6])= % k1 % o1 % [z1,conList]=tmd_tide_pred('DATA/Model_Ross_prior',SDtime,-73,186,'z',[5,6]); % % TMD release 2.02: 21 July 2010 % function [TS,conList]=tmd_tide_pred(Model,SDtime,lat,lon,ptype,Cid); % Original TS=[];conList=[]; w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); if ptype=='z',k=1;else k=2;end [ModName,GridName,Fxy_ll]=rdModFile(Model,k); [Flag]=checkTypeName(ModName,GridName,ptype); if Flag>0,return;end TimeSeries=0;DriftTrack=0;TMap=0; [N,M]=size(lat); n1=N*M; [k1,k2]=size(lon);n2=k1*k2; [k1,k2]=size(SDtime);n3=k1*k2; % if n1==n2, if n1==1 & n3>1, TimeSeries=1; fprintf('MODE: Time series\n'); SDtime=reshape(SDtime,n3,1); elseif n1==n3 & n1>1, DriftTrack=1;N=n1; % make sure all dimensions correspond SDtime=reshape(SDtime,N,1); lat=reshape(lat,N,1); lon=reshape(lon,N,1); fprintf('MODE: Drift Track\n'); elseif n3==1, TMap=1;lon=reshape(lon,N,M); if N==1, lon=lon';lat=lat';N=M;M=1;end fprintf('MODE: Map\n'); else fprintf('WRONG CALL: lengths of vectors lat,lon, SDtime INCONSISTENT:\n'); fprintf('Sizes MUST correspond to one of modes:\n'); fprintf(' 1. Time series: SDtime(N,1),lon(1,1),lat(1,1)\n'); fprintf(' 2. Drift Track: SDtime(N,1),lon(N,1),lat(N,1)\n'); fprintf(' 3. Map: SDtime(1,1),lon(N,M),lat(N,M)\n'); return end else fprintf('WRONG CALL: lengths of vectors lat,lon are different:\n'); return end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Reading %s and extracting HC...',ModName); if nargin>5, [amp,pha,D,conList]=tmd_extract_HC(Model,lat,lon,ptype,Cid); else [amp,pha,D,conList]=tmd_extract_HC(Model,lat,lon,ptype); end cph= -i*pha*pi/180; hc = amp.*exp(cph); hc=squeeze(hc); [nc,dum]=size(conList); % nc here is # of ALL constituents in the model if conList(1:4)=='stop',TS=NaN;return;end fprintf('Done extracting HC\n'); d0=datenum(1992,1,1); % corresponds to 48622mjd d1=SDtime; time=d1-d0; fprintf('Predicting tide ...\n'); % if nargin<=5, fprintf('Minor constituents inferred\n'); if TimeSeries==1, TS=harp1(time,hc,conList); dh = InferMinor(hc,conList,SDtime); TS=TS+dh; elseif DriftTrack==1, for k=1:N TS(k)=harp1(time(k),hc(:,k),conList); dh = InferMinor(hc(:,k),conList,SDtime(k)); TS(k)=TS(k)+dh; end else % Map for k=1:nc hci(:,:,k)=hc(k,:,:); end TS=harp(time,hci,conList); dh=InferMinor(hc,conList,SDtime); if ndims(hci)~=ndims(hc),dh=dh';end TS=TS+dh; end else if isempty(Cid)==0, Cid(find(Cid<1))=1;Cid(find(Cid>nc))=nc; if TimeSeries==1, TS=harp1(time,hc,conList(Cid,:)); elseif DriftTrack==1, for k=1:N TS(k)=harp1(time(k),hc(:,k),conList(Cid,:)); end else % Map if nc>1, for k=1:length(Cid) hci(:,:,k)=hc(k,:,:); end else hci=hc; end TS=harp(time,hci,conList(Cid,:)); end else % same as above Cid=[]: all constituents included fprintf('Minor constituents inferred\n'); if TimeSeries==1, TS=harp1(time,hc,conList); dh = InferMinor(hc,conList,SDtime); TS=TS+dh; elseif DriftTrack==1, for k=1:N TS(k)=harp1(time(k),hc(:,k),conList); dh = InferMinor(hc(:,k),conList,SDtime(k)); TS(k)=TS(k)+dh; end else % Map for k=1:nc hci(:,:,k)=hc(k,:,:); end TS=harp(time,hci,conList); dh=InferMinor(hc,conList,SDtime); TS=TS+dh; end end end fprintf('done\n'); return
github
fspaolo/tmdtoolbox-master
TMD_changeCaxis.m
.m
tmdtoolbox-master/tmd_toolbox/TMD_changeCaxis.m
436
utf_8
674298b11c46617740fdc1afb0907c64
% usage: TMD_changeCaxis(n12,act); % change % n12 - 1/2 lower/upper limit % act '+'/'-' increase/descrease function []=TMD_changeCaxis(n12,act,cb,CBpos); cax=caxis; dcax=(cax(2)-cax(1))/50; if act=='-', cax(n12)=floor((cax(n12)-dcax)*100)/100; else cax(n12)=ceil((cax(n12)+dcax)*100)/100; end caxis(cax); h=get(cb,'children');set(h,'ydata',cax); set(cb,'FontWeight','bold','position',CBpos,'YLim',cax); return
github
fspaolo/tmdtoolbox-master
TMD_timeOnOff.m
.m
tmdtoolbox-master/tmd_toolbox/TMD_timeOnOff.m
144
utf_8
50267ad3d2c9322acef99a47279aa1ed
% function []=TMD_timeOnOff(uTime,uT,action); set(uTime,'Enable',action); nt=length(uT); for it=1:nt, set(uT(it),'Enable',action); end return
github
fspaolo/tmdtoolbox-master
tmd_get_coeff.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_get_coeff.m
2,320
utf_8
3b50e561d7d7ef05dd36e1aa43f231b1
% function to extract amplitude and phase grids from % a model ModName (OTIS format) calculated on bathymetry grid % % % usage: % [x,y,amp,phase]=tmd_get_coeff(Model,type,cons); % PARAMETERS % % INPUT % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % type - one of 'z','u','v' (velocities),'U','V' (transports) % cons - tidal constituent given as char* % % output: % amp - amplituide (m, m^2/s or cm/s for z, U/V, u/v type) % phase - phase degrees GMT % x,y - grid coordinates % % sample call: % [x,y,amp,phase]=tmd_get_coeff('DATA/Model_Ross_prior','z','k1'); % % TMD release 2.02: 21 July 2010 % function [x,y,amp,phase]=tmd_get_coeff(Model,type,cons); w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); if type(1:1)=='z',k=1;else k=2;end [ModName,GridName,Fxy_ll]=rdModFile(Model,k); [Flag]=checkTypeName(ModName,GridName,type); if Flag>0,return;end % [ll_lims,hz,mz,iob]=grd_in(GridName); [n,m]=size(hz); [x,y]=XY(ll_lims,n,m); stx=x(2)-x(1); sty=y(2)-y(1); conList=rd_con(ModName); [nc,dum]=size(conList); cons=deblank(lower(cons)); bcon=deblank(cons(end:-1:1)); cons=bcon(end:-1:1); lc=length(cons); k0=0; for k=1:nc if cons==conList(k,1:lc),ic=k;else k0=k0+1;end end if k0==nc, fprintf('No constituent %s in %s\n',cons,ModName); return end if type =='z', [z,th_lim,ph_lim]=h_in(ModName,ic); [nn,mm]=size(z); if check_dim(Model,n,m,nn,mm)==0,return;end amp=abs(z); phase=atan2(-imag(z),real(z))*180/pi; phase(find(phase<0))=phase(find(phase<0))+360; else [U,V,th_lim,ph_lim]=u_in(ModName,ic); [nn,mm]=size(U); if check_dim(Model,n,m,nn,mm)==0,return;end [hu,hv]=Huv(hz); if type=='u' | type=='U', x=x-stx/2; amp=abs(U); if type=='u', amp=amp./max(hu,10)*100;end phase=atan2(-imag(U),real(U))*180/pi; phase(find(phase<0))=phase(find(phase<0))+360; else y=y-sty/2; amp=abs(V); if type=='v', amp=amp./max(hv,10)*100;end phase=atan2(-imag(V),real(V))*180/pi; phase(find(phase<0))=phase(find(phase<0))+360; end end amp=amp';phase=phase'; % to adopt ny first, then nx convention return
github
fspaolo/tmdtoolbox-master
tmd_ellipse.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_ellipse.m
2,167
utf_8
8627ba2c958574783f01ee2a0e9ede2c
% Calculate tidal ellipse parameters at given locations using a model % % USAGE % [umajor,uminor,uphase,uincl]=tmd_ellipse(Model,lat,lon,constit); % % PARAMETERS % % INPUT % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % % lat(L),lon(L) - coordinates (degrees) -> outputs 1D arrays % OR lat(n,m), LON(n,m) - could be 2D arrays -> then outputs are 2D arrays % % constit - constituent name, char length <=4 % % OUTPUT % umajor,uminor,uphase,uincl - tidal ellipse parameters (cm/s,o) in % lat,lon % % Dependencies: u_in,grd_in,XY,rd_con,BLinterp,TideEl,checkTypeName % % Sample call: % [umaj,umin,uph,uinc]=tmd_ellipse('DATA/Model_Ross_prior',-73,186,'k1'); % % TMD release 2.02: 21 July 2010 function [umajor,uminor,uphase,uincl]=tmd_ellipse(Model,lat,lon,constit); w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); [ModName,GridName,Fxy_ll]=rdModFile(Model,2); km=1; if isempty(Fxy_ll)>0,km=0;end [Flag]=checkTypeName(ModName,GridName,'u'); if Flag>0,return;end while length(constit)<4,constit=[constit ' '];end L=length(lon); if km==1, eval(['[xt,yt]=' Fxy_ll '(lon,lat,''F'');']); else xt=lon;yt=lat; end [ll_lims,H,mz,iob]=grd_in(GridName); [n,m]=size(H); [x,y]=XY(ll_lims,n,m);[X,Y]=meshgrid(x,y); dx=x(2)-x(1);dy=y(2)-y(1); conList=rd_con(ModName); [nc,dum]=size(conList); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% xu=x-dx/2;yv=y-dy/2; H(find(H==0))=NaN; D=BLinterp(x,y,H,xt,yt,km); % for ic=1:nc if constit==conList(ic,:) | lower(constit)==conList(ic,:) ... | upper(constit)==conList(ic,:), ic1=ic;break end end % [u,v,th_lim,ph_lim]=u_in(ModName,ic1); [nn,mm]=size(u); if check_dim(ModName,n,m,nn,mm), u(find(u==0))=NaN;v(find(v==0))=NaN; u1=BLinterp(xu,y,u,xt,yt,km); v1=BLinterp(x,yv,v,xt,yt,km); u1=u1./D*100;v1=v1./D*100; [umajor,uminor,uincl,uphase]=TideEl(u1,v1); end return
github
fspaolo/tmdtoolbox-master
tmd_extract_HC.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_extract_HC.m
5,376
utf_8
868466af43a68b7f468ecc87fb72280c
% Function to extract tidal harmonic constants out of a tidal model % for given locations % USAGE % [amp,Gph,Depth,conList]=tmd_extract_HC(Model,lat,lon,type,Cid); % % PARAMETERS % Input: % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % lat(L),lon(L) or lat(N,M), lon(N,M) - coordinates in degrees; % type - char*1 - one of % 'z' - elvation (m) % 'u','v' - velocities (cm/s) % 'U','V' - transports (m^2/s); % Cid - indices of consituents to include (<=nc); if given % then included constituents are: ConList(Cid,:), % if Cid=[] (or not given), % ALL model constituents included % % Ouput: % amp(nc0,L) or amp(nc0,N,M) - amplitude % Gph(nc0,L) or Gph(nc0,N,M) - Greenwich phase (o) % Depth(L) or Depth(N,M) - model depth at lat,lon % conList(nc,4) - constituent list % if Cid==[], L=nc, else L=length(Cid); end % % Sample call: % [amp,Gph,Depth,conList]=tmd_extract_HC('DATA/Model_Ross_prior',lat,lon,'z'); % % Dependencies: h_in,u_in,grd_in,XY,rd_con,BLinterp,checkTypeName % % TMD release 2.02: 21 July 2010 function [amp,Gph,D,conList]=tmd_extract_HC(Model,lat,lon,type,Cid); amp=[];Gph=[];D=[];conList=[]; w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); if type=='z',k=1;else k=2;end [ModName,GridName,Fxy_ll]=rdModFile(Model,k); km=1; if isempty(Fxy_ll)>0,km=0;end [Flag]=checkTypeName(ModName,GridName,type); if Flag>0,return;end ik=findstr(GridName,'km'); if isempty(ik)==0 & km==0, fprintf('STOPPING...\n'); fprintf('Grid is in km, BUT function to convert lat,lon to x,y is NOT given\n'); conList='stop'; amp=NaN;Gph=NaN;D=NaN; return end if km==1, eval(['[xt,yt]=' Fxy_ll '(lon,lat,''F'');']); else xt=lon;yt=lat; end [ll_lims,H,mz,iob]=grd_in(GridName); if type ~='z', [mz,mu,mv]=Muv(H);[hu,hv]=Huv(H); end [n,m]=size(H); [x,y]=XY(ll_lims,n,m); dx=x(2)-x(1);dy=y(2)-y(1); conList=rd_con(ModName); [nc,dum]=size(conList); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% glob=0; if x(end)-x(1)==360-dx,glob=1;end if glob==1, % extend limits x=[x(1)-dx,x,x(end)+dx]; H=[H(end,:);H;H(1,:)]; mz=[mz(end,:);mz;mz(1,:)]; end % adjust lon convention xmin=min(min(xt));xmax=max(max(xt)); if km==0, ikm1=[];ikm2=[]; if xmin<x(1), ikm1=find(xt<0);xt(ikm1)=xt(ikm1)+360;end if xmin>x(end), ikm2=find(xt>180);xt(ikm2)=xt(ikm2)-360;end end % xu=x-dx/2;yv=y-dy/2; [X,Y]=meshgrid(x,y);[Xu,Yu]=meshgrid(xu,y);[Xv,Yv]=meshgrid(x,yv); H(find(H==0))=NaN; if type ~='z', if glob==1, hu=[hu(end,:);hu;hu(1,:)];hv=[hv(end,:);hv;hv(1,:)]; mu=[mu(end,:);mu;mu(1,:)];mv=[mv(end,:);mv;mv(1,:)]; end hu(find(hu==0))=NaN;hv(find(hv==0))=NaN; end D=interp2(X,Y,H',xt,yt); mz1=interp2(X,Y,real(mz)',xt,yt); % Correct near coast NaNs if possible i1=find(isnan(D)>0 & mz1>0); if isempty(i1)==0, D(i1)=BLinterp(x,y,H,xt(i1),yt(i1),km); end % cind=[1:nc]; if nargin>4, if isempty(Cid)==0;cind=Cid;end;end fprintf('\n'); for ic0=1:length(cind), ic=cind(ic0); fprintf('Interpolating constituent %s...',conList(ic,:)); if type=='z', [z,th_lim,ph_lim]=h_in(ModName,ic); [nn,mm]=size(z);if check_dim(Model,n,m,nn,mm)==0,break;end if glob==1,z=[z(end,:);z;z(1,:)];end z(find(z==0))=NaN; else [u,v,th_lim,ph_lim]=u_in(ModName,ic); [nn,mm]=size(u);if check_dim(Model,n,m,nn,mm)==0,break;end if glob==1, u=[u(end,:);u;u(1,:)];v=[v(end,:);v;v(1,:)]; end u(find(u==0))=NaN;v(find(v==0))=NaN; %%%%if type=='u',u=u./hu*100;end %%%%if type=='v',v=v./hv*100;end end if type=='z', z1=interp2(X,Y,z',xt,yt);z1=conj(z1); % Correct near coast NaNs if possible i1=find(isnan(z1)>0 & mz1>0); if isempty(i1)==0, z1(i1)=BLinterp(x,y,z,xt(i1),yt(i1),km); end amp(ic0,:,:)=abs(z1); Gph(ic0,:,:)=atan2(-imag(z1),real(z1)); elseif type=='u' | type=='U', u1=interp2(Xu,Yu,u',xt,yt);u1=conj(u1); mu1=interp2(Xu,Yu,real(mu)',xt,yt); % Correct near coast NaNs if possible i1=find(isnan(u1)>0 & mu1>0); if isempty(i1)==0, u1(i1)=BLinterp(xu,y,u,xt(i1),yt(i1),km); end if type=='u',u1=u1./D*100;end amp(ic0,:,:)=abs(u1); Gph(ic0,:,:)=atan2(-imag(u1),real(u1)); elseif type=='v' | type=='V', v1=interp2(Xv,Yv,v',xt,yt);v1=conj(v1); mv1=interp2(Xv,Yv,real(mv)',xt,yt); % Correct near coast NaNs if possible i1=find(isnan(v1)>0 & mv1>0); if isempty(i1)==0, v1(i1)=BLinterp(x,yv,v,xt(i1),yt(i1),km); end if type=='v',v1=v1./D*100;end amp(ic0,:,:)=abs(v1); Gph(ic0,:,:)=atan2(-imag(v1),real(v1)); else fprintf(['Wrong Type %s, should be one ',... 'of:''z'',''u'',''v'',''U'',''V''\n'],type); amp=NaN;Gph=NaN; return end fprintf('done\n'); end Gph=Gph*180/pi;Gph(find(Gph<0))=Gph(find(Gph<0))+360; Gph=squeeze(Gph);amp=squeeze(amp); if km==0, xt(ikm1)=xt(ikm1)-360;xt(ikm2)=xt(ikm2)+360; end %%%if nargin>4,conList=conList(cind,:);end % commented Oct 23, 2008 return
github
fspaolo/tmdtoolbox-master
tmd_get_bathy.m
.m
tmdtoolbox-master/tmd_toolbox/tmd_get_bathy.m
1,074
utf_8
2a7ce7567ca7015dcb55f47d48e3c795
%======================================================================== % tmd_get_bathy.m % % Gets map of bathymetry (water column thickness under ice shelves) for % specified model. % % Written by: Laurie Padman (ESR): [email protected] % August 18, 2004 % % Sample call: % [long,latg,H]=tmd_get_bathy('Model_ISPOL'); % %======================================================================== % TMD release 2.02: 21 July 2010 % function [long,latg,H] = tmd_get_bathy(Model); w=what('TMD');funcdir=[w.path '/FUNCTIONS']; path(path,funcdir); [ModName,GridName,Fxy_ll]=rdModFile(Model,1); check=exist(GridName,'file'); if(check~=2); % Grid File not found disp(' ') disp('Grid file not found. Add directory containing model grids') disp(' to bottom of Matlab path definition (use "File -> Set Path') disp(' on Matlab toolbar) or use full path name when specifying') disp(' Model name.') disp(' ') end [latlon_lims, H, mz, iob] = grd_in(GridName); [n,m]=size(H); [long,latg]=XY(latlon_lims, n, m); H=H'; return
github
fspaolo/tmdtoolbox-master
BLinterp_FernandoOld.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/BLinterp_FernandoOld.m
1,722
utf_8
1922e6ca524875c2f13e9ca3c937c1d1
% Bilinear interpolation (neigbouring NaNs avoided) % in point xt,yt % x(n),y(m) - coordinates for h(n,m) % xt(N),yt(N) - coordinates for interpolated values % Global case is considered ONLY for EXACTLY global solutions, % i.e. given in lon limits, satisfying: % ph_lim(2)-ph_lim(1)==360 % (thus for C-grid: x(end)-x(1)==360-dx ) % function [hi]=BLinterp(x,y,h,xt,yt); % dx=x(2)-x(1);dy=y(2)-y(1); glob=0; if x(end)-x(1)==360-dx,glob=1;end inan=find(isnan(h)>0); h(inan)=0; mz=(h~=0); n=length(x);m=length(y); [n1,m1]=size(h); if n~=n1 | m~=m1, fprintf('Check dimensions\n'); hi=NaN; return end % extend solution both sides for global if glob==1, h0=h;mz0=mz; [k1,k2]=size(x);if k1==1,x=x';end [k1,k2]=size(y);if k1==1,y=y';end % just for consistency x=[x(1)-2*dx;x(1)-dx;x;x(end)+dx;x(end)+2*dx]; h=[h(end-1,:);h(end,:);h;h(1,:);h(2,:)]; mz=[mz(end-1,:);mz(end,:);mz;mz(1,:);mz(2,:)]; end % Adjust lon convention xti=xt; ik=find(xti<x(1) | xti>x(end)); if x(end)>180,xti(ik)=xti(ik)+360;end if x(end)<0, xti(ik)=xti(ik)-360;end ik=find(xti>360); xti(ik)=xti(ik)-360; ik=find(xti<-180); xti(ik)=xti(ik)+360; % [X,Y]=meshgrid(x,y); q=1/(4+2*sqrt(2));q1=q/sqrt(2); h1=q1*h(1:end-2,1:end-2)+q*h(1:end-2,2:end-1)+q1*h(1:end-2,3:end)+... q1*h(3:end,1:end-2)+q*h(3:end,2:end-1)+q1*h(3:end,3:end)+... q*h(2:end-1,1:end-2)+q*h(2:end-1,3:end); mz1=q1*mz(1:end-2,1:end-2)+q*mz(1:end-2,2:end-1)+q1*mz(1:end-2,3:end)+... q1*mz(3:end,1:end-2)+q*mz(3:end,2:end-1)+q1*mz(3:end,3:end)+... q*mz(2:end-1,1:end-2)+q*mz(2:end-1,3:end); mz1(find(mz1==0))=1; h2=h; h2(2:end-1,2:end-1)=h1./mz1; ik=find(mz==1); h2(ik)=h(ik); h2(find(h2==0))=NaN; hi=interp2(X,Y,h2',xti,yt);hi=conj(hi); if glob==1, h=h0;mz=mz0;end return
github
fspaolo/tmdtoolbox-master
BLinterp.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/BLinterp.m
1,920
utf_8
4fe0030a891fa204e40bd640d0c9d1fe
% Bilinear interpolation (neigbouring NaNs avoided) % in point xt,yt % x(n),y(m) - coordinates for h(n,m) % xt(N),yt(N) - coordinates for interpolated values % Global case is considered ONLY for EXACTLY global solutions, % i.e. given in lon limits, satisfying: % ph_lim(2)-ph_lim(1)==360 % (thus for C-grid: x(end)-x(1)==360-dx ) % % usage: % [hi]=BLinterp(x,y,h,xt,yt,km); % km=1 if model is on Cartesian grid (km) otherwise 0 % function [hi]=BLinterp(x,y,h,xt,yt,km); % if nargin<5,km=0;end % dx=x(2)-x(1);dy=y(2)-y(1); glob=0; if km==0 & x(end)-x(1)==360-dx,glob=1;end inan=find(isnan(h)>0); h(inan)=0; mz=(h~=0); n=length(x);m=length(y); [n1,m1]=size(h); if n~=n1 | m~=m1, fprintf('Check dimensions\n'); hi=NaN; return end % extend solution both sides for global if glob==1, h0=h;mz0=mz; [k1,k2]=size(x);if k1==1,x=x';end [k1,k2]=size(y);if k1==1,y=y';end % just for consistency x=[x(1)-2*dx;x(1)-dx;x;x(end)+dx;x(end)+2*dx]; h=[h(end-1,:);h(end,:);h;h(1,:);h(2,:)]; mz=[mz(end-1,:);mz(end,:);mz;mz(1,:);mz(2,:)]; end % Adjust lon convention % THIS should be done only if km==0 !!!!!!! xti=xt; if km==0, ik=find(xti<x(1) | xti>x(end)); if x(end)>180,xti(ik)=xti(ik)+360;end if x(end)<0, xti(ik)=xti(ik)-360;end ik=find(xti>360); xti(ik)=xti(ik)-360; ik=find(xti<-180); xti(ik)=xti(ik)+360; end % [X,Y]=meshgrid(x,y); q=1/(4+2*sqrt(2));q1=q/sqrt(2); h1=q1*h(1:end-2,1:end-2)+q*h(1:end-2,2:end-1)+q1*h(1:end-2,3:end)+... q1*h(3:end,1:end-2)+q*h(3:end,2:end-1)+q1*h(3:end,3:end)+... q*h(2:end-1,1:end-2)+q*h(2:end-1,3:end); mz1=q1*mz(1:end-2,1:end-2)+q*mz(1:end-2,2:end-1)+q1*mz(1:end-2,3:end)+... q1*mz(3:end,1:end-2)+q*mz(3:end,2:end-1)+q1*mz(3:end,3:end)+... q*mz(2:end-1,1:end-2)+q*mz(2:end-1,3:end); mz1(find(mz1==0))=1; h2=h; h2(2:end-1,2:end-1)=h1./mz1; ik=find(mz==1); h2(ik)=h(ik); h2(find(h2==0))=NaN; hi=interp2(X,Y,h2',xti,yt);hi=conj(hi); if glob==1, h=h0;mz=mz0;end return
github
fspaolo/tmdtoolbox-master
grd_out.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/grd_out.m
879
utf_8
f14eb25e4e8c8441d2bd37b8ea24f018
% outputs a grid file in matlab % USAGE: grd_out(cfile,ll_lims,hz,mz,iob,dt); function grd_out(cfile,ll_lims,hz,mz,iob,dt); % open this way for files to be read on Unix machine fid = fopen(cfile,'w','b'); [dum,nob] = size(iob); [n,m] = size(hz); reclen = 32; fwrite(fid,reclen,'long'); fwrite(fid,n,'long'); fwrite(fid,m,'long'); fwrite(fid,ll_lims(3:4),'float'); fwrite(fid,ll_lims(1:2),'float'); fwrite(fid,dt,'float'); fwrite(fid,nob,'long'); fwrite(fid,reclen,'long'); % if nob == 0, fwrite(fid,4,'long'); fwrite(fid,0,'long'); fwrite(fid,4,'long'); else reclen=8*nob; fwrite(fid,reclen,'long'); fwrite(fid,iob,'long'); fwrite(fid,reclen,'long'); end % reclen = 4*n*m; fwrite(fid,reclen,'long'); fwrite(fid,hz,'float'); fwrite(fid,reclen,'long'); fwrite(fid,reclen,'long'); fwrite(fid,mz,'long'); fwrite(fid,reclen,'long'); fclose(fid); return
github
fspaolo/tmdtoolbox-master
harp1.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/harp1.m
1,023
utf_8
b4e5dab561d7307655a19e9b9737b508
% function to predict tidal time series % using harmonic constants % INPUT: time (days) relatively Jan 1, 1992 (48622mjd) % con(nc,4) - char*4 tidal constituent IDs % hc(nc) - harmonic constant vector (complex) % OUTPUT:hhat - time series reconstructed using HC % % Nodal corrections included % % usage: [hhat]=harp1(time,hc,con); % function [hhat]=harp1(time,hc,con) % ---- FP edits start here ---- L = length(time); n1 = size(time,1); if n1==1 time=time'; end nc=size(con,1); for k=1:nc [ispec(k),amp(k),ph(k),omega(k),alpha(k),cNum]=constit(con(k,:)); end % igood=find(ispec~=-1);ibad=find(ispec==-1); con1=con(igood,:); % [pu1,pf1]=nodal(time+48622,con1); pu=zeros(L,nc);pf=ones(L,nc); pu(:,igood)=pu1;pf(:,igood)=pf1; % hhat=zeros(size(time)); x=zeros(2*nc,1); x(1:2:end)=real(hc); x(2:2:end)=imag(hc); for k=1:nc arg= pf(:,k).*x(2*k-1).*cos(omega(k)*time*86400+ph(k)+pu(:,k))... - pf(:,k).*x(2*k) .*sin(omega(k)*time*86400+ph(k)+pu(:,k)); hhat=hhat+arg; end return
github
fspaolo/tmdtoolbox-master
xy_ll_CATS2008a_4km.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/xy_ll_CATS2008a_4km.m
308
utf_8
4cbc2a473f2a81dd51203287f338c523
% converts lat,lon to x,y(km) and back % usage: [x,y]=xy_ll_CATS2008a_4km(lon,lat,'F'); or % [lon,lat]=xy_ll_CATS2008a_4km(x,y,'B'); function [x2,y2]=xy_ll_CATS2008a_4km(x1,y1,BF); if BF=='F', % lat,lon ->x,y [x2,y2]=mapll(y1,x1,71,-70,'s'); else [y2,x2]=mapxy(x1,y1,71,-70,'s'); end return
github
fspaolo/tmdtoolbox-master
nodal.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/nodal.m
11,697
utf_8
966b2b2fe1211dc98f2557d8fb7fac9a
% ARGUMENTS and ASTROL FORTRAN subroutines SUPPLIED by RICHARD RAY, March 1999 % This is matlab remake of ARGUMENTS by Lana Erofeeva, Jan 2003 % NOTE - "no1" in constit.h corresponds to "M1" in arguments % usage: [pu,pf]=nodal(time,cid); % time - mjd, cid(nc,4) - tidal constituents array char*4 % pu(:,nc),pf(:,nc) - nodal corrections for the constituents % function [pu,pf]=nodal(time,cid); % cid0 = ['m2 ';'s2 ';'k1 ';'o1 '; ... 'n2 ';'p1 ';'k2 ';'q1 '; ... '2n2 ';'mu2 ';'nu2 ';'l2 '; ... 't2 ';'j1 ';'no1 ';'oo1 '; ... 'rho1';'mf ';'mm ';'ssa ';'m4 ';... 'ms4 ';'mn4 ']; % ------- FP edit start -------- cid01 = {'m2 ';'s2 ';'k1 ';'o1 '; ... 'n2 ';'p1 ';'k2 ';'q1 '; ... '2n2 ';'mu2 ';'nu2 ';'l2 '; ... 't2 ';'j1 ';'no1 ';'oo1 '; ... 'rho1';'mf ';'mm ';'ssa ';'m4 ';... 'ms4 ';'mn4 '}; % ------- FP edit end -------- index=[30,35,19,12,27,17,37,10,25,26,28,33,34,... 23,14,24,11,5,3,2,45,46,44]; % Determine equilibrium arguments % ------------------------------- pp=282.94; % solar perigee at epoch 2000 rad=pi/180; [n1,n2]=size(time); if n1==1,time=time';end [s,h,p,omega]=astrol(time); hour = (time - floor(time))*24.; t1 = 15*hour;t2 = 30.*hour; nT=length(t1); arg=zeros(nT,53); % arg is not needed for now, but let it be here % arg is kept in constit.m (phase_data) for time= Jan 1, 1992, 00:00 GMT arg(:, 1) = h - pp; % Sa arg(:, 2) = 2*h; % Ssa arg(:, 3) = s - p; % Mm arg(:, 4) = 2*s - 2*h; % MSf arg(:, 5) = 2*s; % Mf arg(:, 6) = 3*s - p; % Mt arg(:, 7) = t1 - 5*s + 3*h + p - 90; % alpha1 arg(:, 8) = t1 - 4*s + h + 2*p - 90; % 2Q1 arg(:, 9) = t1 - 4*s + 3*h - 90; % sigma1 arg(:,10) = t1 - 3*s + h + p - 90; % q1 arg(:,11) = t1 - 3*s + 3*h - p - 90; % rho1 arg(:,12) = t1 - 2*s + h - 90; % o1 arg(:,13) = t1 - 2*s + 3*h + 90; % tau1 arg(:,14) = t1 - s + h + 90; % M1 arg(:,15) = t1 - s + 3*h - p + 90; % chi1 arg(:,16) = t1 - 2*h + pp - 90; % pi1 arg(:,17) = t1 - h - 90; % p1 arg(:,18) = t1 + 90; % s1 arg(:,19) = t1 + h + 90; % k1 arg(:,20) = t1 + 2*h - pp + 90; % psi1 arg(:,21) = t1 + 3*h + 90; % phi1 arg(:,22) = t1 + s - h + p + 90; % theta1 arg(:,23) = t1 + s + h - p + 90; % J1 arg(:,24) = t1 + 2*s + h + 90; % OO1 arg(:,25) = t2 - 4*s + 2*h + 2*p; % 2N2 arg(:,26) = t2 - 4*s + 4*h; % mu2 arg(:,27) = t2 - 3*s + 2*h + p; % n2 arg(:,28) = t2 - 3*s + 4*h - p; % nu2 arg(:,29) = t2 - 2*s + h + pp; % M2a arg(:,30) = t2 - 2*s + 2*h; % M2 arg(:,31) = t2 - 2*s + 3*h - pp; % M2b arg(:,32) = t2 - s + p + 180.; % lambda2 arg(:,33) = t2 - s + 2*h - p + 180.; % L2 arg(:,34) = t2 - h + pp; % T2 arg(:,35) = t2; % S2 arg(:,36) = t2 + h - pp + 180; % R2 arg(:,37) = t2 + 2*h; % K2 arg(:,38) = t2 + s + 2*h - pp; % eta2 arg(:,39) = t2 - 5*s + 4.0*h + p; % MNS2 arg(:,40) = t2 + 2*s - 2*h; % 2SM2 arg(:,41) = 1.5*arg(:,30); % M3 arg(:,42) = arg(:,19) + arg(:,30); % MK3 arg(:,43) = 3*t1; % S3 arg(:,44) = arg(:,27) + arg(:,30); % MN4 arg(:,45) = 2*arg(:,30); % M4 arg(:,46) = arg(:,30) + arg(:,35); % MS4 arg(:,47) = arg(:,30) + arg(:,37); % MK4 arg(:,48) = 4*t1; % S4 arg(:,49) = 5*t1; % S5 arg(:,50) = 3*arg(:,30); % M6 arg(:,51) = 3*t2; % S6 arg(:,52) = 7.0*t1; % S7 arg(:,53) = 4*t2; % S8 % % determine nodal corrections f and u % ----------------------------------- sinn = sin(omega*rad); cosn = cos(omega*rad); sin2n = sin(2*omega*rad); cos2n = cos(2*omega*rad); sin3n = sin(3*omega*rad); %% f=zeros(nT,53); f(:,1) = 1; % Sa f(:,2) = 1; % Ssa f(:,3) = 1 - 0.130*cosn; % Mm f(:,4) = 1; % MSf f(:,5) = 1.043 + 0.414*cosn; % Mf f(:,6) = sqrt((1+.203*cosn+.040*cos2n).^2 + ... (.203*sinn+.040*sin2n).^2); % Mt f(:,7) = 1; % alpha1 f(:,8) = sqrt((1.+.188*cosn).^2+(.188*sinn).^2);% 2Q1 f(:,9) = f(:,8); % sigma1 f(:,10) = f(:,8); % q1 f(:,11) = f(:,8); % rho1 f(:,12) = sqrt((1.0+0.189*cosn-0.0058*cos2n).^2 + ... (0.189*sinn-0.0058*sin2n).^2);% O1 f(:, 13) = 1; % tau1 % tmp1 = 2.*cos(p*rad)+.4*cos((p-omega)*rad); % tmp2 = sin(p*rad)+.2*sin((p-omega)*rad);% Doodson's tmp1 = 1.36*cos(p*rad)+.267*cos((p-omega)*rad);% Ray's tmp2 = 0.64*sin(p*rad)+.135*sin((p-omega)*rad); f(:,14) = sqrt(tmp1.^2 + tmp2.^2); % M1 f(:,15) = sqrt((1.+.221*cosn).^2+(.221*sinn).^2);% chi1 f(:,16) = 1; % pi1 f(:,17) = 1; % P1 f(:,18) = 1; % S1 f(:,19) = sqrt((1.+.1158*cosn-.0029*cos2n).^2 + ... (.1554*sinn-.0029*sin2n).^2); % K1 f(:,20) = 1; % psi1 f(:,21) = 1; % phi1 f(:,22) = 1; % theta1 f(:,23) = sqrt((1.+.169*cosn).^2+(.227*sinn).^2); % J1 f(:,24) = sqrt((1.0+0.640*cosn+0.134*cos2n).^2 + ... (0.640*sinn+0.134*sin2n).^2 ); % OO1 f(:,25) = sqrt((1.-.03731*cosn+.00052*cos2n).^2 + ... (.03731*sinn-.00052*sin2n).^2);% 2N2 f(:,26) = f(:,25); % mu2 f(:,27) = f(:,25); % N2 f(:,28) = f(:,25); % nu2 f(:,29) = 1; % M2a f(:,30) = f(:,25); % M2 f(:,31) = 1; % M2b f(:,32) = 1; % lambda2 temp1 = 1.-0.25*cos(2*p*rad)-0.11*cos((2*p-omega)*rad)-0.04*cosn; temp2 = 0.25*sin(2*p*rad)+0.11*sin((2*p-omega)*rad)+ 0.04*sinn; f(:,33) = sqrt(temp1.^2 + temp2.^2); % L2 f(:,34) = 1; % T2 f(:,35) = 1; % S2 f(:,36) = 1; % R2 f(:,37) = sqrt((1.+.2852*cosn+.0324*cos2n).^2 + ... (.3108*sinn+.0324*sin2n).^2); % K2 f(:,38) = sqrt((1.+.436*cosn).^2+(.436*sinn).^2); % eta2 f(:,39) = f(:,30).^2; % MNS2 f(:,40) = f(:,30); % 2SM2 f(:,41) = 1; % wrong % M3 f(:,42) = f(:,19).*f(:,30); % MK3 f(:,43) = 1; % S3 f(:,44) = f(:,30).^2; % MN4 f(:,45) = f(:,44); % M4 f(:,46) = f(:,44); % MS4 f(:,47) = f(:,30).*f(:,37); % MK4 f(:,48) = 1; % S4 f(:,49) = 1; % S5 f(:,50) = f(:,30).^3; % M6 f(:,51) = 1; % S6 f(:,52) = 1; % S7 f(:,53) = 1; % S8 % u=zeros(nT,53); u(:, 1) = 0; % Sa u(:, 2) = 0; % Ssa u(:, 3) = 0; % Mm u(:, 4) = 0; % MSf u(:, 5) = -23.7*sinn + 2.7*sin2n - 0.4*sin3n; % Mf u(:, 6) = atan(-(.203*sinn+.040*sin2n)./... (1+.203*cosn+.040*cos2n))/rad; % Mt u(:, 7) = 0; % alpha1 u(:, 8) = atan(.189*sinn./(1.+.189*cosn))/rad; % 2Q1 u(:, 9) = u(:,8); % sigma1 u(:,10) = u(:,8); % q1 u(:,11) = u(:,8); % rho1 u(:,12) = 10.8*sinn - 1.3*sin2n + 0.2*sin3n; % O1 u(:,13) = 0; % tau1 u(:,14) = atan2(tmp2,tmp1)/rad; % M1 u(:,15) = atan(-.221*sinn./(1.+.221*cosn))/rad; % chi1 u(:,16) = 0; % pi1 u(:,17) = 0; % P1 u(:,18) = 0; % S1 u(:,19) = atan((-.1554*sinn+.0029*sin2n)./... (1.+.1158*cosn-.0029*cos2n))/rad; % K1 u(:,20) = 0; % psi1 u(:,21) = 0; % phi1 u(:,22) = 0; % theta1 u(:,23) = atan(-.227*sinn./(1.+.169*cosn))/rad; % J1 u(:,24) = atan(-(.640*sinn+.134*sin2n)./... (1.+.640*cosn+.134*cos2n))/rad; % OO1 u(:,25) = atan((-.03731*sinn+.00052*sin2n)./ ... (1.-.03731*cosn+.00052*cos2n))/rad; % 2N2 u(:,26) = u(:,25); % mu2 u(:,27) = u(:,25); % N2 u(:,28) = u(:,25); % nu2 u(:,29) = 0; % M2a u(:,30) = u(:,25); % M2 u(:,31) = 0; % M2b u(:,32) = 0; % lambda2 u(:,33) = atan(-temp2./temp1)/rad ; % L2 u(:,34) = 0; % T2 u(:,35) = 0; % S2 u(:,36) = 0; % R2 u(:,37) = atan(-(.3108*sinn+.0324*sin2n)./ ... (1.+.2852*cosn+.0324*cos2n))/rad; % K2 u(:,38) = atan(-.436*sinn./(1.+.436*cosn))/rad; % eta2 u(:,39) = u(:,30)*2; % MNS2 u(:,40) = u(:,30); % 2SM2 u(:,41) = 1.5d0*u(:,30); % M3 u(:,42) = u(:,30) + u(:,19); % MK3 u(:,43) = 0; % S3 u(:,44) = u(:,30)*2; % MN4 u(:,45) = u(:,44); % M4 u(:,46) = u(:,30); % MS4 u(:,47) = u(:,30)+u(:,37); % MK4 u(:,48) = 0; % S4 u(:,49) = 0; % S5 u(:,50) = u(:,30)*3; % M6 u(:,51) = 0; % S6 u(:,52) = 0; % S7 u(:,53) = 0; % S8 % set correspondence between given constituents and supported in OTIS [ncmx,dum]=size(cid0); for ic=1:ncmx PU(:,ic)=u(:,index(ic))*rad; PF(:,ic)=f(:,index(ic)); end % take pu,pf for the set of given cid only [nc,dum]=size(cid); pu=[];pf=[]; % ------- FP edit start -------- idx = zeros(nc,1); for ic = 1:nc foo = find(strcmpi(cid(ic,:), cid01)); if ~isempty(foo) idx(ic) = foo; end end pu=PU(:,idx); pf=PF(:,idx); %size(pu) %pu=[];pf=[]; %for ic=1:nc % ic0=0; % for k=1:ncmx % if cid(ic,:)==cid0(k,:),ic0=k;break;end % end % if ic0>0, % pu=[pu,PU(:,ic0)]; % pf=[pf,PF(:,ic0)]; % end %end % ------- FP edit end -------- return
github
fspaolo/tmdtoolbox-master
xy_ll_S.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/xy_ll_S.m
484
utf_8
19e121c4e6ed5500867a96e8db934718
% converts lat,lon to x,y(km) and back for Antarctic % (x,y)=(0,0) corresponds to lon=135W, lon=0 points up % usage: [x,y]=xy_ll_S(lon,lat,'F'); or % [lon,lat]=xy_ll_S(x,y,'B'); function [x,y]=xy_ll_S(lon,lat,BF); if BF=='F', % lat,lon ->x,y x=-(90.+lat)*111.7.*cos((90+lon)./180.*pi); y= (90.+lat)*111.7.*sin((90+lon)./180.*pi); else x=lon;y=lat; lat=-90+sqrt(x.^2+y.^2)/111.7; lon=-atan2(y,x)*180/pi+90; ii=find(lon<0); lon(ii)=lon(ii)+360; x=lon;y=lat; end return
github
fspaolo/tmdtoolbox-master
grd_in.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/grd_in.m
753
utf_8
2f949135185e056a2a2d7a4e4977887b
% reads a grid file in matlab % USAGE: [ll_lims,hz,mz,iob,dt] = grd_in(cfile); % Location: C:\Toolboxes\TMD\FUNCTIONS function [ll_lims,hz,mz,iob,dt] = grd_in(cfile); fid = fopen(cfile,'r','b'); fseek(fid,4,'bof'); n = fread(fid,1,'long'); m = fread(fid,1,'long'); lats = fread(fid,2,'float'); lons = fread(fid,2,'float'); dt = fread(fid,1,'float'); if(lons(1) < 0) & (lons(2) < 0 ) & dt>0, lons = lons + 360; end ll_lims = [lons ; lats ]; %fprintf('Time step (sec): %10.1f\n',dt); nob = fread(fid,1,'long'); if nob == 0, fseek(fid,20,'cof'); iob = []; else fseek(fid,8,'cof'); iob = fread(fid,[2,nob],'long'); fseek(fid,8,'cof'); end hz = fread(fid,[n,m],'float'); fseek(fid,8,'cof'); mz = fread(fid,[n,m],'long'); fclose(fid);
github
fspaolo/tmdtoolbox-master
harp.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/harp.m
1,089
utf_8
24e7f03475cbbbd9867420ee32afa2f5
% function to predict tidal elevation fields at "time" % using harmonic constants % INPUT: time (days) relatively Jan 1, 1992 (48622mjd) % con(nc,4) - char*4 tidal constituent IDs % hc(n,m,nc) - harmonic constant vector (complex) % OUTPUT:hhat - tidal field at time % % Nodal corrections included % % usage: [hhat]=harp(time,hc,con); % % see harp1 for making time series at ONE location % function [hhat]=harp(time,hc,con); [n,m,nc]=size(hc);hhat=zeros(n,m); [nc1,dum]=size(con); if nc1~=nc, fprintf('Imcompatible hc and con: check dimensions\n'); return end if length(time)>1,time=time(1);end for k=1:nc [ispec(k),amp(k),ph(k),omega(k),alpha(k),cNum]=constit(con(k,:)); end % igood=find(ispec~=-1); con1=con(igood,:); % [pu1,pf1]=nodal(time+48622,con1); pu=zeros(1,nc);pf=ones(1,nc); pu(igood)=pu1;pf(igood)=pf1; % x=zeros(n,m,2*nc); x(:,:,1:2:end)=real(hc); x(:,:,2:2:end)=imag(hc); for k=1:nc arg= pf(k)*x(:,:,2*k-1)*cos(omega(k)*time*86400+ph(k)+pu(k))... - pf(k)*x(:,:,2*k) *sin(omega(k)*time*86400+ph(k)+pu(k)); hhat=hhat+arg; end return
github
fspaolo/tmdtoolbox-master
xy_ll.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/xy_ll.m
392
utf_8
31802e1c496760dab7cd268c390940ed
% converts lat,lon to x,y(km) and back % usage: [x,y]=xy_ll(lon,lat,'F'); or % [lon,lat]=xy_ll(x,y,'B'); function [x,y]=xy_ll(lon,lat,BF); if BF=='F', % lat,lon ->x,y x=(90.-lat)*111.7.*cos(lon./180.*pi); y=(90.-lat)*111.7.*sin(lon./180.*pi); else x=lon;y=lat; lat=90-sqrt(x.^2+y.^2)/111.7; lon=atan2(y,x)*180/pi; ii=find(lon<0); lon(ii)=lon(ii)+360; x=lon;y=lat; end return
github
fspaolo/tmdtoolbox-master
checkTypeName.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/checkTypeName.m
1,407
utf_8
aa1bba0ee0f751a2f55a2c6845c5877b
% returns Flag=0, if ModName, GridName & type OK % Flag>0, if they are not or files do not exist % Flag<0, if not possible to define % usage: [Flag]=checkTypeName(ModName,GridName,type); function [Flag]=checkTypeName(ModName,GridName,type); Flag=0; % check if files exist if exist(ModName,'file')==0, fprintf('File %s NOT found\n',ModName); Flag=1; return end if exist(GridName,'file')==0, fprintf('File %s NOT found\n',GridName); Flag=1; return end type=deblank(type);btype=deblank(type(end:-1:1)); type=btype(end:-1:1);type=type(1:1); % Check type if type~='z' & type~='U'& type~='u'& type~='V' & type~='v', fprintf('WRONG TYPE %s: should be one of: ''z'',''U'',''u'',''V'',''v''\n',type); Flag=2; return end % Check type/name correspondence i1=findstr(ModName,'/'); if isempty(i1)>0,i1=1;else i1=i1(end)+1;end if ModName(i1:i1)=='h', if type=='U'| type=='u'|type=='V'| type=='v', fprintf('For file %s only legal type is ''z'' (%s given)\n',... ModName(i1:end),type); Flag=3; return end elseif ModName(i1:i1)=='u' | ModName(i1:i1)=='U', if type=='z', fprintf('For file %s legal types are: ''U'',''u'',''V'',''v'' (%s given)\n',... ModName(i1:end),type); Flag=4; return end else fprintf('WARNING: Model name %s does not correspond TMD convention:\n',ModName(i1:end)); fprintf('Can not check type %s:...\n',type); Flag=-1; end return
github
fspaolo/tmdtoolbox-master
constit.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/constit.m
3,740
utf_8
5861b866d79ae0fff23d8a9db7b2e0d0
% constit returns amplitude, phase, frequency,alpha, species for % a tidal constituent identified by a 4 character string % This version returns zeros for all phases % Usage: [ispec,amp,ph,omega,alpha,constitNum] = constit(c); function [ispec,amp,ph,omega,alpha,constitNum] = constit(c); ispec=-1; amp=0;ph=0;omega=0;alpha=0;constitNum=0; if( nargout < 6) fprintf('Number of output arguments to constit.m does not agree with current usage\n'); end % c : character string ID of constituents that the program knows about % all other variables are in the same order % ------- FP edit start -------- % c_data = ['m2 ';'s2 ';'k1 ';'o1 '; ... % 'n2 ';'p1 ';'k2 ';'q1 '; ... % '2n2 ';'mu2 ';'nu2 ';'l2 '; ... % 't2 ';'j1 ';'no1 ';'oo1 '; ... % 'rho1';'mf ';'mm ';'ssa ';'m4 ';'ms4 ';'mn4 ' ]; c_data1 = {'m2 ';'s2 ';'k1 ';'o1 '; ... 'n2 ';'p1 ';'k2 ';'q1 '; ... '2n2 ';'mu2 ';'nu2 ';'l2 '; ... 't2 ';'j1 ';'no1 ';'oo1 '; ... 'rho1';'mf ';'mm ';'ssa ';'m4 ';'ms4 ';'mn4 ' }; % ------- FP edit end -------- constitNum_data = [1,2,5,6,... 3,7,4,8,... 0,0,0,0,... 0,0,0,0,... 0,0,0,0,0,0,0]; % ispec : species type (spherical harmonic dependence of quadropole potential) ispec_data = [2;2;1;1; ... 2;1;2;1; ... 2;2;2;2; ... 2;1;1;1; ... 1;0;0;0;0;0;0]; % alpha : loading love number ... frequncy dependance here is suspect alpha_data = [ 0.693;0.693;0.736;0.695; ... 0.693;0.706;0.693;0.695; ... 0.693;0.693;0.693;0.693; ... 0.693;0.693;0.693;0.693; ... 0.693;0.693;0.693;0.693;0.693;0.693;0.693]; % omega : frequencies omega_data = [1.405189e-04;1.454441e-04;7.292117e-05;6.759774e-05; ... 1.378797e-04;7.252295e-05;1.458423e-04;6.495854e-05; ... 1.352405e-04;1.355937e-04;1.382329e-04;1.431581e-04; ... 1.452450e-04;7.556036e-05;7.028195e-05;7.824458e-05; ... 6.531174e-05;0.053234e-04;0.026392e-04;0.003982e-04; ... 2.810377e-04;2.859630e-04;2.783984e-04]; % phase : Astronomical arguments (relative to t0 = 1 Jan 0:00 1992] % Richrad Ray subs: "arguments" and "astrol" phase_data = [ 1.731557546;0.000000000;0.173003674;1.558553872;... 6.050721243;6.110181633;3.487600001;5.877717569; 4.086699633;3.463115091;5.427136701;0.553986502; 0.052841931;2.137025284;2.436575100;1.929046130; 5.254133027;1.756042456;1.964021610;3.487600001; 3.463115091;1.731557546;1.499093481]; % amp : amplitudes %amp_data = [0.242334;0.112743;0.141565;0.100661; ... amp_data = [0.2441 ;0.112743;0.141565;0.100661; ... 0.046397;0.046848;0.030684;0.019273; ... 0.006141;0.007408;0.008811;0.006931; ... 0.006608;0.007915;0.007915;0.004338; ... 0.003661;0.042041;0.022191;0.019567;0;0;0]; nspecies = length(ispec_data); nl = length(c); % kk = 0; % for k = 1:nspecies % if(lower(c) == c_data(k,1:nl)) , % kk = k; % break % end % end % % if(kk == 0 ), % ispec = -1; % return % else % constitNum = constitNum_data(kk); % ispec = ispec_data(kk); % amp = amp_data(kk); % alpha = alpha_data(kk); % omega = omega_data(kk); % % ph = 0; % ph = phase_data(kk); % end % ------- FP edit start -------- if nl ~= 4 error('length of c must = 4') end kk = strcmpi(c, c_data1); if ~any(kk) ispec = -1; return else constitNum = constitNum_data(kk); ispec = ispec_data(kk); amp = amp_data(kk); alpha = alpha_data(kk); omega = omega_data(kk); % ph = 0; ph = phase_data(kk); end % ------- FP edit end -------- return
github
fspaolo/tmdtoolbox-master
astrol.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/astrol.m
1,101
utf_8
d2db9a01c06a48292ad7b7f4a26e7372
% Computes the basic astronomical mean longitudes s, h, p, N. % Note N is not N', i.e. N is decreasing with time. % These formulae are for the period 1990 - 2010, and were derived % by David Cartwright (personal comm., Nov. 1990). % time is UTC in decimal MJD. % All longitudes returned in degrees. % R. D. Ray Dec. 1990 % Non-vectorized version. Re-make for matlab by Lana Erofeeva, 2003 % usage: [s,h,p,N]=astrol(time) % time, MJD function [s,h,p,N]=astrol(time); circle=360; T = time - 51544.4993; % mean longitude of moon % ---------------------- s = 218.3164 + 13.17639648 * T; % mean longitude of sun % --------------------- h = 280.4661 + 0.98564736 * T; % mean longitude of lunar perigee % ------------------------------- p = 83.3535 + 0.11140353 * T; % mean longitude of ascending lunar node % -------------------------------------- N = 125.0445D0 - 0.05295377D0 * T; % s = mod(s,circle); h = mod(h,circle); p = mod(p,circle); N = mod(N,circle); % if s<0, s = s + circle; end if h<0, h = h + circle; end if p<0, p = p + circle; end if N<0, N = N + circle; end return
github
fspaolo/tmdtoolbox-master
rd_con.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/rd_con.m
375
utf_8
ddb5daf0d42c644afb62b724e5b0e05c
% read constituents from h*out or u*out file % usage: [conList]=rd_con(fname); function [conList]=rd_con(fname); fid = fopen(fname,'r','b'); ll = fread(fid,1,'long'); nm = fread(fid,3,'long'); n=nm(1); m = nm(2); nc = nm(3); th_lim = fread(fid,2,'float'); ph_lim = fread(fid,2,'float'); C=fread(fid,nc*4,'uchar'); C=reshape(C,4,nc);C=C'; conList=char(C); fclose(fid); return
github
fspaolo/tmdtoolbox-master
rdModFile.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/rdModFile.m
1,616
utf_8
70c71135dfca84f60f59ac4fa0b60603
% function to read model control file % usage: % [ModName,GridName,Fxy_ll]=rdModFile(Model,k); % % Model - control file name for a tidal model, consisting of lines % <elevation file name> % <transport file name> % <grid file name> % <function to convert lat,lon to x,y> % 4th line is given only for models on cartesian grid (in km) % All model files should be provided in OTIS format % k =1/2 for elevations/transports % % OUTPUT % ModName - model file name for elvations/transports % GridName - grid file name % Fxy_ll - function to convert lat,lon to x,y % (only for models on cartesian grid (in km)); % If model is on lat/lon grid Fxy_ll=[]; function [ModName,GridName,Fxy_ll]=rdModFile(Model,k); i1=findstr(Model,'/'); pname=[]; if isempty(i1)==0,pname=Model(1:i1(end));end fid=fopen(Model,'r'); ModName=[];GridName=[];Fxy_ll=[]; if fid<1,fprintf('File %s does not exist\n',Model);return;end hfile=fgetl(fid); ufile=fgetl(fid); gfile=fgetl(fid); i1=findstr(hfile,'/');if isempty(i1)>0,i1=findstr(hfile,'\');end i2=findstr(ufile,'/');if isempty(i2)>0,i2=findstr(ufile,'\');end i3=findstr(gfile,'/');if isempty(i3)>0,i3=findstr(gfile,'\');end if isempty(i3)==0,GridName=gfile;else GridName=[pname gfile];end if k==1 & isempty(i1)==0,pname=[];end if k==2 & isempty(i2)==0,pname=[];end if k==1,ModName=[pname hfile];else ModName=[pname ufile];end Fxy_ll=fgetl(fid); if Fxy_ll==-1,Fxy_ll=[];end fclose(fid); % check if the file exist fid=fopen(ModName,'r'); if fid<1,fprintf('File does not exist: %s\n',ModName); ModName=[];GridName=[];return;end % return
github
fspaolo/tmdtoolbox-master
InferMinor.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/InferMinor.m
6,069
utf_8
8e1f23c7f63461086e8fbb1c99876a95
% Lana Erofeeva, re-make for matlab OCT 2004 % usage: % [dh]=InferMinor(zmaj,cid,SDtime); % % Based on Richard Ray's code perth2 % Return correction for the 16 minor constituents % zeros, if not enough input constituents for inference % Input: % cid(ncon,4) - GIVEN constituents % zmaj(ncon,... - Complex HC for GIVEN constituents/points % SDtime(... - time expressed in Serial Days (see help datenum) % Modes: % Time series: zmaj(ncon,1), SDtime(nt,1) ->Output: dh(nt,1) % Drift Track: zmaj(ncon,nt), SDtime(nt,1) ->Output: dh(nt,1) % Map: zmaj(ncon,N,M),SDtime(1,1) ->Output: dh(N,M) % ------------------------------------------------------------------- function [dh]=InferMinor(zmaj,cid,SDtime); rad=pi/180;PP=282.8;dh=NaN; % check size [ncon,dum]=size(cid); if dum~=4, fprintf('InferMinor call: Wrong constituents\n');return;end [n1,n2,n3]=size(zmaj); if n1~=ncon,zmaj=conj(zmaj');[n1,n2,n3]=size(zmaj);end if n1~=ncon,fprintf('InferMinor call: Wrong zmaj size\n');return;end TimeSeries=0;DriftTrack=0;TMap=0; nt=length(SDtime); %[n1 n2 n3 nt] if n2==1 & n3==1, TimeSeries=1;N=nt;M=1; elseif n3==1 & n2>1 & nt==n2, DriftTrack=1;N=nt;M=1; elseif n2>1 & nt==1, TMap=1; N=n2;M=n3; else fprintf('InferMinor call: Wrong zmaj/SDtime size\n'); return; end % dh=zeros(N,M); d0=datenum(1992,1,1); % corresponds to 48622mjd d1=SDtime; time=d1-d0; % time (days) relatively Jan 1 1992 GMT time_mjd=48622+time; [ncon,dum]=size(cid); cid8=['q1 ';'o1 ';'p1 ';'k1 ';'n2 ';'m2 ';'s2 ';'k2 ']; % re-order zmaj to correspond to cid8 z8=zeros(8,N,M); ni=0; % ------- FP edit start -------- for i1=1:8 if any(all(cid == cid8(i1,:),2)) idx = all(cid == cid8(i1,:),2); z8(i1,:,:) = zmaj(idx,:,:); if(i1~=3 && i1~=8), ni=ni+1; end end end % for i1=1:8 % for j1=1:ncon % if cid(j1,:) == cid8(i1,:) % z8(i1,:,:) = zmaj(j1,:,:); % if(i1~=3 && i1~=8), ni=ni+1; end % end % end % end % ------- FP edit end -------- if ni<6,return;end % not enough constituents for inference % zmin=zeros(18,N,M); zmin(1,:,:) = 0.263 *z8(1,:,:) - 0.0252*z8(2,:,:); %2Q1 zmin(2,:,:) = 0.297 *z8(1,:,:) - 0.0264*z8(2,:,:); %sigma1 zmin(3,:,:) = 0.164 *z8(1,:,:) + 0.0048*z8(2,:,:); %rho1 + zmin(4,:,:) = 0.0140*z8(2,:,:) + 0.0101*z8(4,:,:); %M1 zmin(5,:,:) = 0.0389*z8(2,:,:) + 0.0282*z8(4,:,:); %M1 zmin(6,:,:) = 0.0064*z8(2,:,:) + 0.0060*z8(4,:,:); %chi1 zmin(7,:,:) = 0.0030*z8(2,:,:) + 0.0171*z8(4,:,:); %pi1 zmin(8,:,:) =-0.0015*z8(2,:,:) + 0.0152*z8(4,:,:); %phi1 zmin(9,:,:) =-0.0065*z8(2,:,:) + 0.0155*z8(4,:,:); %theta1 zmin(10,:,:) =-0.0389*z8(2,:,:) + 0.0836*z8(4,:,:); %J1 + zmin(11,:,:) =-0.0431*z8(2,:,:) + 0.0613*z8(4,:,:); %OO1 + zmin(12,:,:) = 0.264 *z8(5,:,:) - 0.0253*z8(6,:,:); %2N2 + zmin(13,:,:) = 0.298 *z8(5,:,:) - 0.0264*z8(6,:,:); %mu2 + zmin(14,:,:) = 0.165 *z8(5,:,:) + 0.00487*z8(6,:,:); %nu2 + zmin(15,:,:) = 0.0040*z8(6,:,:) + 0.0074*z8(7,:,:); %lambda2 zmin(16,:,:) = 0.0131*z8(6,:,:) + 0.0326*z8(7,:,:); %L2 + zmin(17,:,:) = 0.0033*z8(6,:,:) + 0.0082*z8(7,:,:); %L2 + zmin(18,:,:) = 0.0585*z8(7,:,:); %t2 + % hour = (time - floor(time))*24.D0; t1 = 15.*hour; t2 = 30.*hour; [S,H,P,omega]=astrol(time_mjd); % nsites x nt % arg=zeros(18,N,M); arg(1,:,:) = t1 - 4.*S + H + 2.*P - 90.; % 2Q1 arg(2,:,:) = t1 - 4.*S + 3.*H - 90.; % sigma1 arg(3,:,:) = t1 - 3.*S + 3.*H - P - 90.; % rho1 arg(4,:,:) = t1 - S + H - P + 90.; % M1 arg(5,:,:) = t1 - S + H + P + 90.; % M1 arg(6,:,:) = t1 - S + 3.*H - P + 90.; % chi1 arg(7,:,:) = t1 - 2.*H + PP - 90.; % pi1 arg(8,:,:) = t1 + 3.*H + 90.; % phi1 arg(9,:,:) = t1 + S - H + P + 90.; % theta1 arg(10,:,:) = t1 + S + H - P + 90.; % J1 arg(11,:,:) = t1 + 2.*S + H + 90.; % OO1 arg(12,:,:) = t2 - 4.*S + 2.*H + 2.*P; % 2N2 arg(13,:,:) = t2 - 4.*S + 4.*H; % mu2 arg(14,:,:) = t2 - 3.*S + 4.*H - P; % nu2 arg(15,:,:) = t2 - S + P + 180.D0; % lambda2 arg(16,:,:) = t2 - S + 2.*H - P + 180.D0; % L2 arg(17,:,:) = t2 - S + 2.*H + P; % L2 arg(18,:,:) = t2 - H + PP; % t2 % % determine nodal corrections f and u sinn = sin(omega*rad); cosn = cos(omega*rad); sin2n = sin(2.*omega*rad); cos2n = cos(2.*omega*rad); f = ones(18,N,M); f(1,:,:) = sqrt((1.0 + 0.189*cosn - 0.0058*cos2n).^2 +... (0.189*sinn - 0.0058*sin2n).^2); f(2,:,:) = f(1,:,:); f(3,:,:) = f(1); f(4,:,:) = sqrt((1.0 + 0.185*cosn).^2 + (0.185*sinn).^2); f(5,:,:) = sqrt((1.0 + 0.201*cosn).^2 + (0.201*sinn).^2); f(6,:,:) = sqrt((1.0 + 0.221*cosn).^2 + (0.221*sinn).^2); f(10,:,:) = sqrt((1.0 + 0.198*cosn).^2 + (0.198*sinn).^2); f(11,:,:) = sqrt((1.0 + 0.640*cosn + 0.134*cos2n).^2 +... (0.640*sinn + 0.134*sin2n).^2 ); f(12,:,:) = sqrt((1.0 - 0.0373*cosn).^2 + (0.0373*sinn).^2); f(13,:,:) = f(12,:,:); f(14,:,:) = f(12,:,:); f(16,:,:) = f(12,:,:); f(17,:,:) = sqrt((1.0 + 0.441*cosn).^2 + (0.441*sinn).^2); % u = zeros(18,N,M); u(1,:,:) = atan2(0.189*sinn - 0.0058*sin2n,... 1.0 + 0.189*cosn - 0.0058*sin2n)/rad; u(2,:,:) = u(1,:,:); u(3,:,:) = u(1,:,:); u(4,:,:) = atan2( 0.185*sinn, 1.0 + 0.185*cosn)/rad; u(5,:,:) = atan2(-0.201*sinn, 1.0 + 0.201*cosn)/rad; u(6,:,:) = atan2(-0.221*sinn, 1.0 + 0.221*cosn)/rad; u(10,:,:) = atan2(-0.198*sinn, 1.0 + 0.198*cosn)/rad; u(11,:,:) = atan2(-0.640*sinn - 0.134*sin2n,... 1.0 + 0.640*cosn + 0.134*cos2n)/rad; u(12,:,:) = atan2(-0.0373*sinn, 1.0 - 0.0373*cosn)/rad; u(13,:,:) = u(12,:,:); u(14,:,:) = u(12,:,:); u(16,:,:) = u(12,:,:); u(17,:,:) = atan2(-0.441*sinn, 1.0 + 0.441*cosn)/rad; % sum over all tides % ------------------ for k=1:18 tmp=squeeze(real(zmin(k,:,:)).*f(k,:,:).*... cos((arg(k,:,:) + u(k,:,:))*rad)-... imag(zmin(k,:,:)).*f(k,:,:).*... sin((arg(k,:,:)+u(k,:,:))*rad)); [n1,n2]=size(tmp);if n1==1,tmp=tmp';end dh(:,:) = dh(:,:) + tmp; end return
github
fspaolo/tmdtoolbox-master
TideEl.m
.m
tmdtoolbox-master/tmd_toolbox/FUNCTIONS/TideEl.m
1,158
utf_8
0b67ba4eb9e827c8d9721e6adfdcb423
% calculates tidal ellipse parameters for the arrays of % u and v - COMPLEX amplitudes of EW and NS currents of % a given tidal constituent % land should be set to 0 or NaN in u,v prior to calling tideEl % usage: [umajor,uminor,uincl,uphase]=tideEl(u,v); function [umajor,uminor,uincl,uphase]=tideEl(u,v); % change to polar coordinates % in Robin's was - + + -, this is as in Foreman's t1p = (real (u) - imag(v)); t2p = (real (v) + imag(u)); t1m = (real (u) + imag(v)); t2m = (real (v) - imag(u)); % ap, am - amplitudes of positevely and negatively % rotated vectors ap = sqrt( (t1p.^2 + t2p.^2)) / 2.; am = sqrt( (t1m.^2 + t2m.^2)) / 2.; % ep, em - phases of positively and negatively rotating vectors ep = atan2( t2p, t1p); ep = ep + 2 * pi * (ep < 0.0); ep = 180. * ep / pi; em = atan2( t2m, t1m); em = em + 2 * pi * (em < 0.0); em = 180. * em / pi; % determine the major and minor axes, phase and inclination using Foreman's formula umajor = (ap + am); uminor = (ap - am); uincl = 0.5 * (em + ep); uincl = uincl - 180. * (uincl > 180); uphase = - 0.5*(ep-em) ; uphase = uphase + 360. * (uphase < 0); uphase = uphase - 360. * (uphase >= 360); return
github
Xyuan13/MSRNet-master
classification_demo.m
.m
MSRNet-master/deeplab-caffe/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
Xyuan13/MSRNet-master
MySaliencyEval.m
.m
MSRNet-master/deeplab-caffe/matlab/my_script/MySaliencyEval.m
5,922
utf_8
c1fbf9a95de1539c35958d9759de81fe
%MSRAEVALSEG Evaluates a set of segmentation results. % MSRAEVALSEG(MSRAopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = MSRAEVALSEG(MSRAopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = MSRAEVALSEG(MSRAopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [conf,rawcounts] = MySaliencyEval(salopts,id) % image test set [gtids,t]=textread(sprintf(salopts.imgsetpath,salopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = salopts.nclasses+1; confcounts = zeros(num); count=0; sum_mean=0; num_missing_img = 0; tic; img_num = length(gtids); %precision and recall of all images ALLPRECISION = zeros(img_num, 256); ALLRECALL = zeros(img_num, 256); for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % fprintf('%d %s', i, imname); % ground truth label file gtfile = sprintf(salopts.annopath,imname); %disp(['gtfile ' gtfile]) [gtim,map] = imread(gtfile); gtim = double(gtim); if max(gtim(:) > 1) % not logical gtim = (gtim == 255); end % results file resfile = sprintf(salopts.respath, imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % --- PR Curve --- [precision, recall] = CalPR(resim, gtim, true, true); ALLPRECISION(i, :) = precision; ALLRECALL(i, :) = recall; % --- MAE --- if max(resim(:)) > 1 resim = double(resim / 255); end diff=abs(gtim-resim); sum_mean = sum_mean + mean(mean(diff)); % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; %MAE MAE = sum_mean / length(gtids); fprintf('-------------------------\n'); fprintf('Mean absolute error (MAE): %6.3f\n',MAE); % saliency_idx = 2; % denom = sum(confcounts(saliency_idx, :)); % if (denom == 0) % denom = 1; % end % precision = 100 * confcounts(saliency_idx, saliency_idx) / denom; % denom = sum(confcounts(:,saliency_idx)); % if (denom == 0) % denom = 1; % end % recall = 100 * confcounts(saliency_idx, saliency_idx) / denom; % % fprintf('Saliency Precision: %6.3f%%\n',precision); % fprintf('Saliency Recall: %6.3f%%\n',recall); % % Class Accuracy % class_acc = zeros(1, num); % class_count = 0; % fprintf('-------------------------\n'); % fprintf('Accuracy for each class (pixel accuracy)\n'); % for i = 1 : num-1 % denom = sum(confcounts(i, :)); % if (denom == 0) % denom = 1; % end % class_acc(i) = 100 * confcounts(i, i) / denom; % if i == 1 % clname = 'background'; % else % clname = salopts.classes{i-1}; % end % % if ~strcmp(clname, 'void') % class_count = class_count + 1; % fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); % end % end % % avg_class_acc = sum(class_acc) / class_count; % fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % fprintf('-------------------------\n'); % % Pixel IOU % accuracies = zeros(salopts.nclasses,1); % fprintf('Accuracy for each class (intersection/union measure)\n'); % % real_class_count = 0; % % for j=1:num % % gtj=sum(confcounts(j,:)); % resj=sum(confcounts(:,j)); % gtjresj=confcounts(j,j); % % The accuracy is: true positive / (true positive + false positive + false negative) % % which is equivalent to the following percentage: % denom = (gtj+resj-gtjresj); % % if denom == 0 % denom = 1; % end % % accuracies(j)=100*gtjresj/denom; % % clname = 'background'; % if (j>1), clname = salopts.classes{j-1};end; % % if ~strcmp(clname, 'void') % real_class_count = real_class_count + 1; % else % if denom ~= 1 % fprintf(1, 'WARNING: this void class has denom = %d\n', denom); % end % end % % if ~strcmp(clname, 'void') % fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); % end % end %accuracies = accuracies(1:end); %avacc = mean(accuracies); %avacc = sum(accuracies) / real_class_count; %fprintf('Average accuracy: %6.3f%%\n',avacc); %fprintf('-------------------------\n'); prec = mean(ALLPRECISION, 1); %function 'mean' will give NaN for columns in which NaN appears. rec = mean(ALLRECALL, 1); % Max F-meature beta_square = 0.3; Fmeasure = CalFmeasure(prec, rec, beta_square); maxF = max(Fmeasure); fprintf('MAX F-feature: %6.3f\n',maxF); % Precision % Recall fprintf('Mean Saliency Precision: %6.3f%%\n', 100*mean(prec)); fprintf('Mean Saliency Recall: %6.3f%%\n', 100*mean(rec)); % plot if nargin > 5 plot(rec, prec, 'color',color, 'linestyle',linestyle,'linewidth', 2); else plot(rec, prec, 'r', 'linewidth', 2); end
github
Xyuan13/MSRNet-master
MyVOCevalseg.m
.m
MSRNet-master/deeplab-caffe/matlab/my_script/MyVOCevalseg.m
4,627
utf_8
0e50d31b12d14678fbbb4e2e1d52f118
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
Xyuan13/MSRNet-master
MyMSRAevalseg.m
.m
MSRNet-master/deeplab-caffe/matlab/my_script/MyMSRAevalseg.m
5,692
utf_8
4ff8be0f4a6c9ea0aa622aac46821f37
%MSRAEVALSEG Evaluates a set of segmentation results. % MSRAEVALSEG(MSRAopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = MSRAEVALSEG(MSRAopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = MSRAEVALSEG(MSRAopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyMSRAevalseg(MSRAopts,id) % image test set [gtids,t]=textread(sprintf(MSRAopts.seg.imgsetpath,MSRAopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = MSRAopts.nclasses+1; confcounts = zeros(num); count=0; sum_mean=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(MSRAopts.seg.clsimgpath,imname); %disp(['gtfile ' gtfile]) [gtim,map] = imread(gtfile); gtim = double(gtim); if max(gtim(:) > 1) gtim = (gtim == 255); end % results file %resfile = sprintf(MSRAopts.seg.clsrespath,id,MSRAopts.testset,imname); resfile = fullfile(MSRAopts.seg.clsrespath, imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); if max(resim(:)) > 1 %resim = (resim >= 255/2); % Pat Attention to the threhold!! resim = (resim / 255); end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>MSRAopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,MSRAopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); %compute MAE diff=abs(gtim-resim); sum_mean = sum_mean + mean(mean(diff)); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; %MAE MAE = sum_mean / length(gtids); fprintf('-------------------------\n'); fprintf('Mean absolute error (MAE): %6.3f\n',MAE); %Max F-feature saliency_idx = 2; denom = sum(confcounts(saliency_idx, :)); if (denom == 0) denom = 1; end precision = 100 * confcounts(saliency_idx, saliency_idx) / denom; denom = sum(confcounts(:,saliency_idx)); if (denom == 0) denom = 1; end recall = 100 * confcounts(saliency_idx, saliency_idx) / denom; beta_square = 0.3; f_feature= (1+beta_square)*precision*recall/(beta_square*precision+recall); f_feature = f_feature / 100; fprintf('Saliency Precision: %6.3f%%\n',precision); fprintf('Saliency Recall: %6.3f%%\n',recall); fprintf('Max F-feature: %6.3f\n',f_feature); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('-------------------------\n'); fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = MSRAopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); fprintf('-------------------------\n'); % Pixel IOU accuracies = zeros(MSRAopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = MSRAopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('Average accuracy: %6.3f%%\n',avacc); fprintf('-------------------------\n');
github
Xyuan13/MSRNet-master
MyVOCevalsegBoundary.m
.m
MSRNet-master/deeplab-caffe/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
Xyuan13/MSRNet-master
My_GetDenseCRFResult.m
.m
MSRNet-master/deeplab-caffe/densecrf/my_script/My_GetDenseCRFResult.m
952
utf_8
5891b0bfcbaa14006fdd1d8aae9e451c
% compute the densecrf result (.bin) to png % function My_GetDenseCRFResult(stage) addpath('/home/phoenix/deeplab/code-v2/matlab/my_script'); %SetupEnv; load('./pascal_seg_colormap.mat'); map_folder=['/home/phoenix/Dataset/MSRA-B/SaliencyMap/' stage '_crf_bin']; map_dir = dir(fullfile(map_folder, '*bin')); save_result_folder=['/home/phoenix/Dataset/MSRA-B/SaliencyMap/' stage '_crf_png']; fprintf(1,' saving to %s\n', save_result_folder); if ~exist(save_result_folder, 'dir') mkdir(save_result_folder); end for i = 1 : numel(map_dir) fprintf(1, 'processing %d (%d)...\n', i, numel(map_dir)); map = LoadBinFile(fullfile(map_folder, map_dir(i).name), 'int16'); img_fn = map_dir(i).name(1:end-4); %imwrite(uint8(map), colormap, fullfile(save_result_folder, [img_fn, '.png'])); imwrite(double(map), fullfile(save_result_folder, [img_fn, '.png'])); end end
github
david-hofmann/EMGsim-master
active_force.m
.m
EMGsim-master/Codes/active_force.m
558
utf_8
8843bf1327aab6a84293d0f5204e418c
function [ twitch ] = active_force( P, T, MU_spike_train, discharge_cnt ) gain_at_intersection = (1 - exp(-2 * (0.4^3)))/0.4; if discharge_cnt == 1, nfr = 0; else current_ISI = MU_spike_train(discharge_cnt)-MU_spike_train(discharge_cnt-1); nfr = T / (current_ISI); %normalized firing rate end if nfr <= 0.4, gain_f = 1; else S = 1 - exp(-2 * (nfr^3)); %equation 16 gain_f = (S / nfr) / gain_at_intersection; %equation 17 end %twitch shape: twitch = gain_f * ((P .* [1:1000]) ./ T .* exp(1 - ([1:1000] ./ T))); %equation 18 end
github
david-hofmann/EMGsim-master
artificialEMG_onGPU.m
.m
EMGsim-master/Codes/artificialEMG_onGPU.m
4,097
utf_8
96d29b5c1677ede6ea491636457daf8a
%%% artificial EMG on GPU function artificialEMG_onGPU(MUAP,ISIstats) gpu = gpuDevice(1); %seed = 12345; %parallel.gpu.rng(seed); timer = tic(); T = 100; % in [s] [M, L] = size(MUAP); % number and length of MUAPs dt = 16/L * 10^-3; % temporal resolution in [s] defined by the length of MUAP, 256 data points in x ms (if x=8, sampling frequency = 32kHz) twitch = ones(M,L); twitch(:,[1 end]) = 0; % define GPU arrays MUs = gpuArray([1:M]'); time = gpuArray([1:fix(T/dt)]); % in [s] N = length(time); % define neural drive and firing parameters a = log(30)/M; recthresh = zeros(1,M); % recruit all %recthresh = exp(a * [1:M]); % recruit with exponential increase lambdamin = 0; % in [Hz] lambdamax = 100; % in [Hz] g = 1; % gain between neural drive and MUAP firing rate ndmax = recthresh(end)*g + lambdamax; % maximum neural drive % define neural drive function %f = 2*pi*0.05; %neuraldrive = abs(sin(f*[1:N]*dt)) * ndmax; % ramp function neuraldrive = linspace(0,1,N)*ndmax; % stepwise increase %steps = 10; %tmp = zeros(ceil(N/steps),steps); %tmp(1,:) = 1; %neuraldrive = cumsum(tmp(:))/steps * ndmax; % constant drive %neuraldrive = ones(1,N) * 10; function spike = makeSpikeTrain(MU, t) if recthresh(MU) < neuraldrive(t) lambda = g*(neuraldrive(t)-recthresh(MU)) + lambdamin; lambda = min(lambda, lambdamax); % ISI exponentially distributed exprn = -log(rand())/lambda; spike = exprn < dt; else spike = false; end end for x = 5:5:5 sEMG = zeros(1, N + L); force = zeros(1, N + L); spikes = zeros(1, N); reps = ceil(N*M/double(intmax('int32'))); N_p = floor(N/reps); fprintf('%d, %d\n', N_p, reps); % ISI distributed according to a Gaussian if strcmp(ISIstats, 'gauss') lambda = x; gauss_st = cumsum(lambda^-1 + lambda^-1*0.2*gpuArray.randn(T*lambda*2,M),1); end for r = 1:reps fprintf('working on %d of %d repetitions.\n',r, reps); gpuSimpleTime = toc(timer); fprintf('elapsed time [min]: %f\n', gpuSimpleTime/60); st = gpuArray(logical(zeros(M, N_p, 'uint8'))); switch ISIstats case 'gauss' if reps == 1 tmp = histc(gauss_st, time(N_p*(r-1)+1:N_p*r)*dt); tmp(end,:) = zeros(1,M); elseif r == 1 tmp = histc(gauss_st, time(N_p*(r-1)+1:N_p*r+1)*dt); tmp(end,:) = []; elseif r == reps && reps*N_p == N tmp = histc(gauss_st, time(N_p*(r-1):N_p*r)*dt); tmp(1,:) = []; tmp(end,:) = zeros(1,M); else tmp = histc(gauss_st, time(N_p*(r-1):N_p*r+1)*dt); tmp([1 end],:) = []; end st = tmp' > 0; case 'exponential' st = arrayfun(@makeSpikeTrain, MUs, time(N_p*(r-1)+1:N_p*r)); case 'weibull' end for t = N_p*(r-1)+1:N_p*r sEMG(1,t:t+L-1) = sEMG(1,t:t+L-1) + sum(MUAP(st(:,t-N_p*(r-1)),:), 1); force(1,t:t+L-1) = force(1,t:t+L-1) + sum(twitch(st(:,t-N_p*(r-1)),:), 1); spikes(t) = sum(gather(st(:,t-N_p*(r-1)))); end end rest = N - reps*N_p; fprintf('%d, %d, %d\n', rest, reps*N_p,N); if rest > 0 st = gpuArray(logical(zeros(M, rest, 'uint8'))); if strcmp(ISIstats, 'gauss') tmp = histc(gauss_st, time(N_p*(r-1):N_p*r)*dt); tmp(1,:) = []; tmp(end,:) = zeros(1,M); st = tmp' > 0; else st = arrayfun(@makeSpikeTrain, MUs, time(N_p*reps+1:end)); end for t = N_p*reps+1:N sEMG(1,t:t+L-1) = sEMG(1,t:t+L-1) + sum(MUAP(st(:,t-N_p*reps),:), 1); force(1,t:t+L-1) = force(1,t:t+L-1) + sum(twitch(st(:,t-N_p*reps),:), 1); spikes(t) = sum(st(:,t-N_p*(r-1))); end end %spiketimes = gather(gauss_st); time = gather(time); save(['../results/test_withforce_' ISIstats 'ISI_fr' num2str(neuraldrive(end)) '_' num2str(M) 'MUAP.mat'],'sEMG','recthresh','neuraldrive','dt','T','spikes','time','force') gpuSimpleTime = toc(timer); fprintf('%f\n', gpuSimpleTime); end end
github
wantingallin/transferlearning-master
MyTJM.m
.m
transferlearning-master/code/MyTJM.m
3,517
utf_8
ce3d34bcb6ed86fc570f1f4f818ff2aa
function [acc,acc_list,A] = MyTJM(X_src,Y_src,X_tar,Y_tar,options) % Inputs: %%% X_src :source feature matrix, ns * m %%% Y_src :source label vector, ns * 1 %%% X_tar :target feature matrix, nt * m %%% Y_tar :target label vector, nt * 1 %%% options:option struct % Outputs: %%% acc :final accuracy using knn, float %%% acc_list:list of all accuracies during iterations %%% A :final adaptation matrix, (ns + nt) * (ns + nt) %% Set options lambda = options.lambda; %% lambda for the regularization dim = options.dim; %% dim is the dimension after adaptation, dim <= m kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf gamma = options.gamma; %% gamma is the bandwidth of rbf kernel T = options.T; %% iteration number fprintf('TJM: dim=%d lambda=%f\n',dim,lambda); % Set predefined variables X = [X_src',X_tar']; X = X*diag(sparse(1./sqrt(sum(X.^2)))); ns = size(X_src,1); nt = size(X_tar,1); n = ns+nt; % Construct kernel matrix K = kernel_tjm(kernel_type,X,[],gamma); % Construct centering matrix H = eye(n)-1/(n)*ones(n,n); % Construct MMD matrix e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)]; C = length(unique(Y_src)); M = e*e' * C; Cls = []; % Transfer Joint Matching: JTM G = speye(n); acc_list = []; for t = 1:T %%% Mc [If want to add conditional distribution] N = 0; if ~isempty(Cls) && length(Cls)==nt for c = reshape(unique(Y_src),1,C) e = zeros(n,1); e(Y_src==c) = 1 / length(find(Y_src==c)); e(ns+find(Cls==c)) = -1 / length(find(Cls==c)); e(isinf(e)) = 0; N = N + e*e'; end end M = (1 - mu) * M + mu * N; M = M/norm(M,'fro'); [A,~] = eigs(K*M*K'+lambda*G,K*H*K',dim,'SM'); % [A,~] = eigs(X*M*X'+lambda*G,X*H*X',k,'SM'); G(1:ns,1:ns) = diag(sparse(1./(sqrt(sum(A(1:ns,:).^2,2)+eps)))); Z = A'*K; Z = Z*diag(sparse(1./sqrt(sum(Z.^2)))); Zs = Z(:,1:ns)'; Zt = Z(:,ns+1:n)'; knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1); Cls = knn_model.predict(Zt); acc = sum(Cls==Y_tar)/nt; acc_list = [acc_list;acc(1)]; fprintf('[%d] acc=%f\n',t,full(acc(1))); end fprintf('Algorithm JTM terminated!!!\n\n'); end % With Fast Computation of the RBF kernel matrix % To speed up the computation, we exploit a decomposition of the Euclidean distance (norm) % % Inputs: % ker: 'linear','rbf','sam' % X: data matrix (features * samples) % gamma: bandwidth of the RBF/SAM kernel % Output: % K: kernel matrix function K = kernel_tjm(ker,X,X2,gamma) switch ker case 'linear' if isempty(X2) K = X'*X; else K = X'*X2; end case 'rbf' n1sq = sum(X.^2,1); n1 = size(X,2); if isempty(X2) D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X; else n2sq = sum(X2.^2,1); n2 = size(X2,2); D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2; end K = exp(-gamma*D); case 'sam' if isempty(X2) D = X'*X; else D = X'*X2; end K = exp(-gamma*acos(D).^2); otherwise error(['Unsupported kernel ' ker]) end end
github
wantingallin/transferlearning-master
MyJGSA.m
.m
transferlearning-master/code/MyJGSA.m
6,642
utf_8
09a8f009556a3e0b09d10483558976ec
function [acc,acc_list,A,B] = MyJGSA(X_src,Y_src,X_tar,Y_tar,options) %% Joint Geometrical and Statistic Adaptation % Inputs: %%% X_src :source feature matrix, ns * m %%% Y_src :source label vector, ns * 1 %%% X_tar :target feature matrix, nt * m %%% Y_tar :target label vector, nt * 1 %%% options:option struct % Outputs: %%% acc :final accuracy using knn, float %%% acc_list:list of all accuracies during iterations %%% A :final adaptation matrix for source domain, m * dim %%% B :final adaptation matrix for target domain, m * dim alpha = options.alpha; mu = options.mu; beta = options.beta; gamma = options.gamma; kernel_type = options.kernel_type; dim = options.dim; T = options.T; X_src = X_src'; X_tar = X_tar'; m = size(X_src,1); ns = size(X_src,2); nt = size(X_tar,2); class_set = unique(Y_src); C = length(class_set); acc_list = []; Y_tar_pseudo = []; if strcmp(kernel_type,'primal') [Sw, Sb] = scatter_matrix(X_src',Y_src); P = zeros(2 * m,2 * m); P(1:m,1:m) = Sb; Q = Sw; for t = 1 : T [Ms,Mt,Mst,Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C); Ts = X_src * Ms * X_src'; Tt = X_tar * Mt * X_tar'; Tst = X_src * Mst * X_tar'; Tts = X_tar * Mts * X_src'; Ht = eye(nt) - 1 / nt * ones(nt,nt); X = [zeros(m,ns),zeros(m,nt);zeros(m,ns),X_tar]; H = [zeros(ns,ns),zeros(ns,nt);zeros(nt,ns),Ht]; Smax = mu * X * H * X' + beta * P; Smin = [Ts+alpha*eye(m)+beta*Q, Tst-alpha*eye(m) ; ... Tts-alpha*eye(m), Tt+(alpha+mu)*eye(m)]; mm = 1e-9*eye(2*m); [W,~] = eigs(Smax,Smin + mm,dim,'LM'); As = W(1:m,:); At = W(m+1:end,:); Zs = (As' * X_src)'; Zt = (At' * X_tar)'; if T > 1 knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1); Y_tar_pseudo = knn_model.predict(Zt); acc = length(find(Y_tar_pseudo == Y_tar)) / length(Y_tar); fprintf('acc of iter %d: %0.4f\n',t, acc); acc_list = [acc_list;acc]; end end else Xst = [X_src,X_tar]; nst = size(Xst,2); [Ks, Kt, Kst] = constructKernel(X_src,X_tar,kernel_type,gamma); [Sw, Sb] = scatter_matrix(Ks,Y_src); P = zeros(2 * nst,2 * nst); P(1:nst,1:nst) = Sb; Q = Sw; for t = 1:T % Construct MMD matrix [Ms, Mt, Mst, Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C); Ts = Ks'*Ms*Ks; Tt = Kt'*Mt*Kt; Tst = Ks'*Mst*Kt; Tts = Kt'*Mts*Ks; K = [zeros(ns,nst), zeros(ns,nst); zeros(nt,nst), Kt]; Smax = mu*K'*K+beta*P; Smin = [Ts+alpha*Kst+beta*Q, Tst-alpha*Kst;... Tts-alpha*Kst, Tt+mu*Kst+alpha*Kst]; [W,~] = eigs(Smax, Smin+1e-9*eye(2*nst), dim, 'LM'); W = real(W); As = W(1:nst, :); At = W(nst+1:end, :); Zs = (As'*Ks')'; Zt = (At'*Kt')'; if T > 1 knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1); Y_tar_pseudo = knn_model.predict(Zt); acc = length(find(Y_tar_pseudo == Y_tar)) / length(Y_tar); fprintf('acc of iter %d: %0.4f\n',t, full(acc)); acc_list = [acc_list;acc]; end end end A = As; B = At; end function [Sw,Sb] = scatter_matrix(X,Y) %% Within and between class Scatter matrix %% Inputs: %%% X: data matrix, length * dim %%% Y: label vector, length * 1 % Outputs: %%% Sw: With-in class matrix, dim * dim %%% Sb: Between class matrix, dim * dim X = X'; dim = size(X,1); class_set = unique(Y); C = length(class_set); mean_total = mean(X,2); Sw = zeros(dim,dim); Sb = zeros(dim,dim); for i = 1 : C Xi = X(:,Y == class_set(i)); mean_class_i = mean(Xi,2); Hi = eye(size(Xi,2)) - 1/(size(Xi,2)) * ones(size(Xi,2),size(Xi,2)); Sw = Sw + Xi * Hi * Xi'; Sb = Sb + size(Xi,2) * (mean_class_i - mean_total) * (mean_class_i - mean_total)'; end end function [Ms,Mt,Mst,Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C) es = 1 / ns * ones(ns,1); et = -1 / nt * ones(nt,1); e = [es;et]; M = e * e' * C; Ms = es * es' * C; Mt = et * et' * C; Mst = es * et' * C; Mts = et * es' * C; if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo) == nt for c = reshape(unique(Y_src),1,C) es = zeros(ns,1); et = zeros(nt,1); es(Y_src == c) = 1 / length(find(Y_src == c)); et(Y_tar_pseudo == c) = -1 / length(find(Y_tar_pseudo == c)); es(isinf(es)) = 0; et(isinf(et)) = 0; Ms = Ms + es * es'; Mt = Mt + et * et'; Mst = Mst + es * et'; Mts = Mts + et * es'; end end Ms = Ms / norm(M,'fro'); Mt = Mt / norm(M,'fro'); Mst = Mst / norm(M,'fro'); Mts = Mts / norm(M,'fro'); end function [Ks, Kt, Kst] = constructKernel(Xs,Xt,ker,gamma) Xst = [Xs, Xt]; ns = size(Xs,2); nt = size(Xt,2); nst = size(Xst,2); Kst0 = km_kernel(Xst',Xst',ker,gamma); Ks0 = km_kernel(Xs',Xst',ker,gamma); Kt0 = km_kernel(Xt',Xst',ker,gamma); oneNst = ones(nst,nst)/nst; oneN=ones(ns,nst)/nst; oneMtrN=ones(nt,nst)/nst; Ks=Ks0-oneN*Kst0-Ks0*oneNst+oneN*Kst0*oneNst; Kt=Kt0-oneMtrN*Kst0-Kt0*oneNst+oneMtrN*Kst0*oneNst; Kst=Kst0-oneNst*Kst0-Kst0*oneNst+oneNst*Kst0*oneNst; end function K = km_kernel(X1,X2,ktype,kpar) % KM_KERNEL calculates the kernel matrix between two data sets. % Input: - X1, X2: data matrices in row format (data as rows) % - ktype: string representing kernel type % - kpar: vector containing the kernel parameters % Output: - K: kernel matrix % USAGE: K = km_kernel(X1,X2,ktype,kpar) % % Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2012. % % This file is part of the Kernel Methods Toolbox for MATLAB. % https://github.com/steven2358/kmbox switch ktype case 'gauss' % Gaussian kernel sgm = kpar; % kernel width dim1 = size(X1,1); dim2 = size(X2,1); norms1 = sum(X1.^2,2); norms2 = sum(X2.^2,2); mat1 = repmat(norms1,1,dim2); mat2 = repmat(norms2',dim1,1); distmat = mat1 + mat2 - 2*X1*X2'; % full distance matrix sgm = sgm / mean(mean(distmat)); % added by jing 24/09/2016, median-distance K = exp(-distmat/(2*sgm^2)); case 'gauss-diag' % only diagonal of Gaussian kernel sgm = kpar; % kernel width K = exp(-sum((X1-X2).^2,2)/(2*sgm^2)); case 'poly' % polynomial kernel % p = kpar(1); % polynome order % c = kpar(2); % additive constant p = kpar; % jing c = 1; % jing K = (X1*X2' + c).^p; case 'linear' % linear kernel K = X1*X2'; otherwise % default case error ('unknown kernel type') end end
github
wantingallin/transferlearning-master
MyJDA.m
.m
transferlearning-master/code/MyJDA.m
4,118
utf_8
54f4173e19b0dbf7b2572a964a6a3277
function [acc,acc_ite,A] = MyJDA(X_src,Y_src,X_tar,Y_tar,options) % Inputs: %%% X_src :source feature matrix, ns * m %%% Y_src :source label vector, ns * 1 %%% X_tar :target feature matrix, nt * m %%% Y_tar :target label vector, nt * 1 %%% options:option struct % Outputs: %%% acc :final accuracy using knn, float %%% acc_ite:list of all accuracies during iterations %%% A :final adaptation matrix, (ns + nt) * (ns + nt) %% Set options lambda = options.lambda; %% lambda for the regularization dim = options.dim; %% dim is the dimension after adaptation, dim <= m kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf gamma = options.gamma; %% gamma is the bandwidth of rbf kernel T = options.T; %% iteration number acc_ite = []; Y_tar_pseudo = []; %% Iteration for i = 1 : T [Z,A] = JDA_core(X_src,Y_src,X_tar,Y_tar_pseudo,options); %normalization for better classification performance Z = Z*diag(sparse(1./sqrt(sum(Z.^2)))); Zs = Z(:,1:size(X_src,1)); Zt = Z(:,size(X_src,1)+1:end); knn_model = fitcknn(Zs',Y_src,'NumNeighbors',1); Y_tar_pseudo = knn_model.predict(Zt'); acc = length(find(Y_tar_pseudo==Y_tar))/length(Y_tar); fprintf('JDA+NN=%0.4f\n',acc); acc_ite = [acc_ite;acc]; end end function [Z,A] = JDA_core(X_src,Y_src,X_tar,Y_tar_pseudo,options) %% Set options lambda = options.lambda; %% lambda for the regularization dim = options.dim; %% dim is the dimension after adaptation, dim <= m kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf gamma = options.gamma; %% gamma is the bandwidth of rbf kernel %% Construct MMD matrix X = [X_src',X_tar']; X = X*diag(sparse(1./sqrt(sum(X.^2)))); [m,n] = size(X); ns = size(X_src,1); nt = size(X_tar,1); e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)]; C = length(unique(Y_src)); %%% M0 M = e * e' * C; %multiply C for better normalization %%% Mc N = 0; if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo)==nt for c = reshape(unique(Y_src),1,C) e = zeros(n,1); e(Y_src==c) = 1 / length(find(Y_src==c)); e(ns+find(Y_tar_pseudo==c)) = -1 / length(find(Y_tar_pseudo==c)); e(isinf(e)) = 0; N = N + e*e'; end end M = M + N; M = M / norm(M,'fro'); %% Centering matrix H H = eye(n) - 1/n * ones(n,n); %% Calculation if strcmp(kernel_type,'primal') [A,~] = eigs(X*M*X'+lambda*eye(m),X*H*X',dim,'SM'); Z = A'*X; else K = kernel_jda(kernel_type,X,[],gamma); [A,~] = eigs(K*M*K'+lambda*eye(n),K*H*K',dim,'SM'); Z = A'*K; end end % With Fast Computation of the RBF kernel matrix % To speed up the computation, we exploit a decomposition of the Euclidean distance (norm) % % Inputs: % ker: 'linear','rbf','sam' % X: data matrix (features * samples) % gamma: bandwidth of the RBF/SAM kernel % Output: % K: kernel matrix % % Gustavo Camps-Valls % 2006(c) % Jordi ([email protected]), 2007 % 2007-11: if/then -> switch, and fixed RBF kernel % Modified by Mingsheng Long % 2013(c) % Mingsheng Long ([email protected]), 2013 function K = kernel_jda(ker,X,X2,gamma) switch ker case 'linear' if isempty(X2) K = X'*X; else K = X'*X2; end case 'rbf' n1sq = sum(X.^2,1); n1 = size(X,2); if isempty(X2) D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X; else n2sq = sum(X2.^2,1); n2 = size(X2,2); D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2; end K = exp(-gamma*D); case 'sam' if isempty(X2) D = X'*X; else D = X'*X2; end K = exp(-gamma*acos(D).^2); otherwise error(['Unsupported kernel ' ker]) end end
github
wantingallin/transferlearning-master
MyGFK.m
.m
transferlearning-master/code/MyGFK.m
2,152
utf_8
a01af2b801cc7b96695684ce8e803547
function [acc,G] = MyGFK(X_src,Y_src,X_tar,Y_tar,dim) % Inputs: %%% X_src :source feature matrix, ns * m %%% Y_src :source label vector, ns * 1 %%% X_tar :target feature matrix, nt * m %%% Y_tar :target label vector, nt * 1 % Outputs: %%% acc :accuracy after GFK and 1NN %%% G :geodesic flow kernel matrix Ps = pca(X_src); Pt = pca(X_tar); G = GFK_core([Ps,null(Ps')], Pt(:,1:dim)); [~, acc] = my_kernel_knn(G, X_src, Y_src, X_tar, Y_tar); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [prediction,accuracy] = my_kernel_knn(M, Xr, Yr, Xt, Yt) dist = repmat(diag(Xr*M*Xr'),1,length(Yt)) ... + repmat(diag(Xt*M*Xt')',length(Yr),1)... - 2*Xr*M*Xt'; [~, minIDX] = min(dist); prediction = Yr(minIDX); accuracy = sum( prediction==Yt ) / length(Yt); end function G = GFK_core(Q,Pt) % Input: Q = [Ps, null(Ps')], where Ps is the source subspace, column-wise orthonormal % Pt: target subsapce, column-wise orthonormal, D-by-d, d < 0.5*D % Output: G = \int_{0}^1 \Phi(t)\Phi(t)' dt % ref: Geodesic Flow Kernel for Unsupervised Domain Adaptation. % B. Gong, Y. Shi, F. Sha, and K. Grauman. % Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), Providence, RI, June 2012. % Contact: Boqing Gong ([email protected]) N = size(Q,2); % dim = size(Pt,2); % compute the principal angles QPt = Q' * Pt; [V1,V2,V,Gam,Sig] = gsvd(QPt(1:dim,:), QPt(dim+1:end,:)); V2 = -V2; theta = real(acos(diag(Gam))); % theta is real in theory. Imaginary part is due to the computation issue. % compute the geodesic flow kernel eps = 1e-20; B1 = 0.5.*diag(1+sin(2*theta)./2./max(theta,eps)); B2 = 0.5.*diag((-1+cos(2*theta))./2./max(theta,eps)); B3 = B2; B4 = 0.5.*diag(1-sin(2*theta)./2./max(theta,eps)); G = Q * [V1, zeros(dim,N-dim); zeros(N-dim,dim), V2] ... * [B1,B2,zeros(dim,N-2*dim);B3,B4,zeros(dim,N-2*dim);zeros(N-2*dim,N)]... * [V1, zeros(dim,N-dim); zeros(N-dim,dim), V2]' * Q'; end
github
wantingallin/transferlearning-master
MyTCA.m
.m
transferlearning-master/code/MyTCA.m
2,818
utf_8
7aee1d32ebfb97f5974be024ce450ce1
function [X_src_new,X_tar_new,A] = MyTCA(X_src,X_tar,options) % Inputs: [dim is the dimension of features] %%% X_src:source feature matrix, ns * dim %%% X_tar:target feature matrix, nt * dim %%% options:option struct % Outputs: %%% X_src_new:transformed source feature matrix, ns * dim_new %%% X_tar_new:transformed target feature matrix, nt * dim_new %%% A: adaptation matrix, (ns + nt) * (ns + nt) %% Set options lambda = options.lambda; %% lambda for the regularization dim = options.dim; %% dim is the dimension after adaptation kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf gamma = options.gamma; %% gamma is the bandwidth of rbf kernel %% Calculate X = [X_src',X_tar']; X = X*diag(sparse(1./sqrt(sum(X.^2)))); [m,n] = size(X); ns = size(X_src,1); nt = size(X_tar,1); e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)]; M = e * e'; M = M / norm(M,'fro'); H = eye(n)-1/(n)*ones(n,n); if strcmp(kernel_type,'primal') [A,~] = eigs(X*M*X'+lambda*eye(m),X*H*X',dim,'SM'); Z = A' * X; Z = Z * diag(sparse(1./sqrt(sum(Z.^2)))); X_src_new = Z(:,1:ns)'; X_tar_new = Z(:,ns+1:end)'; else K = TCA_kernel(kernel_type,X,[],gamma); [A,~] = eigs(K*M*K'+lambda*eye(n),K*H*K',dim,'SM'); Z = A' * K; Z = Z*diag(sparse(1./sqrt(sum(Z.^2)))); X_src_new = Z(:,1:ns)'; X_tar_new = Z(:,ns+1:end)'; end end % With Fast Computation of the RBF kernel matrix % To speed up the computation, we exploit a decomposition of the Euclidean distance (norm) % % Inputs: % ker: 'linear','rbf','sam' % X: data matrix (features * samples) % gamma: bandwidth of the RBF/SAM kernel % Output: % K: kernel matrix % % Gustavo Camps-Valls % 2006(c) % Jordi ([email protected]), 2007 % 2007-11: if/then -> switch, and fixed RBF kernel % Modified by Mingsheng Long % 2013(c) % Mingsheng Long ([email protected]), 2013 function K = TCA_kernel(ker,X,X2,gamma) switch ker case 'linear' if isempty(X2) K = X'*X; else K = X'*X2; end case 'rbf' n1sq = sum(X.^2,1); n1 = size(X,2); if isempty(X2) D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X; else n2sq = sum(X2.^2,1); n2 = size(X2,2); D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2; end K = exp(-gamma*D); case 'sam' if isempty(X2) D = X'*X; else D = X'*X2; end K = exp(-gamma*acos(D).^2); otherwise error(['Unsupported kernel ' ker]) end end
github
wantingallin/transferlearning-master
lapgraph.m
.m
transferlearning-master/code/MyARTL/lapgraph.m
20,244
utf_8
cfed436191fe6a863089f6da80644260
function [W, elapse] = lapgraph(fea,options) % Usage: % W = graph(fea,options) % % fea: Rows of vectors of data points. Each row is x_i % options: Struct value in Matlab. The fields in options that can be set: % Metric - Choices are: % 'Euclidean' - Will use the Euclidean distance of two data % points to evaluate the "closeness" between % them. [Default One] % 'Cosine' - Will use the cosine value of two vectors % to evaluate the "closeness" between them. % A popular similarity measure used in % Information Retrieval. % % NeighborMode - Indicates how to construct the graph. Choices % are: [Default 'KNN'] % 'KNN' - k = 0 % Complete graph % k > 0 % Put an edge between two nodes if and % only if they are among the k nearst % neighbors of each other. You are % required to provide the parameter k in % the options. Default k=5. % 'Supervised' - k = 0 % Put an edge between two nodes if and % only if they belong to same class. % k > 0 % Put an edge between two nodes if % they belong to same class and they % are among the k nearst neighbors of % each other. % Default: k=0 % You are required to provide the label % information gnd in the options. % % WeightMode - Indicates how to assign weights for each edge % in the graph. Choices are: % 'Binary' - 0-1 weighting. Every edge receiveds weight % of 1. [Default One] % 'HeatKernel' - If nodes i and j are connected, put weight % W_ij = exp(-norm(x_i - x_j)/2t^2). This % weight mode can only be used under % 'Euclidean' metric and you are required to % provide the parameter t. % 'Cosine' - If nodes i and j are connected, put weight % cosine(x_i,x_j). Can only be used under % 'Cosine' metric. % % k - The parameter needed under 'KNN' NeighborMode. % Default will be 5. % gnd - The parameter needed under 'Supervised' % NeighborMode. Colunm vector of the label % information for each data point. % bLDA - 0 or 1. Only effective under 'Supervised' % NeighborMode. If 1, the graph will be constructed % to make LPP exactly same as LDA. Default will be % 0. % t - The parameter needed under 'HeatKernel' % WeightMode. Default will be 1 % bNormalized - 0 or 1. Only effective under 'Cosine' metric. % Indicates whether the fea are already be % normalized to 1. Default will be 0 % bSelfConnected - 0 or 1. Indicates whether W(i,i) == 1. Default 1 % if 'Supervised' NeighborMode & bLDA == 1, % bSelfConnected will always be 1. Default 1. % % % Examples: % % fea = rand(50,15); % options = []; % options.Metric = 'Euclidean'; % options.NeighborMode = 'KNN'; % options.k = 5; % options.WeightMode = 'HeatKernel'; % options.t = 1; % W = constructW(fea,options); % % % fea = rand(50,15); % gnd = [ones(10,1);ones(15,1)*2;ones(10,1)*3;ones(15,1)*4]; % options = []; % options.Metric = 'Euclidean'; % options.NeighborMode = 'Supervised'; % options.gnd = gnd; % options.WeightMode = 'HeatKernel'; % options.t = 1; % W = constructW(fea,options); % % % fea = rand(50,15); % gnd = [ones(10,1);ones(15,1)*2;ones(10,1)*3;ones(15,1)*4]; % options = []; % options.Metric = 'Euclidean'; % options.NeighborMode = 'Supervised'; % options.gnd = gnd; % options.bLDA = 1; % W = constructW(fea,options); % % % For more details about the different ways to construct the W, please % refer: % Deng Cai, Xiaofei He and Jiawei Han, "Document Clustering Using % Locality Preserving Indexing" IEEE TKDE, Dec. 2005. % % % Written by Deng Cai (dengcai2 AT cs.uiuc.edu), April/2004, Feb/2006, % May/2007 % if (~exist('options','var')) options = []; else if ~isstruct(options) error('parameter error!'); end end %================================================= if ~isfield(options,'Metric') options.Metric = 'Cosine'; end switch lower(options.Metric) case {lower('Euclidean')} case {lower('Cosine')} if ~isfield(options,'bNormalized') options.bNormalized = 0; end otherwise error('Metric does not exist!'); end %================================================= if ~isfield(options,'NeighborMode') options.NeighborMode = 'KNN'; end switch lower(options.NeighborMode) case {lower('KNN')} %For simplicity, we include the data point itself in the kNN if ~isfield(options,'k') options.k = 5; end case {lower('Supervised')} if ~isfield(options,'bLDA') options.bLDA = 0; end if options.bLDA options.bSelfConnected = 1; end if ~isfield(options,'k') options.k = 0; end if ~isfield(options,'gnd') error('Label(gnd) should be provided under ''Supervised'' NeighborMode!'); end if ~isempty(fea) && length(options.gnd) ~= size(fea,1) error('gnd doesn''t match with fea!'); end otherwise error('NeighborMode does not exist!'); end %================================================= if ~isfield(options,'WeightMode') options.WeightMode = 'Binary'; end bBinary = 0; switch lower(options.WeightMode) case {lower('Binary')} bBinary = 1; case {lower('HeatKernel')} if ~strcmpi(options.Metric,'Euclidean') warning('''HeatKernel'' WeightMode should be used under ''Euclidean'' Metric!'); options.Metric = 'Euclidean'; end if ~isfield(options,'t') options.t = 1; end case {lower('Cosine')} if ~strcmpi(options.Metric,'Cosine') warning('''Cosine'' WeightMode should be used under ''Cosine'' Metric!'); options.Metric = 'Cosine'; end if ~isfield(options,'bNormalized') options.bNormalized = 0; end otherwise error('WeightMode does not exist!'); end %================================================= if ~isfield(options,'bSelfConnected') options.bSelfConnected = 1; end %================================================= tmp_T = cputime; if isfield(options,'gnd') nSmp = length(options.gnd); else nSmp = size(fea,1); end maxM = 62500000; %500M BlockSize = floor(maxM/(nSmp*3)); if strcmpi(options.NeighborMode,'Supervised') Label = unique(options.gnd); nLabel = length(Label); if options.bLDA G = zeros(nSmp,nSmp); for idx=1:nLabel classIdx = options.gnd==Label(idx); G(classIdx,classIdx) = 1/sum(classIdx); end W = sparse(G); elapse = cputime - tmp_T; return; end switch lower(options.WeightMode) case {lower('Binary')} if options.k > 0 G = zeros(nSmp*(options.k+1),3); idNow = 0; for i=1:nLabel classIdx = find(options.gnd==Label(i)); D = EuDist2(fea(classIdx,:),[],0); [dump idx] = sort(D,2); % sort each row clear D dump; idx = idx(:,1:options.k+1); nSmpClass = length(classIdx)*(options.k+1); G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]); G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:)); G(idNow+1:nSmpClass+idNow,3) = 1; idNow = idNow+nSmpClass; clear idx end G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp); G = max(G,G'); else G = zeros(nSmp,nSmp); for i=1:nLabel classIdx = find(options.gnd==Label(i)); G(classIdx,classIdx) = 1; end end if ~options.bSelfConnected for i=1:size(G,1) G(i,i) = 0; end end W = sparse(G); case {lower('HeatKernel')} if options.k > 0 G = zeros(nSmp*(options.k+1),3); idNow = 0; for i=1:nLabel classIdx = find(options.gnd==Label(i)); D = EuDist2(fea(classIdx,:),[],0); [dump idx] = sort(D,2); % sort each row clear D; idx = idx(:,1:options.k+1); dump = dump(:,1:options.k+1); dump = exp(-dump/(2*options.t^2)); nSmpClass = length(classIdx)*(options.k+1); G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]); G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:)); G(idNow+1:nSmpClass+idNow,3) = dump(:); idNow = idNow+nSmpClass; clear dump idx end G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp); else G = zeros(nSmp,nSmp); for i=1:nLabel classIdx = find(options.gnd==Label(i)); D = EuDist2(fea(classIdx,:),[],0); D = exp(-D/(2*options.t^2)); G(classIdx,classIdx) = D; end end if ~options.bSelfConnected for i=1:size(G,1) G(i,i) = 0; end end W = sparse(max(G,G')); case {lower('Cosine')} if ~options.bNormalized [nSmp, nFea] = size(fea); if issparse(fea) fea2 = fea'; feaNorm = sum(fea2.^2,1).^.5; for i = 1:nSmp fea2(:,i) = fea2(:,i) ./ max(1e-10,feaNorm(i)); end fea = fea2'; clear fea2; else feaNorm = sum(fea.^2,2).^.5; for i = 1:nSmp fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i)); end end end if options.k > 0 G = zeros(nSmp*(options.k+1),3); idNow = 0; for i=1:nLabel classIdx = find(options.gnd==Label(i)); D = fea(classIdx,:)*fea(classIdx,:)'; [dump idx] = sort(-D,2); % sort each row clear D; idx = idx(:,1:options.k+1); dump = -dump(:,1:options.k+1); nSmpClass = length(classIdx)*(options.k+1); G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]); G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:)); G(idNow+1:nSmpClass+idNow,3) = dump(:); idNow = idNow+nSmpClass; clear dump idx end G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp); else G = zeros(nSmp,nSmp); for i=1:nLabel classIdx = find(options.gnd==Label(i)); G(classIdx,classIdx) = fea(classIdx,:)*fea(classIdx,:)'; end end if ~options.bSelfConnected for i=1:size(G,1) G(i,i) = 0; end end W = sparse(max(G,G')); otherwise error('WeightMode does not exist!'); end elapse = cputime - tmp_T; return; end if strcmpi(options.NeighborMode,'KNN') && (options.k > 0) if strcmpi(options.Metric,'Euclidean') G = zeros(nSmp*(options.k+1),3); for i = 1:ceil(nSmp/BlockSize) if i == ceil(nSmp/BlockSize) smpIdx = (i-1)*BlockSize+1:nSmp; dist = EuDist2(fea(smpIdx,:),fea,0); dist = full(dist); [dump idx] = sort(dist,2); % sort each row idx = idx(:,1:options.k+1); dump = dump(:,1:options.k+1); if ~bBinary dump = exp(-dump/(2*options.t^2)); end G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]); G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),2) = idx(:); if ~bBinary G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = dump(:); else G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = 1; end else smpIdx = (i-1)*BlockSize+1:i*BlockSize; dist = EuDist2(fea(smpIdx,:),fea,0); dist = full(dist); [dump idx] = sort(dist,2); % sort each row idx = idx(:,1:options.k+1); dump = dump(:,1:options.k+1); if ~bBinary dump = exp(-dump/(2*options.t^2)); end G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]); G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),2) = idx(:); if ~bBinary G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = dump(:); else G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = 1; end end end W = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp); else if ~options.bNormalized [nSmp, nFea] = size(fea); if issparse(fea) fea2 = fea'; clear fea; for i = 1:nSmp fea2(:,i) = fea2(:,i) ./ max(1e-10,sum(fea2(:,i).^2,1).^.5); end fea = fea2'; clear fea2; else feaNorm = sum(fea.^2,2).^.5; for i = 1:nSmp fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i)); end end end G = zeros(nSmp*(options.k+1),3); for i = 1:ceil(nSmp/BlockSize) if i == ceil(nSmp/BlockSize) smpIdx = (i-1)*BlockSize+1:nSmp; dist = fea(smpIdx,:)*fea'; dist = full(dist); [dump idx] = sort(-dist,2); % sort each row idx = idx(:,1:options.k+1); dump = -dump(:,1:options.k+1); G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]); G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),2) = idx(:); G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = dump(:); else smpIdx = (i-1)*BlockSize+1:i*BlockSize; dist = fea(smpIdx,:)*fea'; dist = full(dist); [dump idx] = sort(-dist,2); % sort each row idx = idx(:,1:options.k+1); dump = -dump(:,1:options.k+1); G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]); G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),2) = idx(:); G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = dump(:); end end W = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp); end if strcmpi(options.WeightMode,'Binary') W(find(W)) = 1; end if isfield(options,'bSemiSupervised') && options.bSemiSupervised tmpgnd = options.gnd(options.semiSplit); Label = unique(tmpgnd); nLabel = length(Label); G = zeros(sum(options.semiSplit),sum(options.semiSplit)); for idx=1:nLabel classIdx = tmpgnd==Label(idx); G(classIdx,classIdx) = 1; end Wsup = sparse(G); if ~isfield(options,'SameCategoryWeight') options.SameCategoryWeight = 1; end W(options.semiSplit,options.semiSplit) = (Wsup>0)*options.SameCategoryWeight; end if ~options.bSelfConnected for i=1:size(W,1) W(i,i) = 0; end end W = max(W,W'); elapse = cputime - tmp_T; return; end % strcmpi(options.NeighborMode,'KNN') & (options.k == 0) % Complete Graph if strcmpi(options.Metric,'Euclidean') W = EuDist2(fea,[],0); W = exp(-W/(2*options.t^2)); else if ~options.bNormalized % feaNorm = sum(fea.^2,2).^.5; % fea = fea ./ repmat(max(1e-10,feaNorm),1,size(fea,2)); [nSmp, nFea] = size(fea); if issparse(fea) fea2 = fea'; feaNorm = sum(fea2.^2,1).^.5; for i = 1:nSmp fea2(:,i) = fea2(:,i) ./ max(1e-10,feaNorm(i)); end fea = fea2'; clear fea2; else feaNorm = sum(fea.^2,2).^.5; for i = 1:nSmp fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i)); end end end % W = full(fea*fea'); W = fea*fea'; end if ~options.bSelfConnected for i=1:size(W,1) W(i,i) = 0; end end W = max(W,W'); elapse = cputime - tmp_T; function D = EuDist2(fea_a,fea_b,bSqrt) % Euclidean Distance matrix % D = EuDist(fea_a,fea_b) % fea_a: nSample_a * nFeature % fea_b: nSample_b * nFeature % D: nSample_a * nSample_a % or nSample_a * nSample_b if ~exist('bSqrt','var') bSqrt = 1; end if (~exist('fea_b','var')) | isempty(fea_b) [nSmp, nFea] = size(fea_a); aa = sum(fea_a.*fea_a,2); ab = fea_a*fea_a'; aa = full(aa); ab = full(ab); if bSqrt D = sqrt(repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab); D = real(D); else D = repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab; end D = max(D,D'); D = D - diag(diag(D)); D = abs(D); else [nSmp_a, nFea] = size(fea_a); [nSmp_b, nFea] = size(fea_b); aa = sum(fea_a.*fea_a,2); bb = sum(fea_b.*fea_b,2); ab = fea_a*fea_b'; aa = full(aa); bb = full(bb); ab = full(ab); if bSqrt D = sqrt(repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab); D = real(D); else D = repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab; end D = abs(D); end
github
wantingallin/transferlearning-master
MyARTL.m
.m
transferlearning-master/code/MyARTL/MyARTL.m
3,503
utf_8
91802921f23d322f2ffca0e311f9372a
function [acc,acc_ite,Alpha] = MyARTL(X_src,Y_src,X_tar,Y_tar,options) % Inputs: %%% X_src :source feature matrix, ns * m %%% Y_src :source label vector, ns * 1 %%% X_tar :target feature matrix, nt * m %%% Y_tar :target label vector, nt * 1 %%% options:option struct % Outputs: %%% acc :final accuracy using knn, float %%% acc_ite:list of all accuracies during iterations %%% A :final adaptation matrix, (ns + nt) * (ns + nt) %% Set options lambda = options.lambda; %% lambda for the regularization kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf T = options.T; %% iteration number n_neighbor = options.n_neighbor; sigma = options.sigma; gamma = options.gamma; X = [X_src',X_tar']; Y = [Y_src;Y_tar]; X = X*diag(sparse(1./sqrt(sum(X.^2)))); ns = size(X_src,1); nt = size(X_tar,1); nm = ns + nt; e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)]; C = length(unique(Y_src)); E = diag(sparse([ones(ns,1);zeros(nt,1)])); YY = []; for c = reshape(unique(Y),1,length(unique(Y))) YY = [YY,Y==c]; end %% Construct graph laplacian manifold.k = options.n_neighbor; manifold.Metric = 'Cosine'; manifold.NeighborMode = 'KNN'; manifold.WeightMode = 'Cosine'; [W,Dw,L] = construct_lapgraph(X',manifold); %%% M0 M = e * e' * C; %multiply C for better normalization acc_ite = []; Y_tar_pseudo = []; % If want to include conditional distribution in iteration 1, then open % this % if ~isfield(options,'Yt0') % % model = train(Y(1:ns),sparse(X(:,1:ns)'),'-s 0 -c 1 -q 1'); % % [Y_tar_pseudo,~] = predict(Y(ns+1:end),sparse(X(:,ns+1:end)'),model); % knn_model = fitcknn(X_src,Y_src,'NumNeighbors',1); % Y_tar_pseudo = knn_model.predict(X_tar); % else % Y_tar_pseudo = options.Yt0; % end %% Iteration for i = 1 : T %%% Mc N = 0; if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo)==nt for c = reshape(unique(Y_src),1,C) e = zeros(nm,1); e(Y_src==c) = 1 / length(find(Y_src==c)); e(ns+find(Y_tar_pseudo==c)) = -1 / length(find(Y_tar_pseudo==c)); e(isinf(e)) = 0; N = N + e*e'; end end M = M + N; M = M / norm(M,'fro'); %% Calculation K = kernel_artl(kernel_type,X,sqrt(sum(sum(X.^2).^0.5)/nm)); Alpha = ((E + lambda * M + gamma * L) * K + sigma * speye(nm,nm)) \ (E * YY); F = K * Alpha; [~,Cls] = max(F,[],2); Acc = numel(find(Cls(ns+1:end)==Y(ns+1:end)))/nt; Y_tar_pseudo = Cls(ns+1:end); fprintf('Iteration [%2d]:ARTL=%0.4f\n',i,Acc); acc_ite = [acc_ite;Acc]; end end function [W,Dw,L] = construct_lapgraph(X,options) W = lapgraph(X,options); Dw = diag(sparse(sqrt(1./sum(W)))); L = speye(size(X,1)) - Dw * W * Dw; end function K = kernel_artl(ker,X,sigma) switch ker case 'linear' K = X' * X; case 'rbf' n1sq = sum(X.^2,1); n1 = size(X,2); D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X; K = exp(-D/(2*sigma^2)); case 'sam' D = X'*X; K = exp(-acos(D).^2/(2*sigma^2)); otherwise error(['Unsupported kernel ' ker]) end end
github
AndrewSpittlemeister/Multi-contrast-MRI-Image-Registration-master
adjustgray.m
.m
Multi-contrast-MRI-Image-Registration-master/adjustgray.m
300
utf_8
8081142a8a91998df6464bc6885264cc
function p=adjustgray(imgin) %Pass an input image %and output array of same size %Output is normalized to 0-255 temp=255/double(max(max(imgin))); aa=size(imgin); a=zeros(aa(1),aa(2),'uint8'); for y=1:aa(1) for z=1:aa(2) a(y,z)=round(imgin(y,z)*temp); end end p=a; end