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 | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_pr.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_pr.m | 3,763 | utf_8 | 4d1da5ccda1a7df2bec35b8f12fdd620 | function results = vl_test_pr(varargin)
% VL_TEST_PR
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ;
function test_perfect_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(info.auc, 1) ;
vl_assert_almost_equal(info.ap, 1) ;
vl_assert_almost_equal(info.ap_interp_11, 1) ;
function test_swap1_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ;
function test_swap1_tptn_stable(s)
[rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ;
vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ;
function test_swap1_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores1) ;
clf; vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ;
vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ;
vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ;
function test_inf(s)
scores = [1 -inf -1 -1 -1 -1] ;
labels = [1 1 -1 -1 -1 -1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ;
vl_assert_equal(numel(rc1), numel(rc2) + 1) ;
vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ;
vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ;
vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ;
vl_assert_almost_equal(info2.auc, 0.5) ;
vl_assert_almost_equal(info2.ap, 0.5) ;
vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ;
function test_inf_stable(s)
scores = [-1 -1 -1 -1 -inf +1] ;
labels = [-1 -1 -1 -1 +1 +1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ;
[rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ;
[rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ;
% stability does not change scores
vl_assert_almost_equal(info1,info1_) ;
vl_assert_almost_equal(info2,info2_) ;
% unstable with inf (first point (0,1) is conventional)
vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1])
vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6])
% unstable without inf
vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5])
vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5])
% stable with inf (no conventional point here)
vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ;
vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ;
% stable without inf (no conventional point and -inf are NaN)
vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ;
vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ;
function test_normalised_pr(s)
scores = [+1 +2] ;
labels = [+1 -1] ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
[rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ;
vl_assert_almost_equal(pr1, pr2) ;
vl_assert_almost_equal(rc1, rc2) ;
scores_ = [+1 +2 +2 +2] ;
labels_ = [+1 -1 -1 -1] ;
[rc3,pr3,info3] = vl_pr(labels_,scores_) ;
[rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ;
vl_assert_almost_equal(info3, info4) ;
function test_normalised_pr_corner_cases(s)
scores = 1:10 ;
labels = ones(1,10) ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc1, (0:10)/10) ;
vl_assert_almost_equal(pr1, ones(1,11)) ;
scores = 1:10 ;
labels = zeros(1,10) ;
[rc2,pr2,info2] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc2, zeros(1,11)) ;
vl_assert_almost_equal(pr2, ones(1,11)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_hog.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_hog.m | 1,555 | utf_8 | eed7b2a116d142040587dc9c4eb7cd2e | function results = vl_test_hog(varargin)
% VL_TEST_HOG
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
[x,y]= meshgrid(linspace(-1,1,128)) ;
s.round = single(x.^2+y.^2);
s.imSmall = s.im(1:128,1:128,:) ;
s.imSmall = s.im ;
s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ;
function test_basic_call(s)
cellSize = 8 ;
hog = vl_hog(s.im, cellSize) ;
function test_bilinear_orientations(s)
cellSize = 8 ;
vl_hog(s.im, cellSize, 'bilinearOrientations') ;
function test_variants_and_flipping(s)
variants = {'uoctti', 'dalaltriggs'} ;
numOrientationsRange = 3:9 ;
cellSize = 8 ;
for cellSize = [4 8 16]
for i=1:numel(variants)
for j=1:numel(numOrientationsRange)
args = {'bilinearOrientations', ...
'variant', variants{i}, ...
'numOrientations', numOrientationsRange(j)} ;
hog = vl_hog(s.imSmall, cellSize, args{:}) ;
perm = vl_hog('permutation', args{:}) ;
hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ;
hog2 = hog(:,end:-1:1,perm) ;
%norm(hog1(:)-hog2(:))
vl_assert_almost_equal(hog1,hog2,1e-3) ;
end
end
end
function test_polar(s)
cellSize = 8 ;
im = s.round ;
for b = [0 1]
if b
args = {'bilinearOrientations'} ;
else
args = {} ;
end
hog1 = vl_hog(im, cellSize, args{:}) ;
[ix,iy] = vl_grad(im) ;
m = sqrt(ix.^2 + iy.^2) ;
a = atan2(iy,ix) ;
m(:,[1 end]) = 0 ;
m([1 end],:) = 0 ;
hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ;
vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_argparse.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_argparse.m | 795 | utf_8 | e72185b27206d0ee1dfdc19fe77a5be6 | function results = vl_test_argparse(varargin)
% VL_TEST_ARGPARSE
vl_test_init ;
function test_basic()
opts.field1 = 1 ;
opts.field2 = 2 ;
opts.field3 = 3 ;
opts_ = opts ;
opts_.field1 = 3 ;
opts_.field2 = 10 ;
opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ;
assert(isequal(opts, opts_)) ;
opts_.field1 = 9 ;
opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ;
assert(isequal(opts, opts_)) ;
function test_error()
opts.field1 = 1 ;
try
opts = vl_argparse(opts, {'field2', 5}) ;
catch e
return ;
end
assert(false) ;
function test_leftovers()
opts1.field1 = 1 ;
opts2.field2 = 1 ;
opts1_.field1 = 2 ;
opts2_.field2 = 2 ;
[opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ;
opts2 = vl_argparse(opts2, args) ;
assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_liop.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_liop.m | 1,023 | utf_8 | a162be369073bed18e61210f44088cf3 | function results = vl_test_liop(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
randn('state',0) ;
s.patch = randn(65,'single') ;
xr = -32:32 ;
[x,y] = meshgrid(xr) ;
s.blob = - single(x.^2+y.^2) ;
function test_basic(s)
d = vl_liop(s.patch) ;
function test_blob(s)
% with a blob, all local intensity order pattern are equal. In
% particular, if the blob intensity decreases away from the center,
% then all local intensities sampled in a neighbourhood of 2 elements
% are already sorted (see LIOP details).
d = vl_liop(s.blob, ...
'IntensityThreshold', 0, ...
'NumNeighbours', 2, ...
'NumSpatialBins', 1) ;
assert(isequal(d, single([1;0]))) ;
function test_neighbours(s)
for n=2:5
for p=1:3
d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ;
assert(numel(d) == p * factorial(n)) ;
end
end
function test_multiple(s)
x = randn(31,31,3, 'single') ;
d = vl_liop(x) ;
for i=1:3
d_(:,i) = vl_liop(squeeze(x(:,:,i))) ;
end
assert(isequal(d,d_)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_binsearch.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_binsearch.m | 1,339 | utf_8 | 85dc020adce3f228fe7dfb24cf3acc63 | function results = vl_test_binsearch(varargin)
% VL_TEST_BINSEARCH
vl_test_init ;
function test_inf_bins()
x = [-inf -1 0 1 +inf] ;
vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ;
vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ;
vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ;
vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ;
function test_empty()
vl_assert_equal(vl_binsearch([], []), []) ;
function test_bnd()
vl_assert_equal(vl_binsearch([], [1]), [0]) ;
vl_assert_equal(vl_binsearch([], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([], [+inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [.9]), [0]) ;
vl_assert_equal(vl_binsearch([1], [1]), [1]) ;
vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ;
function test_basic()
vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ;
vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ;
vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ;
function test_frac()
vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10))
vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ...
fliplr(floor(1:.5:10))) ;
function test_array()
a = reshape(1:100,10,10) ;
b = reshape(1:.5:100.5, 2, []) ;
c = floor(b) ;
vl_assert_equal(vl_binsearch(a,b), c) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_roc.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/plotop/vl_roc.m | 8,747 | utf_8 | 6b8b4786c9242d5112ca90a616db507a | function [tpr,tnr,info] = vl_roc(labels, scores, varargin)
%VL_ROC ROC curve.
% [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating
% Characteristic (ROC) curve. LABELS are the ground truth labels,
% greather than zero for a positive sample and smaller than zero for
% a negative one. SCORES are the scores of the samples obtained from
% a classifier, where lager scores should correspond to positive
% labels.
%
% Samples are ranked by decreasing scores, starting from rank 1.
% TPR(K) and TNR(K) are the true positive and true negative rates
% when samples of rank smaller or equal to K-1 are predicted to be
% positive. So for example TPR(3) is the true positive rate when the
% two samples with largest score are predicted to be
% positive. Similarly, TPR(1) is the true positive rate when no
% samples are predicted to be positive, i.e. the constant 0.
%
% Set the zero the lables of samples that should be ignored in the
% evaluation. Set to -INF the scores of samples which are not
% retrieved. If there are samples with -INF score, then the ROC curve
% may have maximum TPR and TNR smaller than 1.
%
% [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO
% with the following fields:
%
% info.auc:: Area under the ROC curve (AUC).
% The ROC curve has a `staircase shape' because for each sample
% only TP or TN changes, but not both at the same time. Therefore
% there is no approximation involved in the computation of the
% area.
%
% info.eer:: Equal error rate (EER).
% The equal error rate is the value of FPR (or FNR) when the ROC
% curves intersects the line connecting (0,0) to (1,1).
%
% VL_ROC(...) with no output arguments plots the ROC curve in the
% current axis.
%
% VL_ROC() acccepts the following options:
%
% Plot:: []
% Setting this option turns on plotting unconditionally. The
% following plot variants are supported:
%
% tntp:: Plot TPR against TNR (standard ROC plot).
% tptn:: Plot TNR against TPR (recall on the horizontal axis).
% fptp:: Plot TPR against FPR.
% fpfn:: Plot FNR against FPR (similar to DET curve).
%
% NumPositives:: []
% NumNegatives:: []
% If set to a number, pretend that LABELS contains this may
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entrires in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence, as if they had -INF scores (not
% retrieved). This is useful to evaluate large retrieval systems in
% which one stores ony a handful of top results for efficiency
% reasons.
%
% About the ROC curve::
% Consider a classifier that predicts as positive all samples whose
% score is not smaller than a threshold S. The ROC curve represents
% the performance of such classifier as the threshold S is
% changed. Formally, define
%
% P = overall num. of positive samples,
% N = overall num. of negative samples,
%
% and for each threshold S
%
% TP(S) = num. of samples that are correctly classified as positive,
% TN(S) = num. of samples that are correctly classified as negative,
% FP(S) = num. of samples that are incorrectly classified as positive,
% FN(S) = num. of samples that are incorrectly classified as negative.
%
% Consider also the rates:
%
% TPR = TP(S) / P, FNR = FN(S) / P,
% TNR = TN(S) / N, FPR = FP(S) / N,
%
% and notice that by definition
%
% P = TP(S) + FN(S) , N = TN(S) + FP(S),
% 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S).
%
% The ROC curve is the parametric curve (TPR(S), TNR(S)) obtained
% as the classifier threshold S is varied in the reals. The TPR is
% also known as recall (see VL_PR()).
%
% The ROC curve is contained in the square with vertices (0,0) The
% (average) ROC curve of a random classifier is a line which
% connects (1,0) and (0,1).
%
% The ROC curve is independent of the prior probability of the
% labels (i.e. of P/(P+N) and N/(P+N)).
%
% REFERENCES:
% [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic
%
% See also: VL_PR(), VL_DET(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% 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).
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.plot = [] ;
opts.stable = false ;
opts = vl_argparse(opts,varargin) ;
% compute the rates
small = 1e-10 ;
tpr = tp / max(p, small) ;
fpr = fp / max(n, small) ;
fnr = 1 - tpr ;
tnr = 1 - fpr ;
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || nargout == 0
% Area under the curve. Since the curve is a staircase (in the
% sense that for each sample either tn is decremented by one
% or tp is incremented by one but the other remains fixed),
% the integral is particularly simple and exact.
info.auc = sum(tnr .* diff([0 tpr])) ;
% Equal error rate. One must find the index S for which there is a
% crossing between TNR(S) and TPR(s). If such a crossing exists,
% there are two cases:
%
% o tnr o
% / \
% 1-eer = tnr o-x-o 1-eer = tpr o-x-o
% / \
% tpr o o
%
% Moreover, if the maximum TPR is smaller than 1, then it is
% possible that neither of the two cases realizes (then EER=NaN).
s = max(find(tnr > tpr)) ;
if s == length(tpr)
info.eer = NaN ;
else
if tpr(s) == tpr(s+1)
info.eer = 1 - tpr(s) ;
else
info.eer = 1 - tnr(s) ;
end
end
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if ~isempty(opts.plot) || nargout == 0
if isempty(opts.plot), opts.plot = 'fptp' ; end
cla ; hold on ;
switch lower(opts.plot)
case {'truenegatives', 'tn', 'tntp'}
hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true negative rate') ;
ylabel('true positive rate (recall)') ;
loc = 'sw' ;
case {'falsepositives', 'fp', 'fptp'}
hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ;
spline([1 0], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive rate') ;
ylabel('true positive rate (recall)') ;
loc = 'se' ;
case {'tptn'}
hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true positive rate (recall)') ;
ylabel('false positive rate') ;
loc = 'sw' ;
case {'fpfn'}
hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive (false alarm) rate') ;
ylabel('false negative (miss) rate') ;
loc = 'ne' ;
otherwise
error('''%s'' is not a valid PLOT type.', opts.plot);
end
grid on ;
xlim([0 1]) ;
ylim([0 1]) ;
axis square ;
title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ...
'interpreter', 'none') ;
legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
tpr(1) = [] ;
tnr(1) = [] ;
tpr_ = tpr ;
tnr_ = tnr ;
tpr = NaN(size(tpr)) ;
tnr = NaN(size(tnr)) ;
tpr(perm) = tpr_ ;
tnr(perm) = tnr_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_click.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/plotop/vl_click.m | 2,661 | utf_8 | 6982e869cf80da57fdf68f5ebcd05a86 | function P = vl_click(N,varargin) ;
% VL_CLICK Click a point
% P=VL_CLICK() let the user click a point in the current figure and
% returns its coordinates in P. P is a two dimensiona vectors where
% P(1) is the point X-coordinate and P(2) the point Y-coordinate. The
% user can abort the operation by pressing any key, in which case the
% empty matrix is returned.
%
% P=VL_CLICK(N) lets the user select N points in a row. The user can
% stop inserting points by pressing any key, in which case the
% partial list is returned.
%
% VL_CLICK() accepts the following options:
%
% PlotMarker:: [0]
% Plot a marker as points are selected. The markers are deleted on
% exiting the function.
%
% See also: VL_CLICKPOINT(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% 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).
plot_marker = 0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'plotmarker'
plot_marker = varargin{k+1} ;
otherwise
error(['Uknown option ''', varargin{k}, '''.']) ;
end
end
if nargin < 1
N=1;
end
% --------------------------------------------------------------------
% Do job
% --------------------------------------------------------------------
fig = gcf ;
is_hold = ishold ;
hold on ;
bhandler = get(fig,'WindowButtonDownFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'WindowButtonDownFcn',@click_handler) ;
set(fig,'KeyPressFcn',@key_handler) ;
set(fig,'Pointer','crosshair') ;
P=[] ;
h=[] ;
data.exit=0;
guidata(fig,data) ;
while size(P,2) < N
uiwait(fig) ;
data = guidata(fig) ;
if(data.exit)
break ;
end
P = [P data.P] ;
if( plot_marker )
h=[h plot(data.P(1),data.P(2),'rx')] ;
end
end
if ~is_hold
hold off ;
end
if( plot_marker )
pause(.1);
delete(h) ;
end
set(fig,'WindowButtonDownFcn',bhandler) ;
set(fig,'KeyPressFcn',khandler) ;
set(fig,'Pointer',pointer) ;
% ====================================================================
function click_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
data.P = P ;
guidata(obj,data) ;
uiresume(gcbo) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_pr.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/plotop/vl_pr.m | 9,135 | utf_8 | c5d1b9d67f843d10c0b2c6b48fab3c53 | function [recall, precision, info] = vl_pr(labels, scores, varargin)
%VL_PR Precision-recall curve.
% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the
% precision-recall (PR) curve. LABELS are the ground truth labels,
% greather than zero for a positive sample and smaller than zero for
% a negative one. SCORES are the scores of the samples obtained from
% a classifier, where lager scores should correspond to positive
% samples.
%
% Samples are ranked by decreasing scores, starting from rank 1.
% PRECISION(K) and RECALL(K) are the precison and recall when
% samples of rank smaller or equal to K-1 are predicted to be
% positive and the remaining to be negative. So for example
% PRECISION(3) is the percentage of positive samples among the two
% samples with largest score. PRECISION(1) is the precision when no
% samples are predicted to be positive and is conventionally set to
% the value 1.
%
% Set to zero the lables of samples that should be ignored in the
% evaluation. Set to -INF the scores of samples which are not
% retrieved. If there are samples with -INF score, then the PR curve
% may have maximum recall smaller than 1, unless the INCLUDEINF
% option is used (see below). The options NUMNEGATIVES and
% NUMPOSITIVES can be used to add additional surrogate samples with
% -INF score (see below).
%
% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional
% structure INFO with the following fields:
%
% info.auc::
% The area under the precision-recall curve. If the INTERPOLATE
% option is set to FALSE, then trapezoidal interpolation is used
% to integrate the PR curve. If the INTERPOLATE option is set to
% TRUE, then the curve is piecewise constant and no other
% approximation is introduced in the calculation of the area. In
% the latter case, INFO.AUC is the same as INFO.AP.
%
% info.ap::
% Average precision as defined by TREC. This is the average of the
% precision observed each time a new positive sample is
% recalled. In this calculation, any sample with -INF score
% (unless INCLUDEINF is used) and any additional positive induced
% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE
% option is set to true, the AP is computed from the interpolated
% precision and the result is the same as INFO.AUC. Note that AP
% as defined by TREC normally does not use interpolation [1].
%
% info.ap_interp_11::
% 11-points interpolated average precision as defined by TREC.
% This is the average of the maximum precision for recall levels
% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in
% the PASCAL VOC challenge up to the 2008 edition.
%
% info.auc_pa08::
% Deprecated. It is the same of INFO.AP_INTERP_11.
%
% VL_PR(...) with no output arguments plots the PR curve in the
% current axis.
%
% VL_PR() accepts the following options:
%
% Interpolate:: false
% If set to true, use interpolated precision. The interpolated
% precision is defined as the maximum precision for a given recall
% level and onwards. Here it is implemented as the culumative
% maximum from low to high scores of the precision.
%
% NumPositives:: []
% NumNegatives:: []
% If set to a number, pretend that LABELS contains this may
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entrires in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence, as if they had -INF scores (not
% retrieved). This is useful to evaluate large retrieval systems
% for which one stores ony a handful of top results for efficiency
% reasons.
%
% IncludeInf:: false
% If set to true, data with -INF score SCORES is included in the
% evaluation and the maximum recall is 1 even if -INF scores are
% present. This option does not include any additional positive or
% negative data introduced by specifying NUMPOSITIVES and
% NUMNEGATIVES.
%
% Stable:: false
% If set to true, RECALL and PRECISION are returned the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score (increasing recall). Samples with -INF scores are assigned
% RECALL and PRECISION equal to NaN.
%
% NormalizePrior:: []
% If set to a scalar, reweights positive and negative labels so
% that the fraction of positive ones is equal to the specified
% value. This computes the normalised PR curves of [2]
%
% About the PR curve::
% This section uses the same symbols used in the documentation of
% the VL_ROC() function. In addition to those quantities, define:
%
% PRECISION(S) = TP(S) / (TP(S) + FP(S))
% RECALL(S) = TPR(S) = TP(S) / P
%
% The precision is the fraction of positivie predictions which are
% correct, and the recall is the fraction of positive labels that
% have been correctly classified (recalled). Notice that the recall
% is also equal to the true positive rate for the ROC curve (see
% VL_ROC()).
%
% REFERENCES:
% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to
% Information Retrieval. Cambridge University Press, 2008.
% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in
% object detectors. In Proc. ECCV, 2012.
%
% See also VL_ROC(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% 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).
% TP and FP are the vectors of true positie and false positve label
% counts for decreasing scores, P and N are the total number of
% positive and negative labels. Note that if certain options are used
% some labels may actually not be stored explicitly by LABELS, so P+N
% can be larger than the number of element of LABELS.
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.stable = false ;
opts.interpolate = false ;
opts.normalizePrior = [] ;
opts = vl_argparse(opts,varargin) ;
% compute precision and recall
small = 1e-10 ;
recall = tp / max(p, small) ;
if isempty(opts.normalizePrior)
precision = max(tp, small) ./ max(tp + fp, small) ;
else
a = opts.normalizePrior ;
precision = max(tp * a/max(p,small), small) ./ ...
max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ;
end
% interpolate precision if needed
if opts.interpolate
precision = fliplr(vl_cummax(fliplr(precision))) ;
end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || nargout == 0
% area under the curve using trapezoid interpolation
if ~opts.interpolate
info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ;
end
% average precision (for each recalled positive sample)
sel = find(diff(recall)) + 1 ;
info.ap = sum(precision(sel)) / p ;
if opts.interpolate
info.auc = info.ap ;
end
% TREC 11 points average interpolated precision
info.ap_interp_11 = 0.0 ;
for rc = linspace(0,1,11)
pr = max([0, precision(recall >= rc)]) ;
info.ap_interp_11 = info.ap_interp_11 + pr / 11 ;
end
% legacy definition
info.auc_pa08 = info.ap_interp_11 ;
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if nargout == 0
cla ; hold on ;
plot(recall,precision,'linewidth',2) ;
if isempty(opts.normalizePrior)
randomPrecision = p / (p + n) ;
else
randomPrecision = opts.normalizePrior ;
end
spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ;
axis square ; grid on ;
xlim([0 1]) ; xlabel('recall') ;
ylim([0 1]) ; ylabel('precision') ;
title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ...
info.auc * 100, ...
info.ap * 100, ...
info.ap_interp_11 * 100)) ;
if opts.interpolate
legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ;
else
legend('PR', 'PR rand.', 'Location', 'SouthEast') ;
end
clear recall precision info ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
precision(1) = [] ;
recall(1) = [] ;
precision_ = precision ;
recall_ = recall ;
precision = NaN(size(precision)) ;
recall = NaN(size(recall)) ;
precision(perm) = precision_ ;
recall(perm) = recall_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_ubcread.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/sift/vl_ubcread.m | 3,015 | utf_8 | e8ddd3ecd87e76b6c738ba153fef050f | function [f,d] = vl_ubcread(file, varargin)
% SIFTREAD Read Lowe's SIFT implementation data files
% [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D
% from FILE in UBC (Lowe's original implementation of SIFT) format
% and returns F and D as defined by VL_SIFT().
%
% VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by
% Oxford VGG implementations .
%
% See also: VL_SIFT(), VL_HELP().
% Authors: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% 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.verbosity = 0 ;
opts.format = 'ubc' ;
opts = vl_argparse(opts, varargin) ;
g = fopen(file, 'r');
if g == -1
error(['Could not open file ''', file, '''.']) ;
end
[header, count] = fscanf(g, '%d', [1 2]) ;
if count ~= 2
error('Invalid keypoint file header.');
end
switch opts.format
case 'ubc'
numKeypoints = header(1) ;
descrLen = header(2) ;
case 'oxford'
numKeypoints = header(2) ;
descrLen = header(1) ;
otherwise
error('Unknown format ''%s''.', opts.format) ;
end
if(opts.verbosity > 0)
fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ;
end
%creates two output matrices
switch opts.format
case 'ubc'
P = zeros(4,numKeypoints) ;
case 'oxford'
P = zeros(5,numKeypoints) ;
end
L = zeros(descrLen, numKeypoints) ;
%parse tmp.key
for k = 1:numKeypoints
switch opts.format
case 'ubc'
% Record format: i,j,s,th
[record, count] = fscanf(g, '%f', [1 4]) ;
if count ~= 4
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
case 'oxford'
% Record format: x, y, a, b, c such that x' [a b ; b c] x = 1
[record, count] = fscanf(g, '%f', [1 5]) ;
if count ~= 5
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
end
% Record format: descriptor
[record, count] = fscanf(g, '%d', [1 descrLen]) ;
if count ~= descrLen
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) );
end
L(:,k) = record(:) ;
end
fclose(g) ;
switch opts.format
case 'ubc'
P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y
f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ;
d=uint8(L) ;
p=[1 2 3 4 5 6 7 8] ;
q=[1 8 7 6 5 4 3 2] ;
for j=0:3
for i=0:3
d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ;
end
end
case 'oxford'
P(1:2,:) = P(1:2,:) + 1 ; % matlab origin
f = P ;
f(3:5,:) = inv2x2(f(3:5,:)) ;
d = uint8(L) ;
end
% --------------------------------------------------------------------
function S = inv2x2(C)
% --------------------------------------------------------------------
den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ;
S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_frame2oell.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/sift/vl_frame2oell.m | 2,806 | utf_8 | c93792632f630743485fa4c2cf12d647 | function eframes = vl_frame2oell(frames)
% VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse
% EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an
% oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with
% one frame per column.
%
% A frame is either a point, a disc, an oriented disc, an ellipse,
% or an oriented ellipse. These are represented respectively by 2,
% 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An
% oriented ellipse is the most general geometric frame; hence, there
% is no loss of information in this conversion.
%
% If FRAME is an oriented disc or ellipse, then the conversion is
% immediate. If, however, FRAME is not oriented (it is either a
% point or an unoriented disc or ellipse), then an orientation must
% be assigned. The orientation is chosen in such a way that the
% affine transformation that maps the standard oriented frame into
% the output EFRAME does not rotate the Y axis. If frames represent
% detected visual features, this convention corresponds to assume
% that features are upright.
%
% If FRAME is a point, then the output is an ellipse with null area.
%
% See: <a href="matlab:vl_help('tut.frame')">feature frames</a>,
% VL_PLOTFRAME(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.
% 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).
[D,K] = size(frames) ;
eframes = zeros(6,K) ;
switch D
case 2
eframes(1:2,:) = frames(1:2,:) ;
case 3
eframes(1:2,:) = frames(1:2,:) ;
eframes(3,:) = frames(3,:) ;
eframes(6,:) = frames(3,:) ;
case 4
r = frames(3,:) ;
c = r.*cos(frames(4,:)) ;
s = r.*sin(frames(4,:)) ;
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = [c ; s ; -s ; c] ;
case 5
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = mapFromS(frames(3:5,:)) ;
case 6
eframes = frames ;
otherwise
error('FRAMES format is unknown.') ;
end
% --------------------------------------------------------------------
function A = mapFromS(S)
% --------------------------------------------------------------------
% Returns the (stacking of the) 2x2 matrix A that maps the unit circle
% into the ellipses satisfying the equation x' inv(S) x = 1. Here S
% is a stacked covariance matrix, with elements S11, S12 and S22.
%
% The goal is to find A such that AA' = S. In order to let the Y
% direction unaffected (upright feature), the assumption is taht
% A = [a b ; 0 c]. Hence
%
% AA' = [a^2, ab ; ab, b^2+c^2] = S.
A = zeros(4,size(S,2)) ;
a = sqrt(S(1,:));
b = S(2,:) ./ max(a, 1e-18) ;
A(1,:) = a ;
A(2,:) = b ;
A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_plotsiftdescriptor.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/sift/vl_plotsiftdescriptor.m | 5,114 | utf_8 | a4e125a8916653f00143b61cceda2f23 | function h=vl_plotsiftdescriptor(d,f,varargin)
% VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a
% matrix, it plots one descriptor per column. D has the same format
% used by VL_SIFT().
%
% VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to
% the SIFT frames F, specified as columns of the matrix F. F has the
% same format used by VL_SIFT().
%
% H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line
% drawing representing the descriptors.
%
% The function assumes that the SIFT descriptors use the standard
% configuration of 4x4 spatial bins and 8 orientations bins. The
% following parameters can be used to change this:
%
% NumSpatialBins:: 4
% Number of spatial bins in both spatial directions X and Y.
%
% NumOrientationBins:: 8
% Number of orientation bis.
%
% MagnificationFactor:: 3
% Magnification factor. The width of one bin is equal to the scale
% of the keypoint F multiplied by this factor.
%
% See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% 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.magnificationFactor = 3.0 ;
opts.numSpatialBins = 4 ;
opts.numOrientationBins = 8 ;
opts.maxValue = 0 ;
if nargin > 1
if ~ isnumeric(f)
error('F must be a numeric type (use [] to leave it unspecified)') ;
end
end
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins)
error('The number of rows of D does not match the geometry of the descriptor') ;
end
if nargin > 1
if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6))
error('F must be either empty of have from 2 to six rows.');
end
if size(f,1) == 2
% translation only
f(3:6,:) = deal([10 0 0 10]') ;
%f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 3
% translation and scale
f(3:6,:) = [1 0 0 1]' * f(3,:) ;
%f = [f; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 4
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if size(f,1) == 5
assert(false) ;
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if(~isempty(f) & size(f,2) ~= size(d,2))
error('D and F have incompatible dimension') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2 | isempty(f)
f = repmat([0;0;1;0;0;1],1,K) ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
[x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ;
xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ;
yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue)
% --------------------------------------------------------------------
% Get the coordinates of the lines of the SIFT grid; each bin has side 1
[x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ;
% Get the corresponding bin centers
xc = x(1:end-1,1:end-1) + 0.5 ;
yc = y(1:end-1,1:end-1) + 0.5 ;
% Rescale the descriptor range so that the biggest peak fits inside the bin diagram
if maxValue
d = 0.4 * d / maxValue ;
else
d = 0.4 * d / max(d(:)+eps) ;
end
% We scramble the the centers to have them in row major order
% (descriptor convention).
xc = xc' ;
yc = yc' ;
% Each spatial bin contains a star with numOrientationBins tips
xc = repmat(xc(:)',numOrientationBins,1) ;
yc = repmat(yc(:)',numOrientationBins,1) ;
% Do the stars
th=linspace(0,2*pi,numOrientationBins+1) ;
th=th(1:end-1) ;
xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ;
yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ;
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ;
x1 = xc(:)' ;
y1 = yc(:)' ;
x2 = x1 + xd ;
y2 = y1 + yd ;
xstars = [x1;x2;nans] ;
ystars = [y1;y2;nans] ;
% Horizontal lines of the grid
nans = NaN * ones(1,numSpatialBins+1);
xh = [x(:,1)' ; x(:,end)' ; nans] ;
yh = [y(:,1)' ; y(:,end)' ; nans] ;
% Verical lines of the grid
xv = [x(1,:) ; x(end,:) ; nans] ;
yv = [y(1,:) ; y(end,:) ; nans] ;
x=[xstars(:)' xh(:)' xv(:)'] ;
y=[ystars(:)' yh(:)' yv(:)'] ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | phow_caltech101.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/apps/phow_caltech101.m | 11,594 | utf_8 | 7f4890a2e6844ca56debbfe23cca64f3 | function phow_caltech101()
% PHOW_CALTECH101 Image classification in the Caltech-101 dataset
% This program demonstrates how to use VLFeat to construct an image
% classifier on the Caltech-101 data. The classifier uses PHOW
% features (dense SIFT), spatial histograms of visual words, and a
% Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT,
% kd-trees, and homogeneous kernel map. The program also
% demonstrates VLFeat PEGASOS SVM solver, although for this small
% dataset other solvers such as LIBLINEAR can be more efficient.
%
% By default 15 training images are used, which should result in
% about 64% performance (a good performance considering that only a
% single feature type is being used).
%
% Call PHOW_CALTECH101 to train and test a classifier on a small
% subset of the Caltech-101 data. Note that the program
% automatically downloads a copy of the Caltech-101 data from the
% Internet if it cannot find a local copy.
%
% Edit the PHOW_CALTECH101 file to change the program configuration.
%
% To run on the entire dataset change CONF.TINYPROBLEM to FALSE.
%
% The Caltech-101 data is saved into CONF.CALDIR, which defaults to
% 'data/caltech-101'. Change this path to the desired location, for
% instance to point to an existing copy of the Caltech-101 data.
%
% The program can also be used to train a model on custom data by
% pointing CONF.CALDIR to it. Just create a subdirectory for each
% class and put the training images there. Make sure to adjust
% CONF.NUMTRAIN accordingly.
%
% Intermediate files are stored in the directory CONF.DATADIR. All
% such files begin with the prefix CONF.PREFIX, which can be changed
% to test different parameter settings without overriding previous
% results.
%
% The program saves the trained model in
% <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to
% test novel images independently of the Caltech data.
%
% load('data/baseline-model.mat') ; # change to the model path
% label = model.classify(model, im) ;
%
% Author: Andrea Vedaldi
% Copyright (C) 2011-2013 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).
conf.calDir = 'data/caltech-101' ;
conf.dataDir = 'data/' ;
conf.autoDownloadData = true ;
conf.numTrain = 15 ;
conf.numTest = 15 ;
conf.numClasses = 102 ;
conf.numWords = 600 ;
conf.numSpatialX = [2 4] ;
conf.numSpatialY = [2 4] ;
conf.quantizer = 'kdtree' ;
conf.svm.C = 10 ;
conf.svm.solver = 'sdca' ;
%conf.svm.solver = 'sgd' ;
%conf.svm.solver = 'liblinear' ;
conf.svm.biasMultiplier = 1 ;
conf.phowOpts = {'Step', 3} ;
conf.clobber = false ;
conf.tinyProblem = true ;
conf.prefix = 'baseline' ;
conf.randSeed = 1 ;
if conf.tinyProblem
conf.prefix = 'tiny' ;
conf.numClasses = 5 ;
conf.numSpatialX = 2 ;
conf.numSpatialY = 2 ;
conf.numWords = 300 ;
conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ;
end
conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ;
conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ;
conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ;
conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ;
randn('state',conf.randSeed) ;
rand('state',conf.randSeed) ;
vl_twister('state',conf.randSeed) ;
% --------------------------------------------------------------------
% Download Caltech-101 data
% --------------------------------------------------------------------
if ~exist(conf.calDir, 'dir') || ...
(~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ...
~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes')))
if ~conf.autoDownloadData
error(...
['Caltech-101 data not found. ' ...
'Set conf.autoDownloadData=true to download the required data.']) ;
end
vl_xmkdir(conf.calDir) ;
calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ...
'Caltech101/101_ObjectCategories.tar.gz'] ;
fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ;
untar(calUrl, conf.calDir) ;
end
if ~exist(fullfile(conf.calDir, 'airplanes'),'dir')
conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ;
end
% --------------------------------------------------------------------
% Setup data
% --------------------------------------------------------------------
classes = dir(conf.calDir) ;
classes = classes([classes.isdir]) ;
classes = {classes(3:conf.numClasses+2).name} ;
images = {} ;
imageClass = {} ;
for ci = 1:length(classes)
ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ;
ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ;
ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ;
images = {images{:}, ims{:}} ;
imageClass{end+1} = ci * ones(1,length(ims)) ;
end
selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ;
selTest = setdiff(1:length(images), selTrain) ;
imageClass = cat(2, imageClass{:}) ;
model.classes = classes ;
model.phowOpts = conf.phowOpts ;
model.numSpatialX = conf.numSpatialX ;
model.numSpatialY = conf.numSpatialY ;
model.quantizer = conf.quantizer ;
model.vocab = [] ;
model.w = [] ;
model.b = [] ;
model.classify = @classify ;
% --------------------------------------------------------------------
% Train vocabulary
% --------------------------------------------------------------------
if ~exist(conf.vocabPath) || conf.clobber
% Get some PHOW descriptors to train the dictionary
selTrainFeats = vl_colsubset(selTrain, 30) ;
descrs = {} ;
%for ii = 1:length(selTrainFeats)
parfor ii = 1:length(selTrainFeats)
im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ;
im = standarizeImage(im) ;
[drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ;
end
descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ;
descrs = single(descrs) ;
% Quantize the descriptors to get the visual words
vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ;
save(conf.vocabPath, 'vocab') ;
else
load(conf.vocabPath) ;
end
model.vocab = vocab ;
if strcmp(model.quantizer, 'kdtree')
model.kdtree = vl_kdtreebuild(vocab) ;
end
% --------------------------------------------------------------------
% Compute spatial histograms
% --------------------------------------------------------------------
if ~exist(conf.histPath) || conf.clobber
hists = {} ;
parfor ii = 1:length(images)
% for ii = 1:length(images)
fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ;
im = imread(fullfile(conf.calDir, images{ii})) ;
hists{ii} = getImageDescriptor(model, im);
end
hists = cat(2, hists{:}) ;
save(conf.histPath, 'hists') ;
else
load(conf.histPath) ;
end
% --------------------------------------------------------------------
% Compute feature map
% --------------------------------------------------------------------
psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ;
% --------------------------------------------------------------------
% Train SVM
% --------------------------------------------------------------------
if ~exist(conf.modelPath) || conf.clobber
switch conf.svm.solver
case {'sgd', 'sdca'}
lambda = 1 / (conf.svm.C * length(selTrain)) ;
w = [] ;
parfor ci = 1:length(classes)
perm = randperm(length(selTrain)) ;
fprintf('Training model for class %s\n', classes{ci}) ;
y = 2 * (imageClass(selTrain) == ci) - 1 ;
[w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ...
'Solver', conf.svm.solver, ...
'MaxNumIterations', 50/lambda, ...
'BiasMultiplier', conf.svm.biasMultiplier, ...
'Epsilon', 1e-3);
end
case 'liblinear'
svm = train(imageClass(selTrain)', ...
sparse(double(psix(:,selTrain))), ...
sprintf(' -s 3 -B %f -c %f', ...
conf.svm.biasMultiplier, conf.svm.C), ...
'col') ;
w = svm.w(:,1:end-1)' ;
b = svm.w(:,end)' ;
end
model.b = conf.svm.biasMultiplier * b ;
model.w = w ;
save(conf.modelPath, 'model') ;
else
load(conf.modelPath) ;
end
% --------------------------------------------------------------------
% Test SVM and evaluate
% --------------------------------------------------------------------
% Estimate the class of the test images
scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ;
[drop, imageEstClass] = max(scores, [], 1) ;
% Compute the confusion matrix
idx = sub2ind([length(classes), length(classes)], ...
imageClass(selTest), imageEstClass(selTest)) ;
confus = zeros(length(classes)) ;
confus = vl_binsum(confus, ones(size(idx)), idx) ;
% Plots
figure(1) ; clf;
subplot(1,2,1) ;
imagesc(scores(:,[selTrain selTest])) ; title('Scores') ;
set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ;
subplot(1,2,2) ;
imagesc(confus) ;
title(sprintf('Confusion matrix (%.2f %% accuracy)', ...
100 * mean(diag(confus)/conf.numTest) )) ;
print('-depsc2', [conf.resultPath '.ps']) ;
save([conf.resultPath '.mat'], 'confus', 'conf') ;
% -------------------------------------------------------------------------
function im = standarizeImage(im)
% -------------------------------------------------------------------------
im = im2single(im) ;
if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end
% -------------------------------------------------------------------------
function hist = getImageDescriptor(model, im)
% -------------------------------------------------------------------------
im = standarizeImage(im) ;
width = size(im,2) ;
height = size(im,1) ;
numWords = size(model.vocab, 2) ;
% get PHOW features
[frames, descrs] = vl_phow(im, model.phowOpts{:}) ;
% quantize local descriptors into visual words
switch model.quantizer
case 'vq'
[drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ;
case 'kdtree'
binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ...
single(descrs), ...
'MaxComparisons', 50)) ;
end
for i = 1:length(model.numSpatialX)
binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ;
binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ;
% combined quantization
bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ...
binsy,binsx,binsa) ;
hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ;
hist = vl_binsum(hist, ones(size(bins)), bins) ;
hists{i} = single(hist / sum(hist)) ;
end
hist = cat(1,hists{:}) ;
hist = hist / sum(hist) ;
% -------------------------------------------------------------------------
function [className, score] = classify(model, im)
% -------------------------------------------------------------------------
hist = getImageDescriptor(model, im) ;
psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | sift_mosaic.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/apps/sift_mosaic.m | 4,621 | utf_8 | 8fa3ad91b401b8f2400fb65944c79712 | function mosaic = sift_mosaic(im1, im2)
% SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC
%
% SIFT_MOSAIC demonstrates matching two images based on SIFT
% features and RANSAC and computing their mosaic.
%
% SIFT_MOSAIC by itself runs the algorithm on two standard test
% images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two
% custom images IM1 and IM2.
% AUTORIGHTS
if nargin == 0
im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ;
end
% make single
im1 = im2single(im1) ;
im2 = im2single(im2) ;
% make grayscale
if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end
if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end
% --------------------------------------------------------------------
% SIFT matches
% --------------------------------------------------------------------
[f1,d1] = vl_sift(im1g) ;
[f2,d2] = vl_sift(im2g) ;
[matches, scores] = vl_ubcmatch(d1,d2) ;
numMatches = size(matches,2) ;
X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ;
X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ;
% --------------------------------------------------------------------
% RANSAC with homography model
% --------------------------------------------------------------------
clear H score ok ;
for t = 1:100
% estimate homograpyh
subset = vl_colsubset(1:numMatches, 4) ;
A = [] ;
for i = subset
A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ;
end
[U,S,V] = svd(A) ;
H{t} = reshape(V(:,9),3,3) ;
% score homography
X2_ = H{t} * X1 ;
du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ;
dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ;
ok{t} = (du.*du + dv.*dv) < 6*6 ;
score(t) = sum(ok{t}) ;
end
[score, best] = max(score) ;
H = H{best} ;
ok = ok{best} ;
% --------------------------------------------------------------------
% Optional refinement
% --------------------------------------------------------------------
function err = residual(H)
u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ;
v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ;
d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ;
du = X2(1,ok) - u ./ d ;
dv = X2(2,ok) - v ./ d ;
err = sum(du.*du + dv.*dv) ;
end
if exist('fminsearch') == 2
H = H / H(3,3) ;
opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ;
H(1:8) = fminsearch(@residual, H(1:8)', opts) ;
else
warning('Refinement disabled as fminsearch was not found.') ;
end
% --------------------------------------------------------------------
% Show matches
% --------------------------------------------------------------------
dh1 = max(size(im2,1)-size(im1,1),0) ;
dh2 = max(size(im1,1)-size(im2,1),0) ;
figure(1) ; clf ;
subplot(2,1,1) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ...
[f1(2,matches(1,:));f2(2,matches(2,:))]) ;
title(sprintf('%d tentative matches', numMatches)) ;
axis image off ;
subplot(2,1,2) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ...
[f1(2,matches(1,ok));f2(2,matches(2,ok))]) ;
title(sprintf('%d (%.2f%%) inliner matches out of %d', ...
sum(ok), ...
100*sum(ok)/numMatches, ...
numMatches)) ;
axis image off ;
drawnow ;
% --------------------------------------------------------------------
% Mosaic
% --------------------------------------------------------------------
box2 = [1 size(im2,2) size(im2,2) 1 ;
1 1 size(im2,1) size(im2,1) ;
1 1 1 1 ] ;
box2_ = inv(H) * box2 ;
box2_(1,:) = box2_(1,:) ./ box2_(3,:) ;
box2_(2,:) = box2_(2,:) ./ box2_(3,:) ;
ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ;
vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ;
[u,v] = meshgrid(ur,vr) ;
im1_ = vl_imwbackward(im2double(im1),u,v) ;
z_ = H(3,1) * u + H(3,2) * v + H(3,3) ;
u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ;
v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ;
im2_ = vl_imwbackward(im2double(im2),u_,v_) ;
mass = ~isnan(im1_) + ~isnan(im2_) ;
im1_(isnan(im1_)) = 0 ;
im2_(isnan(im2_)) = 0 ;
mosaic = (im1_ + im2_) ./ mass ;
figure(2) ; clf ;
imagesc(mosaic) ; axis image off ;
title('Mosaic') ;
if nargout == 0, clear mosaic ; end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | encodeImage.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/apps/recognition/encodeImage.m | 5,278 | utf_8 | 5d9dc6161995b8e10366b5649bf4fda4 | function descrs = encodeImage(encoder, im, varargin)
% ENCODEIMAGE Apply an encoder to an image
% DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER
% to image IM, returning a corresponding code vector PSI.
%
% IM can be an image, the path to an image, or a cell array of
% the same, to operate on multiple images.
%
% ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE
% directory to store encodings for the given images. The cache
% is used only if the images are specified as file names.
%
% See also: TRAINENCODER().
% Author: Andrea Vedaldi
% Copyright (C) 2013 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.cacheDir = [] ;
opts.cacheChunkSize = 512 ;
opts = vl_argparse(opts,varargin) ;
if ~iscell(im), im = {im} ; end
% break the computation into cached chunks
startTime = tic ;
descrs = cell(1, numel(im)) ;
numChunks = ceil(numel(im) / opts.cacheChunkSize) ;
for c = 1:numChunks
n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ;
chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ;
if ~isempty(opts.cacheDir) && exist(chunkPath)
fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ;
load(chunkPath, 'data') ;
else
range = (c-1)*opts.cacheChunkSize + (1:n) ;
fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ...
mfilename, numel(range), ...
c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ;
data = processChunk(encoder, im(range)) ;
if ~isempty(opts.cacheDir)
save(chunkPath, 'data') ;
end
end
descrs{c} = data ;
clear data ;
end
descrs = cat(2,descrs{:}) ;
% --------------------------------------------------------------------
function psi = processChunk(encoder, im)
% --------------------------------------------------------------------
psi = cell(1,numel(im)) ;
if numel(im) > 1 & matlabpool('size') > 1
parfor i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
else
% avoiding parfor makes debugging easier
for i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
end
psi = cat(2, psi{:}) ;
% --------------------------------------------------------------------
function psi = encodeOne(encoder, im)
% --------------------------------------------------------------------
im = encoder.readImageFn(im) ;
features = encoder.extractorFn(im) ;
imageSize = size(im) ;
psi = {} ;
for i = 1:size(encoder.subdivisions,2)
minx = encoder.subdivisions(1,i) * imageSize(2) ;
miny = encoder.subdivisions(2,i) * imageSize(1) ;
maxx = encoder.subdivisions(3,i) * imageSize(2) ;
maxy = encoder.subdivisions(4,i) * imageSize(1) ;
ok = ...
minx <= features.frame(1,:) & features.frame(1,:) < maxx & ...
miny <= features.frame(2,:) & features.frame(2,:) < maxy ;
descrs = encoder.projection * bsxfun(@minus, ...
features.descr(:,ok), ...
encoder.projectionCenter) ;
if encoder.renormalize
descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ;
end
w = size(im,2) ;
h = size(im,1) ;
frames = features.frame(1:2,:) ;
frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ;
descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ;
switch encoder.type
case 'bovw'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 100) ;
z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ;
z = sqrt(z) ;
case 'fv'
z = vl_fisher(descrs, ...
encoder.means, ...
encoder.covariances, ...
encoder.priors, ...
'Improved') ;
case 'vlad'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 15) ;
assign = zeros(encoder.numWords, numel(words), 'single') ;
assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ;
z = vl_vlad(descrs, ...
encoder.words, ...
assign, ...
'SquareRoot', ...
'NormalizeComponents') ;
end
z = z / max(sqrt(sum(z.^2)), 1e-12) ;
psi{i} = z(:) ;
end
psi = cat(1, psi{:}) ;
% --------------------------------------------------------------------
function psi = getFromCache(name, cache)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
if exist(cachePath, 'file')
data = load(cachePath) ;
psi = data.psi ;
else
psi = [] ;
end
% --------------------------------------------------------------------
function storeToCache(name, cache, psi)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
vl_xmkdir(cache) ;
data.psi = psi ;
save(cachePath, '-STRUCT', 'data') ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | experiments.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/apps/recognition/experiments.m | 6,905 | utf_8 | 1e4a4911eed4a451b9488b9e6cc9b39c | function experiments()
% EXPERIMENTS Run image classification experiments
% The experimens download a number of benchmark datasets in the
% 'data/' subfolder. Make sure that there are several GBs of
% space available.
%
% By default, experiments run with a lite option turned on. This
% quickly runs all of them on tiny subsets of the actual data.
% This is used only for testing; to run the actual experiments,
% set the lite variable to false.
%
% Running all the experiments is a slow process. Using parallel
% MATLAB and several cores/machiens is suggested.
% Author: Andrea Vedaldi
% Copyright (C) 2013 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).
lite = true ;
clear ex ;
ex(1).prefix = 'fv-aug' ;
ex(1).trainOpts = {'C', 10} ;
ex(1).datasets = {'fmd', 'scene67'} ;
ex(1).seed = 1 ;
ex(1).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(2) = ex(1) ;
ex(2).datasets = {'caltech101'} ;
ex(2).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(3) = ex(1) ;
ex(3).datasets = {'voc07'} ;
ex(3).C = 1 ;
ex(4) = ex(1) ;
ex(4).prefix = 'vlad-aug' ;
ex(4).opts = {...
'type', 'vlad', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(5) = ex(4) ;
ex(5).datasets = {'caltech101'} ;
ex(5).opts{end} = ex(2).opts{end} ;
ex(6) = ex(4) ;
ex(6).datasets = {'voc07'} ;
ex(6).C = 1 ;
ex(7) = ex(1) ;
ex(7).prefix = 'bovw-aug' ;
ex(7).opts = {...
'type', 'bovw', ...
'numWords', 4096, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(8) = ex(7) ;
ex(8).datasets = {'caltech101'} ;
ex(8).opts{end} = ex(2).opts{end} ;
ex(9) = ex(7) ;
ex(9).datasets = {'voc07'} ;
ex(9).C = 1 ;
ex(10).prefix = 'fv' ;
ex(10).trainOpts = {'C', 10} ;
ex(10).datasets = {'fmd', 'scene67'} ;
ex(10).seed = 1 ;
ex(10).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(11) = ex(10) ;
ex(11).datasets = {'caltech101'} ;
ex(11).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(12) = ex(10) ;
ex(12).datasets = {'voc07'} ;
ex(12).C = 1 ;
ex(13).prefix = 'fv-sp' ;
ex(13).trainOpts = {'C', 10} ;
ex(13).datasets = {'fmd', 'scene67'} ;
ex(13).seed = 1 ;
ex(13).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1', '3x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(14) = ex(13) ;
ex(14).datasets = {'caltech101'} ;
ex(14).opts{6} = {'1x1', '2x2'} ;
ex(14).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(15) = ex(13) ;
ex(15).datasets = {'voc07'} ;
ex(15).C = 1 ;
if lite, tag = 'lite' ;
else, tag = 'ex' ; end
for i=1:numel(ex)
for j=1:numel(ex(i).datasets)
dataset = ex(i).datasets{j} ;
if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts)
ex(i).trainOpts = {} ;
end
traintest(...
'prefix', [tag '-' dataset '-' ex(i).prefix], ...
'seed', ex(i).seed, ...
'dataset', char(dataset), ...
'datasetDir', fullfile('data', dataset), ...
'lite', lite, ...
ex(i).trainOpts{:}, ...
'encoderParams', ex(i).opts) ;
end
end
% print HTML table
pf('<table>\n') ;
ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ;
pr('FV', ...
ge([tag '-voc07-fv'],'ap11'), ...
ge([tag '-caltech101-fv']), ...
ge([tag '-scene67-fv']), ...
ge([tag '-fmd-fv'])) ;
pr('FV + aug.', ...
ge([tag '-voc07-fv-aug'],'ap11'), ...
ge([tag '-caltech101-fv-aug']), ...
ge([tag '-scene67-fv-aug']), ...
ge([tag '-fmd-fv-aug'])) ;
pr('FV + s.p.', ...
ge([tag '-voc07-fv-sp'],'ap11'), ...
ge([tag '-caltech101-fv-sp']), ...
ge([tag '-scene67-fv-sp']), ...
ge([tag '-fmd-fv-sp'])) ;
%pr('VLAD', ...
% ge([tag '-voc07-vlad'],'ap11'), ...
% ge([tag '-caltech101-vlad']), ...
% ge([tag '-scene67-vlad']), ...
% ge([tag '-fmd-vlad'])) ;
pr('VLAD + aug.', ...
ge([tag '-voc07-vlad-aug'],'ap11'), ...
ge([tag '-caltech101-vlad-aug']), ...
ge([tag '-scene67-vlad-aug']), ...
ge([tag '-fmd-vlad-aug'])) ;
%pr('VLAD+sp', ...
% ge([tag '-voc07-vlad-sp'],'ap11'), ...
% ge([tag '-caltech101-vlad-sp']), ...
% ge([tag '-scene67-vlad-sp']), ...
% ge([tag '-fmd-vlad-sp'])) ;
%pr('BOVW', ...
% ge([tag '-voc07-bovw'],'ap11'), ...
% ge([tag '-caltech101-bovw']), ...
% ge([tag '-scene67-bovw']), ...
% ge([tag '-fmd-bovw'])) ;
pr('BOVW + aug.', ...
ge([tag '-voc07-bovw-aug'],'ap11'), ...
ge([tag '-caltech101-bovw-aug']), ...
ge([tag '-scene67-bovw-aug']), ...
ge([tag '-fmd-bovw-aug'])) ;
%pr('BOVW+sp', ...
% ge([tag '-voc07-bovw-sp'],'ap11'), ...
% ge([tag '-caltech101-bovw-sp']), ...
% ge([tag '-scene67-bovw-sp']), ...
% ge([tag '-fmd-bovw-sp'])) ;
pf('</table>\n');
function pf(str)
fprintf(str) ;
function str = ge(name, format)
if nargin == 1, format = 'acc'; end
data = load(fullfile('data', name, 'result.mat')) ;
switch format
case 'acc'
str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ;
case 'ap11'
str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ;
end
function pr(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end
fprintf('</tr>\n') ;
function ph(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end
fprintf('</tr>\n') ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | getDenseSIFT.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/apps/recognition/getDenseSIFT.m | 1,679 | utf_8 | 2059c0a2a4e762226d89121408c6e51c | function features = getDenseSIFT(im, varargin)
% GETDENSESIFT Extract dense SIFT features
% FEATURES = GETDENSESIFT(IM) extract dense SIFT features from
% image IM.
% Author: Andrea Vedaldi
% Copyright (C) 2013 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.scales = logspace(log10(1), log10(.25), 5) ;
opts.contrastthreshold = 0 ;
opts.step = 3 ;
opts.rootSift = false ;
opts.normalizeSift = true ;
opts.binSize = 8 ;
opts.geometry = [4 4 8] ;
opts.sigma = 0 ;
opts = vl_argparse(opts, varargin) ;
dsiftOpts = {'norm', 'fast', 'floatdescriptors', ...
'step', opts.step, ...
'size', opts.binSize, ...
'geometry', opts.geometry} ;
if size(im,3)>1, im = rgb2gray(im) ; end
im = im2single(im) ;
im = vl_imsmooth(im, opts.sigma) ;
for si = 1:numel(opts.scales)
im_ = imresize(im, opts.scales(si)) ;
[frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ;
% root SIFT
if opts.rootSift
descrs{si} = sqrt(descrs{si}) ;
end
if opts.normalizeSift
descrs{si} = snorm(descrs{si}) ;
end
% zero low contrast descriptors
info.contrast{si} = frames{si}(3,:) ;
kill = info.contrast{si} < opts.contrastthreshold ;
descrs{si}(:,kill) = 0 ;
% store frames
frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ;
frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ;
end
features.frame = cat(2, frames{:}) ;
features.descr = cat(2, descrs{:}) ;
features.contrast = cat(2, info.contrast{:}) ;
function x = snorm(x)
x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
|
github | joe-of-all-trades/vtkwrite-master | vtkwrite.m | .m | vtkwrite-master/vtkwrite.m | 11,698 | utf_8 | b2d2311772bb3c962cf4c421b43f3ea2 | function vtkwrite( filename,dataType,varargin )
% VTKWRITE Writes 3D Matlab array into VTK file format.
% vtkwrite(filename,'structured_grid',x,y,z,'vectors',title,u,v,w) writes
% a structured 3D vector data into VTK file, with name specified by the string
% filename. (u,v,w) are the vector components at the points (x,y,z). x,y,z
% should be 3-D matrices like those generated by meshgrid, where
% point(ijk) is specified by x(i,j,k), y(i,j,k) and z(i,j,k).
% The matrices x,y,z,u,v,w must all be the same size and contain
% corrresponding position and vector component. The string title specifies
% the name of the vector field to be saved.
%
% vtkwrite(filename,'structured_grid',x,y,z,'scalars',title,r) writes a 3D
% scalar data into VTK file whose name is specified by the string
% filename. r is the scalar value at the points (x,y,z). The matrices
% x,y,z,r must all be the same size and contain the corresponding position
% and scalar values.
%
% vtkwrite(filename,'structured_grid',x,y,z,'vectors',title,u,v,w,'scalars',
% title2,r) writes a 3D structured grid that contains both vector and scalar values.
% x,y,z,u,v,w,r must all be the same size and contain the corresponding
% positon, vector and scalar values.
%
% vtkwrite(filename, 'structured_points', title, m) saves matrix m (could
% be 1D, 2D or 3D array) into vtk as structured points.
%
% vtkwrite(filename, 'structured_points', title, m, 'spacing', sx, sy, sz)
% allows user to specify spacing. (default: 1, 1, 1). This is the aspect
% ratio of a single voxel.
%
% vtkwrite(filename, 'structured_points', title, m, 'origin', ox, oy, oz)
% allows user to speicify origin of dataset. (default: 0, 0, 0).
%
% vtkwrite(filename,'unstructured_grid',x,y,z,'vectors',title,u,v,w,'scalars',
% title2,r) writes a 3D unstructured grid that contains both vector and scalar values.
% x,y,z,u,v,w,r must all be the same size and contain the corresponding
% positon, vector and scalar values.
%
% vtkwrite(filename, 'polydata', 'lines', x, y, z) exports a 3D line where
% x,y,z are coordinates of the points that make the line. x, y, z are
% vectors containing the coordinates of points of the line, where point(n)
% is specified by x(n), y(n) and z(n).
%
% vtkwrite(filename,'polydata','lines',x,y,z,'Precision',n) allows you to
% specify precision of the exported number up to n digits after decimal
% point. Default precision is 3 digits.
%
% vtkwrite(filename,'polydata','triangle',x,y,z,tri) exports a list of
% triangles where x,y,z are the coordinates of the points and tri is an
% m*3 matrix whose rows denote the points of the individual triangles.
%
% vtkwrite(filename,'polydata','tetrahedron',x,y,z,tetra) exports a list
% of tetrahedrons where x,y,z are the coordinates of the points
% and tetra is an m*4 matrix whose rows denote the points of individual
% tetrahedrons.
%
% vtkwrite('execute','polydata','lines',x,y,z) will save data with default
% filename ''matlab_export.vtk' and automatically loads data into
% ParaView.
%
% Version 2.3
% Copyright, Chaoyuan Yeh, 2016
% Codes are modified from William Thielicke and David Gingras's submission.
if strcmpi(filename,'execute'), filename = 'matlab_export.vtk'; end
fid = fopen(filename, 'w');
% VTK files contain five major parts
% 1. VTK DataFile Version
fprintf(fid, '# vtk DataFile Version 2.0\n');
% 2. Title
fprintf(fid, 'VTK from Matlab\n');
binaryflag = any(strcmpi(varargin, 'BINARY'));
if any(strcmpi(varargin, 'PRECISION'))
precision = num2str(varargin{find(strcmpi(vin, 'PRECISION'))+1});
else
precision = '2';
end
switch upper(dataType)
case 'STRUCTURED_POINTS'
title = varargin{1};
m = varargin{2};
if any(strcmpi(varargin, 'spacing'))
sx = varargin{find(strcmpi(varargin, 'spacing'))+1};
sy = varargin{find(strcmpi(varargin, 'spacing'))+2};
sz = varargin{find(strcmpi(varargin, 'spacing'))+3};
else
sx = 1;
sy = 1;
sz = 1;
end
if any(strcmpi(varargin, 'origin'))
ox = varargin{find(strcmpi(varargin, 'origin'))+1};
oy = varargin{find(strcmpi(varargin, 'origin'))+2};
oz = varargin{find(strcmpi(varargin, 'origin'))+3};
else
ox = 0;
oy = 0;
oz = 0;
end
[nx, ny, nz] = size(m);
setdataformat(fid, binaryflag);
fprintf(fid, 'DATASET STRUCTURED_POINTS\n');
fprintf(fid, 'DIMENSIONS %d %d %d\n', nx, ny, nz);
fprintf(fid, ['SPACING ', num2str(sx), ' ', num2str(sy), ' ',...
num2str(sz), '\n']);
fprintf(fid, ['ORIGIN ', num2str(ox), ' ', num2str(oy), ' ',...
num2str(oz), '\n']);
fprintf(fid, 'POINT_DATA %d\n', nx*ny*nz);
fprintf(fid, ['SCALARS ', title, ' float 1\n']);
fprintf(fid,'LOOKUP_TABLE default\n');
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, m(:)');
else
fwrite(fid, m(:)', 'float', 'b');
end
case {'STRUCTURED_GRID','UNSTRUCTURED_GRID'}
% 3. The format data proper is saved in (ASCII or Binary). Use
% fprintf to write data in the case of ASCII and fwrite for binary.
if numel(varargin)<6, error('Not enough input arguments'); end
setdataformat(fid, binaryflag);
% fprintf(fid, 'BINARY\n');
x = varargin{1};
y = varargin{2};
z = varargin{3};
if sum(size(x)==size(y) & size(y)==size(z))~=length(size(x))
error('Input dimesions do not match')
end
n_elements = numel(x);
% 4. Type of Dataset ( can be STRUCTURED_POINTS, STRUCTURED_GRID,
% UNSTRUCTURED_GRID, POLYDATA, RECTILINEAR_GRID or FIELD )
% This part, dataset structure, begins with a line containing the
% keyword 'DATASET' followed by a keyword describing the type of dataset.
% Then the geomettry part describes geometry and topology of the dataset.
if strcmpi(dataType,'STRUCTURED_GRID')
fprintf(fid, 'DATASET STRUCTURED_GRID\n');
fprintf(fid, 'DIMENSIONS %d %d %d\n', size(x,1), size(x,2), size(x,3));
else
fprintf(fid, 'DATASET UNSTRUCTURED_GRID\n');
end
fprintf(fid, ['POINTS ' num2str(n_elements) ' float\n']);
output = [x(:)'; y(:)'; z(:)'];
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, output);
else
fwrite(fid, output, 'float', 'b');
end
% 5.This final part describe the dataset attributes and begins with the
% keywords 'POINT_DATA' or 'CELL_DATA', followed by an integer number
% specifying the number of points of cells. Other keyword/data combination
% then define the actual dataset attribute values.
fprintf(fid, ['\nPOINT_DATA ' num2str(n_elements)]);
% Parse remaining argument.
vidx = find(strcmpi(varargin,'VECTORS'));
sidx = find(strcmpi(varargin,'SCALARS'));
if vidx~=0
for ii = 1:length(vidx)
title = varargin{vidx(ii)+1};
% Data enteries begin with a keyword specifying data type
% and numeric format.
fprintf(fid, ['\nVECTORS ', title,' float\n']);
output = [varargin{ vidx(ii) + 2 }(:)';...
varargin{ vidx(ii) + 3 }(:)';...
varargin{ vidx(ii) + 4 }(:)'];
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, output);
else
fwrite(fid, output, 'float', 'b');
end
% fwrite(fid, [reshape(varargin{vidx(ii)+2},1,n_elements);...
% reshape(varargin{vidx(ii)+3},1,n_elements);...
% reshape(varargin{vidx(ii)+4},1,n_elements)],'float','b');
end
end
if sidx~=0
for ii = 1:length(sidx)
title = varargin{sidx(ii)+1};
fprintf(fid, ['\nSCALARS ', title,' float\n']);
fprintf(fid, 'LOOKUP_TABLE default\n');
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, varargin{ sidx(ii) + 2});
else
fwrite(fid, varargin{ sidx(ii) + 2}, 'float', 'b');
end
% fwrite(fid, reshape(varargin{sidx(ii)+2},1,n_elements),'float','b');
end
end
case 'POLYDATA'
fprintf(fid, 'ASCII\n');
if numel(varargin)<4, error('Not enough input arguments'); end
x = varargin{2}(:);
y = varargin{3}(:);
z = varargin{4}(:);
if numel(varargin)<4, error('Not enough input arguments'); end
if sum(size(x)==size(y) & size(y)==size(z))~= length(size(x))
error('Input dimesions do not match')
end
n_elements = numel(x);
fprintf(fid, 'DATASET POLYDATA\n');
if mod(n_elements,3)==1
x(n_elements+1:n_elements+2,1)=[0;0];
y(n_elements+1:n_elements+2,1)=[0;0];
z(n_elements+1:n_elements+2,1)=[0;0];
elseif mod(n_elements,3)==2
x(n_elements+1,1)=0;
y(n_elements+1,1)=0;
z(n_elements+1,1)=0;
end
nbpoint = numel(x);
fprintf(fid, ['POINTS ' num2str(nbpoint) ' float\n']);
spec = [repmat(['%0.', precision, 'f '], 1, 9), '\n'];
output = [x(1:3:end-2), y(1:3:end-2), z(1:3:end-2),...
x(2:3:end-1), y(2:3:end-1), z(2:3:end-1),...
x(3:3:end), y(3:3:end), z(3:3:end)]';
fprintf(fid, spec, output);
switch upper(varargin{1})
case 'LINES'
if mod(n_elements,2)==0
nbLine = 2*n_elements-2;
else
nbLine = 2*(n_elements-1);
end
conn1 = zeros(nbLine,1);
conn2 = zeros(nbLine,1);
conn2(1:nbLine/2) = 1:nbLine/2;
conn1(1:nbLine/2) = conn2(1:nbLine/2)-1;
conn1(nbLine/2+1:end) = 1:nbLine/2;
conn2(nbLine/2+1:end) = conn1(nbLine/2+1:end)-1;
fprintf(fid,'\nLINES %d %d\n',nbLine,3*nbLine);
fprintf(fid,'2 %d %d\n',[conn1';conn2']);
case 'TRIANGLE'
ntri = length(varargin{5});
fprintf(fid,'\nPOLYGONS %d %d\n',ntri,4*ntri);
fprintf(fid,'3 %d %d %d\n',(varargin{5}-1)');
case 'TETRAHEDRON'
ntetra = length(varargin{5});
fprintf(fid,'\nPOLYGONS %d %d\n',ntetra,5*ntetra);
fprintf(fid,'4 %d %d %d %d\n',(varargin{5}-1)');
end
end
fclose(fid);
if strcmpi(filename,'matlab_export.vtk')
switch computer
case {'PCWIN','PCWIN64'}
!paraview.exe --data='matlab_export.vtk' &
% Exclamation point character is a shell escape, the rest of the
% input line will be sent to operating system. It can not take
% variables, though. The & at the end of line will return control to
% Matlab even when the outside process is still running.
case {'GLNXA64','MACI64'}
!paraview --data='matlab_export.vtk' &
end
end
end
function setdataformat(fid, binaryflag)
if ~binaryflag
fprintf(fid, 'ASCII\n');
else
fprintf(fid, 'BINARY\n');
end
end
|
github | krrish94/caffe-keypoint-master | classification_demo.m | .m | caffe-keypoint-master/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 | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex8/submit.m | 17,515 | utf_8 | 2949fbde41e47f99c42171e2e0a39efc | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '8';
end
function [partNames] = validParts()
partNames = { 'Estimate Gaussian Parameters', ...
'Select Threshold' ...
'Collaborative Filtering Cost', ...
'Collaborative Filtering Gradient', ...
'Regularized Cost', ...
'Regularized Gradient' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'estimateGaussian.m' }, ...
{ 'selectThreshold.m' }, ...
{ 'cofiCostFunc.m' }, ...
{ 'cofiCostFunc.m' }, ...
{ 'cofiCostFunc.m' }, ...
{ 'cofiCostFunc.m' }, ...
};
end
function out = output(partId, auxstring)
% Random Test Cases
n_u = 3; n_m = 4; n = 5;
X = reshape(sin(1:n_m*n), n_m, n);
Theta = reshape(cos(1:n_u*n), n_u, n);
Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
R = Y > 0.5;
pval = [abs(Y(:)) ; 0.001; 1];
yval = [R(:) ; 1; 0];
params = [X(:); Theta(:)];
if partId == 1
[mu sigma2] = estimateGaussian(X);
out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
elseif partId == 2
[bestEpsilon bestF1] = selectThreshold(yval, pval);
out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
elseif partId == 3
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', J(:));
elseif partId == 4
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', grad(:));
elseif partId == 5
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', J(:));
elseif partId == 6
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', grad(:));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex8/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex6/submit.m | 16,836 | utf_8 | d4c87e5dbf32a81bdaf04fd017fe4cb3 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '6';
end
function [partNames] = validParts()
partNames = { 'Gaussian Kernel', ...
'Parameters (C, sigma) for Dataset 3', ...
'Email Preprocessing' ...
'Email Feature Extraction' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'gaussianKernel.m' }, ...
{ 'dataset3Params.m' }, ...
{ 'processEmail.m' }, ...
{ 'emailFeatures.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
x1 = sin(1:10)';
x2 = cos(1:10)';
ec = 'the quick brown fox jumped over the lazy dog';
wi = 1 + abs(round(x1 * 1863));
wi = [wi ; wi];
if partId == 1
sim = gaussianKernel(x1, x2, 2);
out = sprintf('%0.5f ', sim);
elseif partId == 2
load('ex6data3.mat');
[C, sigma] = dataset3Params(X, y, Xval, yval);
out = sprintf('%0.5f ', C);
out = [out sprintf('%0.5f ', sigma)];
elseif partId == 3
word_indices = processEmail(ec);
out = sprintf('%d ', word_indices);
elseif partId == 4
x = emailFeatures(wi);
out = sprintf('%d ', x);
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | porterStemmer.m | .m | coursera-machine-learning-1-master/mlclass-ex6/porterStemmer.m | 9,902 | utf_8 | 7ed5acd925808fde342fc72bd62ebc4d | function stem = porterStemmer(inString)
% Applies the Porter Stemming algorithm as presented in the following
% paper:
% Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
% no. 3, pp 130-137
% Original code modeled after the C version provided at:
% http://www.tartarus.org/~martin/PorterStemmer/c.txt
% The main part of the stemming algorithm starts here. b is an array of
% characters, holding the word to be stemmed. The letters are in b[k0],
% b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since
% matlab begins indexing by 1 instead of 0). k is readjusted downwards as
% the stemming progresses. Zero termination is not in fact used in the
% algorithm.
% To call this function, use the string to be stemmed as the input
% argument. This function returns the stemmed word as a string.
% Lower-case string
inString = lower(inString);
global j;
b = inString;
k = length(b);
k0 = 1;
j = k;
% With this if statement, strings of length 1 or 2 don't go through the
% stemming process. Remove this conditional to match the published
% algorithm.
stem = b;
if k > 2
% Output displays per step are commented out.
%disp(sprintf('Word to stem: %s', b));
x = step1ab(b, k, k0);
%disp(sprintf('Steps 1A and B yield: %s', x{1}));
x = step1c(x{1}, x{2}, k0);
%disp(sprintf('Step 1C yields: %s', x{1}));
x = step2(x{1}, x{2}, k0);
%disp(sprintf('Step 2 yields: %s', x{1}));
x = step3(x{1}, x{2}, k0);
%disp(sprintf('Step 3 yields: %s', x{1}));
x = step4(x{1}, x{2}, k0);
%disp(sprintf('Step 4 yields: %s', x{1}));
x = step5(x{1}, x{2}, k0);
%disp(sprintf('Step 5 yields: %s', x{1}));
stem = x{1};
end
% cons(j) is TRUE <=> b[j] is a consonant.
function c = cons(i, b, k0)
c = true;
switch(b(i))
case {'a', 'e', 'i', 'o', 'u'}
c = false;
case 'y'
if i == k0
c = true;
else
c = ~cons(i - 1, b, k0);
end
end
% mseq() measures the number of consonant sequences between k0 and j. If
% c is a consonant sequence and v a vowel sequence, and <..> indicates
% arbitrary presence,
% <c><v> gives 0
% <c>vc<v> gives 1
% <c>vcvc<v> gives 2
% <c>vcvcvc<v> gives 3
% ....
function n = measure(b, k0)
global j;
n = 0;
i = k0;
while true
if i > j
return
end
if ~cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
while true
while true
if i > j
return
end
if cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
n = n + 1;
while true
if i > j
return
end
if ~cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
end
% vowelinstem() is TRUE <=> k0,...j contains a vowel
function vis = vowelinstem(b, k0)
global j;
for i = k0:j,
if ~cons(i, b, k0)
vis = true;
return
end
end
vis = false;
%doublec(i) is TRUE <=> i,(i-1) contain a double consonant.
function dc = doublec(i, b, k0)
if i < k0+1
dc = false;
return
end
if b(i) ~= b(i-1)
dc = false;
return
end
dc = cons(i, b, k0);
% cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant
% and also if the second c is not w,x or y. this is used when trying to
% restore an e at the end of a short word. e.g.
%
% cav(e), lov(e), hop(e), crim(e), but
% snow, box, tray.
function c1 = cvc(i, b, k0)
if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0))
c1 = false;
else
if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y')
c1 = false;
return
end
c1 = true;
end
% ends(s) is TRUE <=> k0,...k ends with the string s.
function s = ends(str, b, k)
global j;
if (str(length(str)) ~= b(k))
s = false;
return
end % tiny speed-up
if (length(str) > k)
s = false;
return
end
if strcmp(b(k-length(str)+1:k), str)
s = true;
j = k - length(str);
return
else
s = false;
end
% setto(s) sets (j+1),...k to the characters in the string s, readjusting
% k accordingly.
function so = setto(s, b, k)
global j;
for i = j+1:(j+length(s))
b(i) = s(i-j);
end
if k > j+length(s)
b((j+length(s)+1):k) = '';
end
k = length(b);
so = {b, k};
% rs(s) is used further down.
% [Note: possible null/value for r if rs is called]
function r = rs(str, b, k, k0)
r = {b, k};
if measure(b, k0) > 0
r = setto(str, b, k);
end
% step1ab() gets rid of plurals and -ed or -ing. e.g.
% caresses -> caress
% ponies -> poni
% ties -> ti
% caress -> caress
% cats -> cat
% feed -> feed
% agreed -> agree
% disabled -> disable
% matting -> mat
% mating -> mate
% meeting -> meet
% milling -> mill
% messing -> mess
% meetings -> meet
function s1ab = step1ab(b, k, k0)
global j;
if b(k) == 's'
if ends('sses', b, k)
k = k-2;
elseif ends('ies', b, k)
retVal = setto('i', b, k);
b = retVal{1};
k = retVal{2};
elseif (b(k-1) ~= 's')
k = k-1;
end
end
if ends('eed', b, k)
if measure(b, k0) > 0;
k = k-1;
end
elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0)
k = j;
retVal = {b, k};
if ends('at', b, k)
retVal = setto('ate', b(k0:k), k);
elseif ends('bl', b, k)
retVal = setto('ble', b(k0:k), k);
elseif ends('iz', b, k)
retVal = setto('ize', b(k0:k), k);
elseif doublec(k, b, k0)
retVal = {b, k-1};
if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ...
b(retVal{2}) == 'z'
retVal = {retVal{1}, retVal{2}+1};
end
elseif measure(b, k0) == 1 && cvc(k, b, k0)
retVal = setto('e', b(k0:k), k);
end
k = retVal{2};
b = retVal{1}(k0:k);
end
j = k;
s1ab = {b(k0:k), k};
% step1c() turns terminal y to i when there is another vowel in the stem.
function s1c = step1c(b, k, k0)
global j;
if ends('y', b, k) && vowelinstem(b, k0)
b(k) = 'i';
end
j = k;
s1c = {b, k};
% step2() maps double suffices to single ones. so -ization ( = -ize plus
% -ation) maps to -ize etc. note that the string before the suffix must give
% m() > 0.
function s2 = step2(b, k, k0)
global j;
s2 = {b, k};
switch b(k-1)
case {'a'}
if ends('ational', b, k) s2 = rs('ate', b, k, k0);
elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end;
case {'c'}
if ends('enci', b, k) s2 = rs('ence', b, k, k0);
elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end;
case {'e'}
if ends('izer', b, k) s2 = rs('ize', b, k, k0); end;
case {'l'}
if ends('bli', b, k) s2 = rs('ble', b, k, k0);
elseif ends('alli', b, k) s2 = rs('al', b, k, k0);
elseif ends('entli', b, k) s2 = rs('ent', b, k, k0);
elseif ends('eli', b, k) s2 = rs('e', b, k, k0);
elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end;
case {'o'}
if ends('ization', b, k) s2 = rs('ize', b, k, k0);
elseif ends('ation', b, k) s2 = rs('ate', b, k, k0);
elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end;
case {'s'}
if ends('alism', b, k) s2 = rs('al', b, k, k0);
elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0);
elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0);
elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end;
case {'t'}
if ends('aliti', b, k) s2 = rs('al', b, k, k0);
elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0);
elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end;
case {'g'}
if ends('logi', b, k) s2 = rs('log', b, k, k0); end;
end
j = s2{2};
% step3() deals with -ic-, -full, -ness etc. similar strategy to step2.
function s3 = step3(b, k, k0)
global j;
s3 = {b, k};
switch b(k)
case {'e'}
if ends('icate', b, k) s3 = rs('ic', b, k, k0);
elseif ends('ative', b, k) s3 = rs('', b, k, k0);
elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end;
case {'i'}
if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end;
case {'l'}
if ends('ical', b, k) s3 = rs('ic', b, k, k0);
elseif ends('ful', b, k) s3 = rs('', b, k, k0); end;
case {'s'}
if ends('ness', b, k) s3 = rs('', b, k, k0); end;
end
j = s3{2};
% step4() takes off -ant, -ence etc., in context <c>vcvc<v>.
function s4 = step4(b, k, k0)
global j;
switch b(k-1)
case {'a'}
if ends('al', b, k) end;
case {'c'}
if ends('ance', b, k)
elseif ends('ence', b, k) end;
case {'e'}
if ends('er', b, k) end;
case {'i'}
if ends('ic', b, k) end;
case {'l'}
if ends('able', b, k)
elseif ends('ible', b, k) end;
case {'n'}
if ends('ant', b, k)
elseif ends('ement', b, k)
elseif ends('ment', b, k)
elseif ends('ent', b, k) end;
case {'o'}
if ends('ion', b, k)
if j == 0
elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t'))
j = k;
end
elseif ends('ou', b, k) end;
case {'s'}
if ends('ism', b, k) end;
case {'t'}
if ends('ate', b, k)
elseif ends('iti', b, k) end;
case {'u'}
if ends('ous', b, k) end;
case {'v'}
if ends('ive', b, k) end;
case {'z'}
if ends('ize', b, k) end;
end
if measure(b, k0) > 1
s4 = {b(k0:j), j};
else
s4 = {b(k0:k), k};
end
% step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1.
function s5 = step5(b, k, k0)
global j;
j = k;
if b(k) == 'e'
a = measure(b, k0);
if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0))
k = k-1;
end
end
if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1)
k = k-1;
end
s5 = {b(k0:k), k};
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex6/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex4/submit.m | 17,129 | utf_8 | 917c487f37cf14037c77e3c57ad78ce1 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '4';
end
function [partNames] = validParts()
partNames = { 'Feedforward and Cost Function', ...
'Regularized Cost Function', ...
'Sigmoid Gradient', ...
'Neural Network Gradient (Backpropagation)' ...
'Regularized Gradient' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'nnCostFunction.m' }, ...
{ 'nnCostFunction.m' }, ...
{ 'sigmoidGradient.m' }, ...
{ 'nnCostFunction.m' }, ...
{ 'nnCostFunction.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
X = reshape(3 * sin(1:1:30), 3, 10);
Xm = reshape(sin(1:32), 16, 2) / 5;
ym = 1 + mod(1:16,4)';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
t = [t1(:) ; t2(:)];
if partId == 1
[J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);
out = sprintf('%0.5f ', J);
elseif partId == 2
[J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);
out = sprintf('%0.5f ', J);
elseif partId == 3
out = sprintf('%0.5f ', sigmoidGradient(X));
elseif partId == 4
[J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == 5
[J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex4/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex1/submit.m | 17,317 | utf_8 | 14dfeccc6eb749406cb5d77fabb6bf47 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '1';
end
function [partNames] = validParts()
partNames = { 'Warm up exercise ', ...
'Computing Cost (for one variable)', ...
'Gradient Descent (for one variable)', ...
'Feature Normalization', ...
'Computing Cost (for multiple variables)', ...
'Gradient Descent (for multiple variables)', ...
'Normal Equations'};
end
function srcs = sources()
% Separated by part
srcs = { { 'warmUpExercise.m' }, ...
{ 'computeCost.m' }, ...
{ 'gradientDescent.m' }, ...
{ 'featureNormalize.m' }, ...
{ 'computeCostMulti.m' }, ...
{ 'gradientDescentMulti.m' }, ...
{ 'normalEqn.m' }, ...
};
end
function out = output(partId, auxstring)
% Random Test Cases
X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
Y2 = Y1.^0.5 + Y1;
if partId == 1
out = sprintf('%0.5f ', warmUpExercise());
elseif partId == 2
out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
elseif partId == 3
out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));
elseif partId == 4
out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
elseif partId == 5
out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));
elseif partId == 6
out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));
elseif partId == 7
out = sprintf('%0.5f ', normalEqn(X2, Y2));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex1/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex2/submit.m | 17,086 | utf_8 | 7b02ce6b9daa919a9a66ef0adb401b07 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '2';
end
function [partNames] = validParts()
partNames = { 'Sigmoid Function ', ...
'Logistic Regression Cost', ...
'Logistic Regression Gradient', ...
'Predict', ...
'Regularized Logistic Regression Cost' ...
'Regularized Logistic Regression Gradient' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'sigmoid.m' }, ...
{ 'costFunction.m' }, ...
{ 'costFunction.m' }, ...
{ 'predict.m' }, ...
{ 'costFunctionReg.m' }, ...
{ 'costFunctionReg.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
if partId == 1
out = sprintf('%0.5f ', sigmoid(X));
elseif partId == 2
out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y));
elseif partId == 3
[cost, grad] = costFunction([0.25 0.5 -0.5]', X, y);
out = sprintf('%0.5f ', grad);
elseif partId == 4
out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X));
elseif partId == 5
out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1));
elseif partId == 6
[cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', grad);
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex2/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex3/submit.m | 17,041 | utf_8 | 07a62d95df0814b4ffbc6c2f4b433e22 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '3';
end
function [partNames] = validParts()
partNames = { 'Vectorized Logistic Regression ', ...
'One-vs-all classifier training', ...
'One-vs-all classifier prediction', ...
'Neural network prediction function' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'lrCostFunction.m' }, ...
{ 'oneVsAll.m' }, ...
{ 'predictOneVsAll.m' }, ...
{ 'predict.m' } };
end
function out = output(partId, auxdata)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...
1 1 ; 1 2 ; 2 1 ; 2 2 ; ...
-1 1 ; -1 2 ; -2 1 ; -2 2 ; ...
1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];
ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
if partId == 1
[J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == 2
out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));
elseif partId == 3
out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));
elseif partId == 4
out = sprintf('%0.5f ', predict(t1, t2, Xm));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex3/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex5/submit.m | 17,211 | utf_8 | 057662350ffa8db95583373185a26a6b | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '5';
end
function [partNames] = validParts()
partNames = { 'Regularized Linear Regression Cost Function', ...
'Regularized Linear Regression Gradient', ...
'Learning Curve', ...
'Polynomial Feature Mapping' ...
'Validation Curve' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'linearRegCostFunction.m' }, ...
{ 'linearRegCostFunction.m' }, ...
{ 'learningCurve.m' }, ...
{ 'polyFeatures.m' }, ...
{ 'validationCurve.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)'];
y = sin(1:3:30)';
Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)'];
yval = sin(1:10)';
if partId == 1
[J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', J);
elseif partId == 2
[J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', grad);
elseif partId == 3
[error_train, error_val] = ...
learningCurve(X, y, Xval, yval, 1);
out = sprintf('%0.5f ', [error_train(:); error_val(:)]);
elseif partId == 4
[X_poly] = polyFeatures(X(2,:)', 8);
out = sprintf('%0.5f ', X_poly);
elseif partId == 5
[lambda_vec, error_train, error_val] = ...
validationCurve(X, y, Xval, yval);
out = sprintf('%0.5f ', ...
[lambda_vec(:); error_train(:); error_val(:)]);
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex5/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | ijameslive/coursera-machine-learning-1-master | submit.m | .m | coursera-machine-learning-1-master/mlclass-ex7/submit.m | 16,958 | utf_8 | cd11307f72915c0d3b58176b66081197 | function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '7';
end
function [partNames] = validParts()
partNames = {
'Find Closest Centroids (k-Means)', ...
'Compute Centroid Means (k-Means)' ...
'PCA', ...
'Project Data (PCA)', ...
'Recover Data (PCA)' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'findClosestCentroids.m' }, ...
{ 'computeCentroids.m' }, ...
{ 'pca.m' }, ...
{ 'projectData.m' }, ...
{ 'recoverData.m' } ...
};
end
function out = output(partId, auxstring)
% Random Test Cases
X = reshape(sin(1:165), 15, 11);
Z = reshape(cos(1:121), 11, 11);
C = Z(1:5, :);
idx = (1 + mod(1:15, 3))';
if partId == 1
idx = findClosestCentroids(X, C);
out = sprintf('%0.5f ', idx(:));
elseif partId == 2
centroids = computeCentroids(X, idx, 3);
out = sprintf('%0.5f ', centroids(:));
elseif partId == 3
[U, S] = pca(X);
out = sprintf('%0.5f ', abs([U(:); S(:)]));
elseif partId == 4
X_proj = projectData(X, Z, 5);
out = sprintf('%0.5f ', X_proj(:));
elseif partId == 5
X_rec = recoverData(X(:,1:5), Z, 5);
out = sprintf('%0.5f ', X_rec(:));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-008';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github | ijameslive/coursera-machine-learning-1-master | submitWeb.m | .m | coursera-machine-learning-1-master/mlclass-ex7/submitWeb.m | 807 | utf_8 | a53188558a96eae6cd8b0e6cda4d478d | % submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github | cgtuebingen/Product-Quantization-Tree-master | ivecs_read.m | .m | Product-Quantization-Tree-master/cpu_version/matlab/ivecs_read.m | 1,361 | utf_8 | a6dcf18c53cf54bf185c73f31ed016ea | % Read a set of vectors stored in the ivec format (int + n * int)
% The function returns a set of output vector (one vector per column)
%
% Syntax:
% v = ivecs_read (filename) -> read all vectors
% v = ivecs_read (filename, n) -> read n vectors
% v = ivecs_read (filename, [a b]) -> read the vectors from a to b (indices starts from 1)
function v = ivecs_read (filename, bounds)
% open the file and count the number of descriptors
fid = fopen (filename, 'rb');
if fid == -1
error ('I/O error : Unable to open the file %s\n', filename)
end
% Read the vector size
d = fread (fid, 1, 'int');
vecsizeof = 1 * 4 + d * 4;
% Get the number of vectrors
fseek (fid, 0, 1);
a = 1;
bmax = ftell (fid) / vecsizeof;
b = bmax;
if nargin >= 2
if length (bounds) == 1
b = bounds;
elseif length (bounds) == 2
a = bounds(1);
b = bounds(2);
end
end
assert (a >= 1);
if b > bmax
b = bmax;
end
if b == 0 | b < a
v = [];
fclose (fid);
return;
end
% compute the number of vectors that are really read and go in starting positions
n = b - a + 1;
fseek (fid, (a - 1) * vecsizeof, -1);
% read n vectors
v = fread (fid, (d + 1) * n, 'int=>double');
v = reshape (v, d + 1, n);
% Check if the first column (dimension of the vectors) is correct
assert (sum (v (1, 2:end) == v(1, 1)) == n - 1);
v = v (2:end, :);
fclose (fid);
|
github | cgtuebingen/Product-Quantization-Tree-master | fvecs_read.m | .m | Product-Quantization-Tree-master/cpu_version/matlab/fvecs_read.m | 1,363 | utf_8 | 267b271a3740ad6bf22d8f14965b7c4a | % Read a set of vectors stored in the fvec format (int + n * float)
% The function returns a set of output vector (one vector per column)
%
% Syntax:
% v = fvecs_read (filename) -> read all vectors
% v = fvecs_read (filename, n) -> read n vectors
% v = fvecs_read (filename, [a b]) -> read the vectors from a to b (indices starts from 1)
function v = fvecs_read (filename, bounds)
% open the file and count the number of descriptors
fid = fopen (filename, 'rb');
if fid == -1
error ('I/O error : Unable to open the file %s\n', filename)
end
% Read the vector size
d = fread (fid, 1, 'int');
vecsizeof = 1 * 4 + d * 4;
% Get the number of vectrors
fseek (fid, 0, 1);
a = 1;
bmax = ftell (fid) / vecsizeof;
b = bmax;
if nargin >= 2
if length (bounds) == 1
b = bounds;
elseif length (bounds) == 2
a = bounds(1);
b = bounds(2);
end
end
assert (a >= 1);
if b > bmax
b = bmax;
end
if b == 0 | b < a
v = [];
fclose (fid);
return;
end
% compute the number of vectors that are really read and go in starting positions
n = b - a + 1;
fseek (fid, (a - 1) * vecsizeof, -1);
% read n vectors
v = fread (fid, (d + 1) * n, 'float=>single');
v = reshape (v, d + 1, n);
% Check if the first column (dimension of the vectors) is correct
assert (sum (v (1, 2:end) == v(1, 1)) == n - 1);
v = v (2:end, :);
fclose (fid);
|
github | claassengroup/matLeap-master | isFbcEnabled.m | .m | matLeap-master/libSBML-5.12.0-matlab/isFbcEnabled.m | 2,380 | utf_8 | 52e85daac8468f2c9bf66de5b51e04fe | function fbcEnabled = isFbcEnabled()
% Checks whether the version of libSBML has been built with
% the FBC package extension enabled
% Filename : isFbcEnabled.m
% Description : check fbc status
% Author(s) : SBML Team <[email protected]>
% Organization: EMBL-EBI, Caltech
% Created : 2011-02-08
%
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2011 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation. A copy of the license
% agreement is provided in the file named "LICENSE.txt" included with
% this software distribution and also available online as
% http://sbml.org/software/libsbml/license.html
% assume not enabled
fbcEnabled = 0;
if (isoctave() == '0')
filename = fullfile(tempdir, 'fbc.xml');
else
filename = fullfile(pwd, 'fbc.xml');
end;
writeTempFile(filename);
try
[m, e] = TranslateSBML(filename, 1, 0);
if (length(e) == 0 && isfield(m, 'fbc_version') == 1 )
fbcEnabled = 1;
end;
delete(filename);
catch
delete(filename);
return
end;
function writeTempFile(filename)
fout = fopen(filename, 'w');
fprintf(fout, '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n');
fprintf(fout, '<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" ');
fprintf(fout, 'xmlns:fbc=\"http://www.sbml.org/sbml/level3/version1/fbc/version1\" ');
fprintf(fout, 'level=\"3\" version=\"1\" fbc:required=\"false\">\n');
fprintf(fout, ' <model/>\n</sbml>\n');
fclose(fout);
|
github | claassengroup/matLeap-master | buildSBML.m | .m | matLeap-master/libSBML-5.12.0-matlab/buildSBML.m | 30,786 | utf_8 | 90b3ea6ab3341cde3685da49306e5977 | function buildSBML(varargin)
% Builds the MATLAB language interface for libSBML.
%
% This script is meant to be invoked from libSBML's MATLAB bindings
% source directory. LibSBML must already have been compiled and
% installed on your system. This script makes the following
% assumptions:
%
% * Linux and Mac systems: the compiled libSBML library must be on the
% appropriate library search paths, and/or the appropriate environment
% variables must have been set so that programs such as MATLAB can
% load the library dynamically.
%
% * Windows systems: the libSBML binaries (.dll and .lib files) and its
% dependencies (such as the XML parser library being used) must be
% located together in the same directory. This script also assumes
% that libSBML was configured to use the libxml2 XML parser library.
% (This assumption is under Windows only.)
%
% After this script is executed successfully, a second step is necessary
% to install the results. This second step is performed by the
% "installSBML" script found in the same location as this script.
%
% (File $Revision: 13171 $ of $Date:: 2011-03-04 10:30:24 +0000#$
% Filename : buildSBML.m
% Description : Build MATLAB binding.
% Author(s) : SBML Team <[email protected]>
% Organization: EMBL-EBI, Caltech
% Created : 2011-02-08
%
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2013 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation. A copy of the license
% agreement is provided in the file named "LICENSE.txt" included with
% this software distribution and also available online as
% http://sbml.org/software/libsbml/license.html
% =========================================================================
% Main loop.
% =========================================================================
[matlab_octave, bit64] = check_system();
disp(sprintf('\nConstructing the libSBML %s interface.\n', matlab_octave));
[location, writeAccess, in_installer] = check_location(matlab_octave);
if isWindows()
build_win(matlab_octave, location, writeAccess, bit64, in_installer);
elseif ismac() || isunix()
% here we allow input arguments of include and library directories
% but we only use these if we are in the source tree
if (nargin > 0 && strcmp(location, 'source'))
% we need two arguments
% one must be the full path to the include directory
% two must be the full path to the library directory
correctArguments = 0;
if (nargin == 2)
include_dir_supplied = varargin{1};
lib_dir_supplied = varargin{2};
if checkSuppliedArguments(include_dir_supplied, lib_dir_supplied)
correctArguments = 1;
end;
end;
if correctArguments == 0
message = sprintf('\n%s\n%s\n%s\n', ...
'If arguments are passed to the buildSBML script we expect 2 arguments:', ...
'1) the full path to the include directory', ...
'2) the full path to the directory containing the libSBML library');
error(message);
else
% arguments are fine - go ahead and build
build_unix(matlab_octave, location, writeAccess, bit64, ...
include_dir_supplied, lib_dir_supplied);
end;
else
build_unix(matlab_octave, location, writeAccess, bit64);
end;
else
message = sprintf('\n%s\n%s\n', ...
'Unable to determine the type of operating system in use.', ...
'Please contact [email protected] to help resolve this problem.');
error(message);
end;
disp(sprintf('\n%s%s\n', 'Successfully finished. ', ...
'If appropriate, please run "installSBML" next.'));
% =========================================================================
% Support functions.
% =========================================================================
%
%
% Is this windows
% Mac OS X 10.7 Lion returns true for a call to ispc()
% since we were using that to distinguish between windows and macs we need
% to catch this
% ------------------------------------------------------------------------
function y = isWindows()
y = 1;
if isunix()
y = 0;
return;
end;
if ismac()
y = 0;
return;
end;
if ~ispc()
message = sprintf('\n%s\n%s\n', ...
'Unable to determine the type of operating system in use.', ...
'Please contact [email protected] to help resolve this problem.');
error(message);
end;
%
% Assess our computing environment.
% -------------------------------------------------------------------------
function [matlab_octave, bit64] = check_system()
disp('* Doing preliminary checks of runtime environment ...');
if (strcmp(isoctave(), '0'))
matlab_octave = 'MATLAB';
disp(' - This appears to be MATLAB and not Octave.');
else
matlab_octave = 'Octave';
disp(' - This appears to be Octave and not MATLAB.');
end;
bit64 = 32;
if isWindows()
if strcmp(computer(), 'PCWIN64') == 1
bit64 = 64;
disp(sprintf(' - %s reports the OS is Windows 64-bit.', matlab_octave));
else
disp(sprintf(' - %s reports the OS is Windows 32-bit.', matlab_octave));
end;
elseif ismac()
if strcmp(computer(), 'MACI64') == 1
bit64 = 64;
disp(sprintf(' - %s reports the OS is 64-bit MacOS.', matlab_octave));
else
% Reading http://www.mathworks.com/help/techdoc/ref/computer.html
% it is still not clear to me what a non-64-bit MacOS will report.
% Let's not assume the only other alternative is 32-bit, since we
% actually don't care here. Let's just say "macos".
%
disp(sprintf(' - %s reports the OS is MacOS.', matlab_octave));
end;
elseif isunix()
if strcmp(computer(), 'GLNXA64') == 1
bit64 = 64;
disp(sprintf(' - %s reports the OS is 64-bit Linux.', matlab_octave));
else
disp(sprintf(' - %s reports the OS is 32-bit Linux.', matlab_octave));
end;
end;
%
% Assess our location in the file system.
% -------------------------------------------------------------------------
% Possible values returned:
% LOCATION:
% 'installed' -> installation directory
% 'source' -> libsbml source tree
%
% WRITEACCESS:
% 1 -> we can write in this directory
% 0 -> we can't write in this directory
%
function [location, writeAccess, in_installer] = check_location(matlab_octave)
disp('* Trying to establish our location ...');
% This is where things get iffy. There are a lot of possibilities, and
% we have to resort to heuristics.
%
% Linux and Mac: we look for 2 possibilities
% - installation dir ends in "libsbml/bindings/matlab"
% Detect it by looking for ../../VERSION.txt.
% Assume we're in .../share/libsbml/bindings/matlab and that our
% library is in .../lib/
%
% - source dir ends in "libsbml/src/bindings/matlab"
% Detect it by looking for ../../../VERSION.txt.
% Assume our library is in ../../
%
[remain, first] = fileparts(pwd);
if strcmpi(matlab_octave, 'matlab')
if ~strcmp(first, 'matlab')
error_incorrect_dir('matlab');
else
disp(' - We are in the libSBML subdirectory for Matlab.');
end;
else
if ~strcmp(first, 'octave')
error_incorrect_dir('octave');
else
disp(' - We are in the libSBML subdirectory for Octave.');
end;
end;
in_installer = 0;
[above_bindings, bindings] = fileparts(remain);
if exist(fullfile(above_bindings, 'VERSION.txt'))
disp(' - We appear to be in the installation target directory.');
in_installer = 1;
if isWindows()
location = above_bindings;
else
location = 'installed';
end;
else
[libsbml_root, src] = fileparts(above_bindings);
if exist(fullfile(libsbml_root, 'VERSION.txt'))
disp(' - We appear to be in the libSBML source tree.');
if isWindows()
location = libsbml_root;
else
location = 'source';
end;
else
% We don't know where we are.
if strcmpi(matlab_octave, 'MATLAB')
error_incorrect_dir('matlab');
else
error_incorrect_dir('octave');
end;
end;
end;
% Test that it looks like we have the expected pieces in this directory.
% We don't want to assume particular paths, because we might be
% getting run from the libSBML source tree or the installed copy of
% the matlab bindings sources. So, we test for just a couple of
% things: the tail of the name of the directory in which this file is
% located (should be either "matlab" or "octave") and the presence of
% another file, "OutputSBML.c", which became part of libsbml at the
% same time this new build scheme was introduced.
our_name = sprintf('%s.m', mfilename);
other_name = 'OutputSBML.cpp';
if ~exist(fullfile(pwd, our_name), 'file') ...
|| ~exist(fullfile(pwd, other_name), 'file')
error_incorrect_dir('matlab');
end;
% Check whether we have write access to this directory.
fid = fopen('temp.txt', 'w');
writeAccess = 1;
if fid == -1
disp(' - We do not have write access here -- will write elsewhere.');
writeAccess = 0;
else
disp(' - We have write access here! That makes us happy.');
fclose(fid);
delete('temp.txt');
end;
%
% Find include and library dirs (Linux & Mac case).
% -------------------------------------------------------------------------
% Return values:
% INCLUDE -> the full path to the include directory
% LIB -> the full path to the libsbml library directory
%
function [include, lib] = find_unix_dirs(location, bit64)
disp('* Locating libSBML library and include files ...');
% The 'location' argument guides us:
% 'installed' -> installation directory
% look for libsbml.so or libsbml.dylib in ../../../lib{64}/
% 'source' -> libsbml source tree
% look for libsbml.so or libsbml.dylib in ../../.libs/
if ismac()
libname = 'libsbml.dylib';
else
libname = 'libsbml.so';
end;
if strcmpi(location, 'source')
[parent, here] = fileparts(pwd); % ..
[parent, here] = fileparts(parent); % ..
lib = fullfile(parent, '.libs');
libfile = fullfile(lib, libname);
if exist(libfile)
disp(sprintf(' - Found %s', libfile));
else
lib = 'unfound';
end;
include = parent;
if exist(include)
disp(sprintf(' - Root of includes is %s', include));
else
error_incorrect_dir('matlab');
end;
else
% location is 'installed'
[parent, here] = fileparts(pwd); % ..
[parent, here] = fileparts(parent); % ..
[parent, here] = fileparts(parent); % ..
lib = fullfile(parent, 'lib');
libfile = fullfile(lib, libname);
if exist(libfile)
disp(sprintf(' - Found %s', libfile));
else
if bit64 == 64
% Try one more common alternative.
lib = fullfile(parent, 'lib64');
libfile = fullfile(lib, libname);
if exist(libfile)
disp(sprintf(' - Found %s', libfile));
else
lib = 'unfound';
end;
end;
end;
% In the installed target directory, include will be something
% like /usr/local/include
%
include = fullfile(parent, 'include');
if exist(include)
disp(sprintf(' - Root of includes is %s', include));
else
error_incorrect_dir('matlab');
end;
end;
%
% we on occasion allow the user to supply arguments for the directories
% Check include and library dirs (Linux & Mac case) supplied exist
% -------------------------------------------------------------------------
function y = checkSuppliedArguments(include_supplied, lib_supplied)
disp('* Checking for libSBML library and include files ...');
% assume we find them
y = 1;
% check the include directory supplied exists
if exist(include_supplied)
disp(sprintf(' - Root of includes found at %s', include_supplied));
else
disp(sprintf(' - Root of includes NOT found at %s', include_supplied));
y = 0;
end;
% check that the correct library is found
if ismac()
libname = 'libsbml.dylib';
else
libname = 'libsbml.so';
end;
libfile = fullfile(lib_supplied, libname);
if exist(libfile)
disp(sprintf(' - Found %s', libfile));
else
disp(sprintf(' - NOT found %s', libfile));
y = 0;
end;
%
% Drive the build process (Windows version).
% -------------------------------------------------------------------------
function build_win(matlab_octave, root, writeAccess, bit64, in_installer)
disp('Phase 2: tests for libraries and other dependencies ...');
[include_dir, lib] = find_win_dirs(root, bit64, in_installer);
% check that the libraries can all be found
found = 1;
for i = 1:length(lib)
if (exist(lib{i}) ~= 0)
disp(sprintf('%s found', lib{i}));
else
disp(sprintf('%s not found', lib{i}));
found = 0;
end;
end;
if (found == 0)
error (sprintf('Not all dependencies could be found\n%s%s', ...
'expected the dependencies to be in ', fileparts(lib{1})));
else
disp(' - All dependencies found. Good.');
end;
% if we do not have write access need to find somewhere else to build
if (writeAccess == 0)% must be 0; 1 is for testing
% create a new dir in the users path
this_dir = pwd;
if (matlab_octave == 'MATLAB')
user_dir = userpath;
user_dir = user_dir(1:length(user_dir)-1);
else
% This is Octave. Octave doesn't have 'userpath'.
user_dir = tempdir;
end;
disp(sprintf(' - Copying library files to %s ...', user_dir));
if (copyLibraries(this_dir, user_dir, lib) == 1)
disp(' - Copying of library files successful.');
else
error('Cannot copy library files on this system');
end;
disp(sprintf(' - Copying MATLAB binding files to %s ...', user_dir));
if (copyMatlabDir(this_dir, user_dir) == 1)
disp('- Copying of MATLAB binding files successful');
else
error('Cannot copy matlab binding files on this system');
end;
else
this_dir = pwd;
user_dir = pwd;
% copy the library files to here
disp(sprintf(' - Copying library files to %s ...', user_dir));
if (copyLibraries(this_dir, user_dir, lib) == 1)
disp(' - Copying of library files successful');
else
error('Cannot copy library files on this system');
end;
end;
% build the files
compile_mex(include_dir, lib{1}, matlab_octave);
%
% Find include and library dirs (windows case).
% -------------------------------------------------------------------------
% Return values:
% INCLUDE -> the full path to the include directory
% LIB -> an array of the libsbml dependency libraries
%
function [include, lib] = find_win_dirs(root, bit64, in_installer)
disp('* Locating libSBML library and include files ...');
% in the src tree we expect all lib dlls to be in root/win/bin
% and the include dir to be root/src
% in the installer the lib will be in root/win32/lib
% the dll will be in root/win32/bin
% and the include dir to be root/win32/include
% and for 64 bits the win32 will be win64
if (in_installer == 0)
bin_dir = [root, filesep, 'win', filesep, 'bin'];
lib_dir = [root, filesep, 'win', filesep, 'bin'];
include = [root, filesep, 'src'];
else
if (bit64 == 32)
bin_dir = [root, filesep, 'win32', filesep, 'bin'];
lib_dir = [root, filesep, 'win32', filesep, 'lib'];
include = [root, filesep, 'win32', filesep, 'include'];
else
bin_dir = [root, filesep, 'win64', filesep, 'bin'];
lib_dir = [root, filesep, 'win64', filesep, 'lib'];
include = [root, filesep, 'win64', filesep, 'include'];
end;
end;
disp(sprintf(' - Checking for the existence of the %s directory ...\n', bin_dir));
% and are the libraries in this directory
if ((exist(bin_dir, 'dir') ~= 7) || (exist([bin_dir, filesep, 'libsbml.dll']) == 0))
disp(sprintf('%s directory could not be found\n\n%s\n%s %s', bin_dir, ...
'The build process assumes that the libsbml binaries', ...
'exist at', bin_dir));
message = sprintf('\n%s\n%s', ...
'if they are in another directory please enter the ', ...
'full path to reach the directory from this directory: ');
new_bin_dir = input(message, 's');
if (exist(new_bin_dir, 'dir') == 0)
error('libraries could not be found');
else
bin_dir = new_bin_dir;
if (in_installer == 0)
lib_dir = bin_dir;
end;
end;
end;
if (~strcmp(bin_dir, lib_dir))
disp(sprintf(' - Checking for the existence of the %s directory ...\n', lib_dir));
if (exist(lib_dir, 'dir') ~= 7)
disp(sprintf('%s directory could not be found\n\n%s\n%s %s', lib_dir, ...
'The build process assumes that the libsbml binaries', ...
'exist at', lib_dir));
message = sprintf('\n%s\n%s', ...
'if they are in another directory please enter the ', ...
'full path to reach the directory from this directory: ');
new_lib_dir = input(message, 's');
if (exist(new_lib_dir, 'dir') == 0)
error('libraries could not be found');
else
lib_dir = new_lib_dir;
end;
end;
end;
% check that the include directory exists
disp(sprintf(' - Checking for the existence of the %s directory ...\n', include));
if (exist(include, 'dir') ~= 7)
disp(sprintf('%s directory could not be found\n\n%s\n%s %s', include, ...
'The build process assumes that the libsbml include files', ...
'exist at', include));
message = sprintf('\n%s\n%s', ...
'if they are in another directory please enter the ', ...
'full path to reach the directory from this directory: ');
new_inc_dir = input(message, 's');
if (exist(new_inc_dir, 'dir') == 0)
error('include files could not be found');
else
include = new_inc_dir;
end;
end;
% create the array of library files
if (bit64 == 32)
if (in_installer == 0)
lib{1} = [bin_dir, filesep, 'libsbml.lib'];
lib{2} = [bin_dir, filesep, 'libsbml.dll'];
lib{3} = [bin_dir, filesep, 'libxml2.lib'];
lib{4} = [bin_dir, filesep, 'libxml2.dll'];
lib{5} = [bin_dir, filesep, 'iconv.lib'];
lib{6} = [bin_dir, filesep, 'iconv.dll'];
lib{7} = [bin_dir, filesep, 'bzip2.lib'];
lib{8} = [bin_dir, filesep, 'bzip2.dll'];
lib{9} = [bin_dir, filesep, 'zdll.lib'];
lib{10} = [bin_dir, filesep, 'zlib1.dll'];
else
lib{1} = [lib_dir, filesep, 'libsbml.lib'];
lib{2} = [bin_dir, filesep, 'libsbml.dll'];
lib{3} = [lib_dir, filesep, 'libxml2.lib'];
lib{4} = [bin_dir, filesep, 'libxml2.dll'];
lib{5} = [lib_dir, filesep, 'iconv.lib'];
lib{6} = [bin_dir, filesep, 'iconv.dll'];
lib{7} = [lib_dir, filesep, 'bzip2.lib'];
lib{8} = [bin_dir, filesep, 'bzip2.dll'];
lib{9} = [lib_dir, filesep, 'zdll.lib'];
lib{10} = [bin_dir, filesep, 'zlib1.dll'];
end;
else
if (in_installer == 0)
lib{1} = [bin_dir, filesep, 'libsbml.lib'];
lib{2} = [bin_dir, filesep, 'libsbml.dll'];
lib{3} = [bin_dir, filesep, 'libxml2.lib'];
lib{4} = [bin_dir, filesep, 'libxml2.dll'];
lib{5} = [bin_dir, filesep, 'libiconv.lib'];
lib{6} = [bin_dir, filesep, 'libiconv.dll'];
lib{7} = [bin_dir, filesep, 'bzip2.lib'];
lib{8} = [bin_dir, filesep, 'libbz2.dll'];
lib{9} = [bin_dir, filesep, 'zdll.lib'];
lib{10} = [bin_dir, filesep, 'zlib1.dll'];
else
lib{1} = [lib_dir, filesep, 'libsbml.lib'];
lib{2} = [bin_dir, filesep, 'libsbml.dll'];
lib{3} = [lib_dir, filesep, 'libxml2.lib'];
lib{4} = [bin_dir, filesep, 'libxml2.dll'];
lib{5} = [lib_dir, filesep, 'libiconv.lib'];
lib{6} = [bin_dir, filesep, 'libiconv.dll'];
lib{7} = [lib_dir, filesep, 'bzip2.lib'];
lib{8} = [bin_dir, filesep, 'libbz2.dll'];
lib{9} = [lib_dir, filesep, 'zdll.lib'];
lib{10} = [bin_dir, filesep, 'zlib1.dll'];
end;
end;
%
% Drive the build process (Mac and Linux version).
% -------------------------------------------------------------------------
function build_unix(varargin)
matlab_octave = varargin{1};
location = varargin{2};
writeAccess = varargin{3};
bit64 = varargin{4};
if (nargin == 4)
[include, lib] = find_unix_dirs(location, bit64);
else
include = varargin{5};
lib = varargin{6};
end;
if writeAccess == 1
% We can write to the current directory. Our job is easy-peasy.
%
compile_mex(include, lib, matlab_octave);
else
% We don't have write access to this directory. Copy the files
% somewhere else, relocate to there, and then try building.
%
working_dir = find_working_dir(matlab_octave);
current_dir = pwd;
copy_matlab_dir(current_dir, working_dir);
cd(working_dir);
compile_mex(include, lib, matlab_octave);
cd(current_dir);
end;
%
% Run mex/mkoctfile.
% -------------------------------------------------------------------------
function compile_mex(include_dir, library_dir, matlab_octave)
disp(sprintf('* Creating mex files in %s', pwd));
% list the possible opts files to be tried
optsfiles = {'', './mexopts-osx109.sh', './mexopts-osx108.sh', './mexopts-lion.sh', './mexopts-xcode43.sh', './mexopts-xcode45.sh', './mexopts-R2009-R2010.sh', './mexopts-R2008.sh', './mexopts-R2007.sh'};
success = 0;
n = 1;
if strcmpi(matlab_octave, 'matlab')
while(~success && n < length(optsfiles))
try
if ~isempty(optsfiles{n})
disp(sprintf('* Trying to compile with mexopts file: %s', optsfiles{n}));
end;
success = do_compile_mex(include_dir, library_dir, matlab_octave, optsfiles{n});
catch err
disp(' ==> The last attempt to build the Matlab bindings failed. We will try again with a different mexopts file');
end;
n = n + 1;
end;
else
success = do_compile_mex(include_dir, library_dir, matlab_octave, optsfiles{n});
end;
if ~success
error('Build failed');
end;
function success = do_compile_mex(include_dir, library_dir, matlab_octave, altoptions)
inc_arg = ['-I', include_dir];
inc_arg2 = ['-I', library_dir];
lib_arg = ['-L', library_dir];
added_args = [' '];
if ismac() || isunix()
added_args = ['-lsbml'];
end;
% The messy file handle stuff is because this seems to be the best way to
% be able to pass arguments to the feval function.
if strcmpi(matlab_octave, 'matlab')
% on windows the command needs to be different
if isWindows()
fhandle = @mex;
disp(' - Building TranslateSBML ...');
feval(fhandle, 'TranslateSBML.cpp', inc_arg, inc_arg2, library_dir, '-DWIN32');
disp(' - Building OutputSBML ...');
feval(fhandle, 'OutputSBML.cpp', inc_arg, inc_arg2, library_dir, '-DWIN32');
else
fhandle = @mex;
disp(' - Building TranslateSBML ...');
if ~isempty(altoptions)
feval(fhandle, 'TranslateSBML.cpp', '-f', altoptions, inc_arg, inc_arg2, lib_arg, added_args);
else
feval(fhandle, 'TranslateSBML.cpp', inc_arg, inc_arg2, lib_arg, added_args);
end;
disp(' - Building OutputSBML ...');
if ~isempty(altoptions)
feval(fhandle, 'OutputSBML.cpp', '-f', altoptions, inc_arg, inc_arg2, lib_arg, added_args);
else
feval(fhandle, 'OutputSBML.cpp', inc_arg, inc_arg2, lib_arg, added_args);
end;
end;
else
if isWindows()
fhandle = @mkoctfile;
disp(' - Building TranslateSBML ...');
feval(fhandle, '--mex', 'TranslateSBML.cpp', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
'-lbz2', '-lz', library_dir);
disp(' - Building OutputSBML ...');
feval(fhandle, '--mex', 'OutputSBML.cpp', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
'-lbz2', '-lz', library_dir);
else
fhandle = @mkoctfile;
disp(' - Building TranslateSBML ...');
feval(fhandle, '--mex', 'TranslateSBML.cpp', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
'-lbz2', '-lz', lib_arg, added_args);
disp(' - Building OutputSBML ...');
feval(fhandle, '--mex', 'OutputSBML.cpp', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
'-lbz2', '-lz', lib_arg, added_args);
end;
% mkoctfile --mex TranslateSBML.cpp -DUSE_OCTAVE inc_arg inc_arg2 -lbz2 -lz lib_arg;
end;
transFile = strcat('TranslateSBML.', mexext());
outFile = strcat('OutputSBML.', mexext());
if ~exist(transFile) || ~exist(outFile)
success = 0;
else
success = 1;
end;
%
% Find a directory where we can copy our files (Linux & Mac version).
%
% -------------------------------------------------------------------------
function working_dir = find_working_dir(matlab_octave)
if strcmpi(matlab_octave, 'matlab')
user_dir = userpath;
user_dir = user_dir(1:length(user_dir)-1);
else
% This is Octave. Octave doesn't have 'userpath'.
user_dir = tempdir;
end;
working_dir = fullfile(user_dir, 'libsbml');
if ~exist(working_dir, 'dir')
[success, msg, msgid] = mkdir(working_dir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
end;
%
% Copy the matlab binding directory, with tests.
%
% This also creates the necessary directories and subdirectories.
% -------------------------------------------------------------------------
function copy_matlab_dir(orig_dir, working_dir)
disp(sprintf(' - Copying files to %s', working_dir));
% Copy files from src/bindings/matlab.
[success, msg, msgid] = copyfile('TranslateSBML.cpp', working_dir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
[success, msg, msgid] = copyfile('OutputSBML.cpp', working_dir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
[success, msg, msgid] = copyfile('*.m', working_dir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
[success, msg, msgid] = copyfile('*.xml', working_dir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
% Copy files from src/bindings/matlab/test.
test_subdir = fullfile(working_dir, 'test');
if ~exist(test_subdir, 'dir')
[success, msg, msgid] = mkdir(test_subdir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
end;
cd 'test';
[success, msg, msgid] = copyfile('*.m', test_subdir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
% Copy files from src/bindings/matlab/test/test-data/.
test_data_subdir = fullfile(test_subdir, 'test-data');
if ~exist(test_data_subdir, 'dir')
[success, msg, msgid] = mkdir(test_data_subdir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
end;
cd 'test-data';
[success, msg, msgid] = copyfile('*.xml', test_data_subdir);
if ~success
error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
end;
%
% Print error about being in the wrong location.
% -------------------------------------------------------------------------
function error_incorrect_dir(expected)
message = sprintf('\n%s\n%s%s%s\n%s\n%s%s%s\n%s\n', ...
'This script needs to be invoked from the libSBML subdirectory ', ...
'ending in "', expected, '". However, it is being invoked', ...
'from the directory', ' "', pwd, '"', ...
'instead. Please change your working directory and re-run this script.');
error(message);
%
% Copy library files to the given directory on windows
% -------------------------------------------------------------------------
function copied = copyLibraries(orig_dir, target_dir, lib)
copied = 0;
cd (target_dir);
% if we moving to another location create a libsbml directory
% if we are staying in src/matlab/bindings copy here
if (~strcmp(orig_dir, target_dir))
if (exist('libsbml', 'dir') == 0)
mkdir('libsbml');
end;
cd libsbml;
end;
new_dir = pwd;
% copy the necessary files
for i = 1:length(lib)
copyfile(lib{i}, new_dir);
end;
cd(orig_dir);
copied = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% creates a copy of the matlab binding directory with tests
function copied = copyMatlabDir(orig_dir, target_dir)
copied = 0;
cd (target_dir);
% create libsbml dir
if (exist('libsbml', 'dir') == 0)
mkdir('libsbml');
end;
cd libsbml;
new_dir = pwd;
%copy files to libsbml
cd(orig_dir);
copyfile('TranslateSBML.cpp', new_dir);
copyfile('OutputSBML.cpp', new_dir);
copyfile('*.m', new_dir);
copyfile('*.xml', new_dir);
cd(new_dir);
% delete ('buildLibSBML.m');
% create test dir
testdir = fullfile(pwd, 'test');
if (exist(testdir, 'dir') == 0)
mkdir('test');
end;
cd('test');
new_dir = pwd;
%copy test files
cd(orig_dir);
cd('test');
copyfile('*.m', new_dir);
% create test-data dir
cd(new_dir);
testdir = fullfile(pwd, 'test-data');
if (exist(testdir, 'dir') == 0)
mkdir('test-data');
end;
cd('test-data');
new_dir = pwd;
%copy test-data files
cd(orig_dir);
cd ('test');
cd ('test-data');
copyfile('*.xml', new_dir);
%navigate to new libsbml directory
cd(new_dir);
cd ..;
cd ..;
% put in some tests here
copied = 1;
% =========================================================================
% The end.
%
% Please leave the following for [X]Emacs users:
% Local Variables:
% matlab-indent-level: 2
% fill-column: 72
% End:
% =========================================================================
|
github | claassengroup/matLeap-master | CheckAndConvert.m | .m | matLeap-master/libSBML-5.12.0-matlab/CheckAndConvert.m | 13,028 | utf_8 | 00513eb63c558601962fb1952bb6ae86 | function Formula = CheckAndConvert(Input)
% converts from MathML in-fix to MATLAB functions
% Filename : CheckAndConvert.m
% Description : converts from MathML in-fix to MATLAB functions
% Author(s) : SBML Team <[email protected]>
% Organization: University of Hertfordshire STRC
% Created : 2004-12-13
%
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2013 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation. A copy of the license agreement is provided
% in the file named "LICENSE.txt" included with this software distribution
% and also available online as http://sbml.org/software/libsbml/license.html
%
% The original code contained here was initially developed by:
%
% Sarah Keating
% Science and Technology Research Centre
% University of Hertfordshire
% Hatfield, AL10 9AB
% United Kingdom
%
% http://www.sbml.org
% mailto:[email protected]
%
% Contributor(s):
Formula = strrep(Input, 'arccosh', 'acosh');
Formula = strrep(Formula, 'arccot', 'acot');
Formula = strrep(Formula, 'arccoth', 'acoth');
Formula = strrep(Formula, 'arccsc', 'acsc');
Formula = strrep(Formula, 'arccsch', 'acsch');
Formula = strrep(Formula, 'arcsec', 'asec');
Formula = strrep(Formula, 'arcsech', 'asech');
Formula = strrep(Formula, 'arcsinh', 'asinh');
Formula = strrep(Formula, 'arctanh', 'atanh');
Formula = strrep(Formula, 'exponentiale', 'exp(1)');
Formula = strrep(Formula, 'geq', 'ge');
Formula = strrep(Formula, 'leq', 'le');
Formula = strrep(Formula, 'neq', 'ne');
Formula = strrep(Formula, 'pow', 'power');
% any logical expressions can only have two arguments
Formula = SortLogicals(Formula);
% log(2,x) must become log2(x)
Formula = strrep(Formula, 'log(2,', 'log2(');
% root(n,x) must become nthroot(x,n)
Index = strfind(Formula, 'root(');
for i = 1:length(Index)
% create a subformula root(n,x)
SubFormula = '';
j = 1;
nFunctions=0; %number of functions in expression
closedFunctions=0; %number of closed functions
while(nFunctions==0 || nFunctions~=closedFunctions)
SubFormula(j) = Formula(Index(i)+j-1);
if(strcmp(SubFormula(j),')'))
closedFunctions=closedFunctions+1;
end;
if(strcmp(SubFormula(j),'('))
nFunctions=nFunctions+1;
end;
j = j+1;
end;
j = 6;
n = '';
while(~strcmp(SubFormula(j), ','))
n = strcat(n, SubFormula(j));
j = j+1;
end;
j = j+1;
x = SubFormula(j:length(SubFormula)-1);
ReplaceFormula = strcat('nthroot(', x, ',', n, ')');
Formula = strrep(Formula, SubFormula, ReplaceFormula);
Index = strfind(Formula, 'root(');
end;
% log(n,x) must become (log(x)/log(n))
% but log(x) must be left alone
LogTypes = IsItLogBase(Formula);
Index = strfind(Formula, 'log(');
for i = 1:length(Index)
if (LogTypes(i) == 1)
% create a subformula log(n,x)
SubFormula = '';
j = 1;
while(~strcmp(Formula(Index(i)+j-1), ')'))
SubFormula(j) = Formula(Index(i)+j-1);
j = j+1;
end;
SubFormula = strcat(SubFormula, ')');
j = 5;
n = '';
while(~strcmp(SubFormula(j), ','))
n = strcat(n, SubFormula(j));
j = j+1;
end;
j = j+1;
x = '';
while(~strcmp(SubFormula(j), ')'))
x = strcat(x, SubFormula(j));
j = j+1;
end;
ReplaceFormula = sprintf('(log(%s)/log(%s))', x, n);
Formula = strrep(Formula, SubFormula, ReplaceFormula);
Index = Index + 7;
end;
end;
function y = IsItLogBase(Formula)
% returns an array of 0/1 indicating whether each occurence of log is
% a log(n,x) or a log(x)
% e.g. Formula = 'log(2,3) + log(6)'
% IsItLogBase returns y = [1,0]
y = 0;
% find log
LogIndex = strfind(Formula, 'log(');
if (isempty(LogIndex))
return;
else
OpenBracket = strfind(Formula, '(');
Comma = strfind(Formula, ',');
CloseBracket = strfind(Formula, ')');
for i = 1:length(LogIndex)
if (isempty(Comma))
% no commas so no logbase formulas
y(i) = 0;
else
% find the opening bracket
Open = find(ismember(OpenBracket, LogIndex(i)+3) == 1);
% find closing bracket
Close = find(CloseBracket > LogIndex(i)+3, 1);
% is there a comma between
Greater = find(Comma > OpenBracket(Open));
Less = find(Comma < CloseBracket(Close));
if (isempty(Greater) || isempty(Less))
y(i) = 0;
else
Equal = find(Greater == Less);
if (isempty(Equal))
y(i) = 0;
else
y(i) = 1;
end;
end;
end;
end;
end;
function Formula = CorrectFormula(OriginalFormula, LogicalExpression)
% CorrectFormula takes an OriginalFormula (as a char array)
% and a Logical Expression (as a char array with following '(')
% and returns the formula written so that the logical expression only takes 2 arguments
%
% *************************************************************************************
%
% EXAMPLE: y = CorrectFormula('and(A,B,C)', 'and(')
%
% y = 'and(and(A,B), C)'
%
% find all opening brackets, closing brackets and commas contained
% within the original formula
OpeningBracketIndex = find((ismember(OriginalFormula, '(')) == 1);
ClosingBracketIndex = find((ismember(OriginalFormula, ')')) == 1);
CommaIndex = find((ismember(OriginalFormula, ',')) == 1);
% check that tha number of brackets matches
if (length(OpeningBracketIndex) ~= length(ClosingBracketIndex))
error('Bracket mismatch');
end;
% find the commas that are between the arguments of the logical expression
% not those that may be part of the argument
% in the OpeningBracketIndex the first element refers to the opening
% bracket of the expression and the last element of ClosingBracketIndex
% refers to the the closing bracket of the expression
% commas between other pairs of brackets do not need to be considered
% e.g. 'and(gt(d,e),lt(2,e),gt(f,d))'
% | |
% relevant commas
for i = 1:length(CommaIndex)
for j = 2:length(OpeningBracketIndex)
if ((CommaIndex(i) > OpeningBracketIndex(j)) && (CommaIndex(i) < ClosingBracketIndex(j-1)))
CommaIndex(i) = 0;
end;
end;
end;
NonZeros = find(CommaIndex ~= 0);
% if there is only one relevant comma
% implies only two arguments
% MATLAB can deal with the OriginalFormula
if (length(NonZeros) == 1)
Formula = OriginalFormula;
return;
end;
% get elements that represent the arguments of the logical expression
% as an array of character arrays
% e.g. first element is between opening barcket and first relevant comma
% next elements are between relevant commas
% last element is between last relevant comma and closing bracket
j = OpeningBracketIndex(1);
ElementNumber = 1;
for i = 1:length(NonZeros)
element = '';
j = j+1;
while (j <= CommaIndex(NonZeros(i)) - 1)
element = strcat(element, OriginalFormula(j));
j = j + 1;
end;
Elements{ElementNumber} = element;
ElementNumber = ElementNumber + 1;
end;
element = '';
j = j+1;
while (j < ClosingBracketIndex(length(ClosingBracketIndex)) - 1)
element = strcat(element, OriginalFormula(j));
j = j + 1;
end;
Elements{ElementNumber} = element;
% iteratively replace the first two arguments with the logical expression applied to
% the first two arguments
% e.g. OriginalFormula = 'and(a,b,c,d)'
% becomes 'and(and(a,b),c,d)'
% which becomes 'and(and(and(a,b),c),d)'
Formula = OriginalFormula;
if (length(Elements) > 2)
for i = 2:length(Elements)-1
Find = strcat(Elements{i-1}, ',', Elements{i});
Replace = strcat(LogicalExpression, Find, ')');
Formula = strrep(Formula, Find, Replace);
Elements{i} = Replace;
end;
end;
function Arguments = CheckLogical(Formula, LogicalExpression)
% CheckLogical takes a Formula (as a character array)
% and a LogicalExpression (as a char array)
% and returns an array of character strings
% representing the application of the logical expression within the formula
%
% NOTE the logical expression is followed by an '(' to prevent confusion
% with other character strings within the formula
%
% ******************************************************************
% EXAMPLE: y = CheckLogical('piecewise(and(A,B,C), 0.2, 1)' , 'and(')
%
% y = 'and(A,B,C)'
%
% EXAMPLE: y = CheckLogical('or(and(A,B), and(A,B,C))', 'and(')
%
% y = 'and(A,B)' 'and(A,B,C)'
% find the starting indices of all occurences of the logical expression
Start = strfind(Formula, LogicalExpression);
% if not found; no arguments - return
if (isempty(Start))
Arguments = {};
return;
end;
for j = 1:length(Start) % each occurence of the logical expression
Stop = 0;
flag = 0;
i = Start(j);
output = '';
for i = Start(j):Start(j)+length(LogicalExpression)
output = strcat(output, Formula(i));
end;
i = i + 1;
while ((Stop == 0) && (i <= length(Formula)))
c = Formula(i);
if (strcmp(c, '('))
flag = flag + 1;
output = strcat(output, c);
elseif (strcmp(c, ')'))
if (flag > 0)
output = strcat(output, c);
flag = flag - 1;
else
output = strcat(output, c);
Stop = 1;
end;
else
output = strcat(output, c);
end;
i = i + 1;
end;
Arguments{j} = output;
end;
function y = SortLogicals(Formula)
% SortLogicals takes a formula as a char array
% and returns the formula with and logical expressions applied to only two arguments
Formula = LoseWhiteSpace(Formula);
Find = CheckLogical(Formula, 'and(');
for i = 1:length(Find)
Replace = CorrectFormula(Find{i}, 'and(');
Formula = strrep(Formula, Find{i}, Replace);
end;
Find = CheckLogical(Formula, 'xor(');
for i = 1:length(Find)
Replace = CorrectFormula(Find{i}, 'xor(');
Formula = strrep(Formula, Find{i}, Replace);
end;
Find = CheckLogical(Formula, 'or(');
for i = 1:length(Find)
Replace = CorrectFormula(Find{i}, 'or(');
Formula = strrep(Formula, Find{i}, Replace);
end;
y = Formula;
%**********************************************************************
% LoseWhiteSpace(charArray) takes an array of characters
% and returns the array with any white space removed
%
%**********************************************************************
function y = LoseWhiteSpace(charArray)
% LoseWhiteSpace(charArray) takes an array of characters
% and returns the array with any white space removed
%
%----------------------------------------------------------------
% EXAMPLE:
% y = LoseWhiteSpace(' exa mp le')
% y = 'example'
%
%------------------------------------------------------------
% check input is an array of characters
if (~ischar(charArray))
error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters');
end;
%-------------------------------------------------------------
% get the length of the array
NoChars = length(charArray);
%-------------------------------------------------------------
% create an array that indicates whether the elements of charArray are
% spaces
% e.g. WSpace = isspace(' v b') = [1, 1, 0, 1, 0]
% and determine how many
WSpace = isspace(charArray);
NoSpaces = sum(WSpace);
%-----------------------------------------------------------
% rewrite the array to leaving out any spaces
% remove any numbers from the array of symbols
if (NoSpaces > 0)
NewArrayCount = 1;
for i = 1:NoChars
if (~isspace(charArray(i)))
y(NewArrayCount) = charArray(i);
NewArrayCount = NewArrayCount + 1;
end;
end;
else
y = charArray;
end;
|
github | claassengroup/matLeap-master | ConvertFormulaToMathML.m | .m | matLeap-master/libSBML-5.12.0-matlab/ConvertFormulaToMathML.m | 9,356 | utf_8 | 340134515b50305b849db7c47490aef3 | function Formula = ConvertFormulaToMathML(Input)
% converts from MATLAB to MathML in-fix functions
% Filename : ConvertFormulaToMathML.m
%
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2013 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation. A copy of the license agreement is provided
% in the file named "LICENSE.txt" included with this software distribution
% and also available online as http://sbml.org/software/libsbml/license.html
%
% The original code contained here was initially developed by:
%
% Sarah Keating
% Science and Technology Research Centre
% University of Hertfordshire
% Hatfield, AL10 9AB
% United Kingdom
%
% http://www.sbml.org
% mailto:[email protected]
%
% Contributor(s):
Input = LoseWhiteSpace(Input);
Formula = strrep(Input, 'acosh(', 'arccosh(');
Formula = strrep(Formula, 'acot(', 'arccot(');
Formula = strrep(Formula, 'acoth(', 'arccoth(');
Formula = strrep(Formula, 'acsc(', 'arccsc(');
Formula = strrep(Formula, 'acsch(', 'arccsch(');
Formula = strrep(Formula, 'asec(', 'arcsec(');
Formula = strrep(Formula, 'asech(', 'arcsech(');
Formula = strrep(Formula, 'asinh(', 'arcsinh(');
Formula = strrep(Formula, 'atanh(', 'arctanh(');
Formula = strrep(Formula, 'exp(1)', 'exponentiale');
Formula = strrep(Formula, 'ge(', 'geq(');
Formula = strrep(Formula, 'le(', 'leq(');
Formula = strrep(Formula, 'ne(', 'neq(');
Formula = strrep(Formula, 'power(', 'pow(');
% log2(x) must become log(2, x)
Formula = strrep(Formula, 'log2(', 'log(2, ');
%
%
% nthroot(x,n) must become root(n,x)
Index = strfind(Formula, 'nthroot(');
for i = 1:length(Index)
% create a subformula nthroot(x,n)
SubFunction = '';
j = 1;
nFunctions=0; %number of functions in expression
closedFunctions=0; %number of closed functions
while(nFunctions==0 || nFunctions~=closedFunctions)
SubFormula(j) = Formula(Index(i)+j-1);
if(strcmp(SubFormula(j),')'))
closedFunctions=closedFunctions+1;
end;
if(strcmp(SubFormula(j),'('))
nFunctions=nFunctions+1;
end;
j = j+1;
end;
j = 9;
n = '';
while(~strcmp(SubFormula(j), ','))
n = strcat(n, SubFormula(j));
j = j+1;
end;
j = j+1;
x = SubFormula(j:length(SubFormula)-1);
if (exist('OCTAVE_VERSION'))
ReplaceFormula = myRegexprep(SubFormula, n, x, 'once');
ReplaceFormula = myRegexprep(ReplaceFormula,regexptranslate('escape',x),n,2);
ReplaceFormula = myRegexprep(ReplaceFormula, 'nthroot', 'root', 'once');
else
ReplaceFormula = regexprep(SubFormula, n, x, 'once');
ReplaceFormula = regexprep(ReplaceFormula,regexptranslate('escape',x),n,2);
ReplaceFormula = regexprep(ReplaceFormula, 'nthroot', 'root', 'once');
end;
Formula = strrep(Formula, SubFormula, ReplaceFormula);
Index = strfind(Formula, 'nthroot(');
end;
% (log(x)/log(n)) must become log(n,x)
% but log(x) must be left alone
Formula = convertLog(Formula);
%
function y = convertLog(Formula)
y = Formula;
LogTypes = IsItLogBase(Formula);
num = sum(LogTypes);
Index = strfind(Formula, '(log(');
subIndex = 1;
for i = 1:length(Index)
if (LogTypes(i) == 1)
% get x and n from (log(x)/log(n))
pairs = PairBrackets(Formula);
for j=1:length(pairs)
if (pairs(j,1) == Index(i))
break;
end;
end;
subFormula{subIndex} = Formula(Index(i):pairs(j,2));
ff = subFormula{subIndex};
subPairs = PairBrackets(ff);
x = ff(subPairs(2,1)+1:subPairs(2,2)-1);
n = ff(subPairs(3,1)+1:subPairs(3,2)-1);
newFormula{subIndex} = sprintf('log(%s,%s)', n, x);
subIndex = subIndex+1;
end;
end;
if (subIndex-1 > num)
error('Problem');
end;
for i=1:num
y = strrep(y, subFormula{i}, newFormula{i});
end;
function y = IsItLogBase(Formula)
% returns an array of 0/1 indicating whether each occurence of log is
% a (log(n)/log(x)) or a log(x)
% e.g. Formula = '(log(2)/log(3)) + log(6)'
% IsItLogBase returns y = [1,0]
y = 0;
LogIndex = strfind(Formula, '(log(');
if (isempty(LogIndex))
return;
else
Divide = strfind(Formula, ')/log(');
pairs = PairBrackets(Formula);
if (isempty(Divide))
return;
else
% check that the divide occurs between logs
for i=1:length(LogIndex)
match = 0;
for j=1:length(pairs)
if (pairs(j, 1) == LogIndex(i))
break;
end;
end;
for k = 1:length(Divide)
if (pairs(j+1,2) == Divide(k))
match = 1;
break;
end;
end;
y(i) = match;
end;
end;
end;
%**********************************************************************
% LoseWhiteSpace(charArray) takes an array of characters
% and returns the array with any white space removed
%
%**********************************************************************
function y = LoseWhiteSpace(charArray)
% LoseWhiteSpace(charArray) takes an array of characters
% and returns the array with any white space removed
%
%----------------------------------------------------------------
% EXAMPLE:
% y = LoseWhiteSpace(' exa mp le')
% y = 'example'
%
%------------------------------------------------------------
% check input is an array of characters
if (~ischar(charArray))
error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters');
end;
%-------------------------------------------------------------
% get the length of the array
NoChars = length(charArray);
%-------------------------------------------------------------
% create an array that indicates whether the elements of charArray are
% spaces
% e.g. WSpace = isspace(' v b') = [1, 1, 0, 1, 0]
% and determine how many
WSpace = isspace(charArray);
NoSpaces = sum(WSpace);
%-----------------------------------------------------------
% rewrite the array to leaving out any spaces
% remove any numbers from the array of symbols
if (NoSpaces > 0)
NewArrayCount = 1;
for i = 1:NoChars
if (~isspace(charArray(i)))
y(NewArrayCount) = charArray(i);
NewArrayCount = NewArrayCount + 1;
end;
end;
else
y = charArray;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pairs = PairBrackets(formula)
% PairBrackets takes a string
% and returns
% an array of indices of each pair of brackets
% ordered from the opening bracket index
%
if (~ischar(formula))
error(sprintf('%s\n%s', 'PairBrackets(formula)', 'first argument must be a string'));
end;
OpeningBracketIndex = strfind(formula, '(');
ClosingBracketIndex = strfind(formula, ')');
% check that the number of brackets matches
if (length(OpeningBracketIndex) ~= length(ClosingBracketIndex))
error('Bracket mismatch');
end;
if (isempty(OpeningBracketIndex))
pairs = 0;
return;
end;
for i = 1:length(OpeningBracketIndex)
j = length(OpeningBracketIndex);
while(j > 0)
if (OpeningBracketIndex(j) < ClosingBracketIndex(i))
pairs(i,1) = OpeningBracketIndex(j);
pairs(i,2) = ClosingBracketIndex(i);
OpeningBracketIndex(j) = max(ClosingBracketIndex);
j = 0;
else
j = j - 1;
end;
end;
end;
% order the pairs so that the opening bracket index is in ascending order
OriginalPairs = pairs;
% function 'sort' changes in version 7.0.1
v = version;
v_num = str2num(v(1));
if (v_num < 7)
TempPairs = sort(pairs, 1);
else
TempPairs = sort(pairs, 1, 'ascend');
end;
for i = 1:length(OpeningBracketIndex)
pairs(i, 1) = TempPairs(i, 1);
j = find(OriginalPairs == pairs(i, 1));
pairs(i, 2) = OriginalPairs(j, 2);
end;
function string = myRegexprep(string, repre, repstr, number)
%% Parse input arguements
n = -1;
if isnumeric(number)
n = number;
elseif strcmpi(number, 'once')
n = 1;
else
error('Invalid argument to myRegexprep');
end;
[st, en] = regexp(string, repre);
if (n > 0)
if (length(st) >= n)
st = st(n);
en = en(n);
else
error('Invalid number of matches in myRegexprep');
st = [];
end;
end;
for i = length(st):-1:1
string = [string(1:st(i)-1) repstr string(en(i)+1:length(string))];
end;
|
github | claassengroup/matLeap-master | installSBML.m | .m | matLeap-master/libSBML-5.12.0-matlab/installSBML.m | 12,505 | utf_8 | d29eeee59c9bb8682a5b13deeeabf9b5 | function installSBML(varargin)
% Installs the MATLAB language interface for libSBML.
%
% This script assumes that the libsbml matlab binding executables files already
% exist; either because the user has built them using buildSBML (only
% in the src release) or the binding is being installed from an installer.
%
% Currently prebuilt executables are only available in the windows installers
% of libSBML.
%
% For Linux or Mac users this means that you need to build libsbml and then
% run the buildSBML script.
% Filename : installSBML.m
% Description : install matlab binding
% Author(s) : SBML Team <[email protected]>
% Organization: EMBL-EBI
%
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2013 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation. A copy of the license agreement is provided
% in the file named "LICENSE.txt" included with this software distribution
% and also available online as http://sbml.org/software/libsbml/license.html
%
% =========================================================================
% Main loop.
% =========================================================================
% look at input arguments
[verbose, directory] = checkInputArguments(varargin);
myDisp({'Installing the libSBML interface.'}, verbose);
[matlab_octave] = check_system(verbose);
[functioning, located] = checkForExecutables(matlab_octave, directory, verbose);
if (functioning == 0)
if (located == 0)
% we didnt find executables where we first looked
% try again with a different directory
if (isWindows() == 0)
if (strcmp(directory, '/usr/local/lib') == 0)
directory = '/usr/local/lib';
functioning = checkForExecutables(matlab_octave, directory, verbose);
end;
else
if (strcmp(directory, pwd) == 0)
directory = pwd;
functioning = checkForExecutables(matlab_octave, directory, verbose);
end;
end;
else
% we found executables but they did not work
error('%s%s%s\n%s%s', ...
'Executables were located at ', directory, ' but failed to execute', ...
'Please contact the libSBML team [email protected] ', ...
'for further assistance');
end;
end;
if (functioning == 1)
myDisp({'Installation successful'}, verbose);
end;
end
% =========================================================================
% Helper functions
% =========================================================================
% check any input arguments
%--------------------------------------------------------------------------
function [verbose, directory] = checkInputArguments(input)
numArgs = length(input);
if (numArgs > 2)
reportInputArgumentError('Too many arguments to installSBML');
end;
if (numArgs == 0)
verbose = 1;
if (isWindows() == 1)
directory = pwd;
else
directory = '/usr/local/lib';
end;
elseif (numArgs == 1)
directory = input{1};
verbose = 1;
else
directory = input{1};
verbose = input{2};
end;
if (verbose ~= 0 && verbose ~= 1)
reportInputArgumentError('Incorrect value for verbose flag');
end;
if (ischar(directory) ~= 1)
reportInputArgumentError('Directory value should be a string');
elseif(exist(directory, 'dir') ~= 7)
reportInputArgumentError('Directory value should be a directory');
end;
end
% display error message relating to input arguments
%---------------------------------------------------
function reportInputArgumentError(message)
error('%s\n%s\n\t%s%s\n\t%s%s\n\t\t%s', message, ...
'Arguments are optional but if present:', ...
'the first should be a string representing the directory containing ', ...
'the executables', 'the second should be a flag (0 or 1) indicating ', ...
'whether messages should be displayed ', ...
'0 - no messages; 1 - display messages');
end
% display error messages iff verbose = 1
%-----------------------------------------
function myDisp(message, verbose)
outputStr = '';
if (verbose == 1)
for i=1:length(message)
outputStr = sprintf('%s\n%s', outputStr, message{i});
end;
end;
disp(outputStr);
end
%
%
% Is this windows
% Mac OS X 10.7 Lion returns true for a call to ispc()
% since we were using that to distinguish between windows and macs we need
% to catch this
% ------------------------------------------------------------------------
function y = isWindows()
y = 1;
if isunix()
y = 0;
return;
end;
if ismac()
y = 0;
return;
end;
if ~ispc()
error('\n%s\n%s\n', ...
'Unable to determine the type of operating system in use.', ...
'Please contact [email protected] to help resolve this problem.');
end;
end
%
% Assess our computing environment.
% -------------------------------------------------------------------------
function [matlab_octave] = check_system(verbose)
message{1} = '* Doing preliminary checks of runtime environment ...';
if (strcmp(isoctave(), '0'))
matlab_octave = 'MATLAB';
message{2} = ' - This appears to be MATLAB and not Octave.';
else
matlab_octave = 'Octave';
message{2} = ' - This appears to be Octave and not MATLAB.';
end;
myDisp(message, verbose);
end
%
% check for executables and that they are right ones
% -------------------------------------------------------------------------
function [success, located] = checkForExecutables(matlab_octave, directory, verbose)
message{1} = 'Checking for executables in ';
message{2} = sprintf('\t%s', directory);
transFile = strcat('TranslateSBML.', mexext());
outFile = strcat('OutputSBML.', mexext());
thisDirTFile = fullfile(pwd(), transFile);
thisDirOFile = fullfile(pwd(), outFile);
success = 0;
located = 0;
if strcmpi(matlab_octave, 'matlab')
if (~(exist([directory, filesep, transFile], 'file') ~= 0 ...
&& exist([directory, filesep, outFile], 'file') ~= 0))
located = 0;
else
located = 1;
end;
else
% octave is much more picky about whether the files exist
% it wants to find the libraries at the same time
% exist throws an exception if it cannot find them
if (~(myExist(directory, transFile) ~= 0 ...
&& myExist(directory, outFile) ~= 0))
located = 0;
else
located = 1;
end;
end;
if (located == 1)
% we have found the executables where the user says but
% need to check that there are not other files on the path
t = which(transFile);
o = which(outFile);
% exclude the current dir
currentT = strcmp(t, thisDirTFile);
currentO = strcmp(t, thisDirOFile);
found = 0;
if (currentT == 1 && currentO == 1)
t_found = 0;
if (isempty(t) == 0 && strcmp(t, [directory, filesep, transFile]) == 0)
found = 1;
t_found = 1;
elseif (isempty(o) == 0 && strcmp(o, [directory, filesep, outFile]) == 0)
found = 1;
end;
end;
if (found == 1)
if (t_found == 1)
pathDir = t;
else
pathDir = o;
end;
error('%s\n%s\n%s', 'Other libsbml executables found on the path at:', ...
pathDir, ...
'Please uninstall these before attempting to install again');
end;
end;
if (located == 1)
message{3} = 'Executables found';
else
message{3} = 'Executables not found';
end;
myDisp(message, verbose);
if (located == 1)
% we have found the executables
% add the directory to the matlab path
added = addDir(directory, verbose);
% if addDir returns 0 this may be that the user does not have
% permission to add to the path
if (added == 0)
error('%s%s%s%s\n%s%s', ...
'The directory containing the executables could not ', ...
'be added to the ', matlab_octave, ' path', ...
'You may need to run in administrator mode or contact your ', ...
'network manager if running from a network');
elseif (added == 1)
% to test the actual files we need to be in the directory
% if we happen to be in the src tree where the .m helps files
% exist these will get picked up first by the function calls
% according to mathworks the only way to avoid this is to cd to the
% right dir
currentDir = pwd();
cd(directory);
success = doesItRun(matlab_octave, verbose, currentDir);
cd (currentDir);
end;
% at this point if success = 0 it means there was an error running
% the files - take the directory out of the path
if (success == 0 && added == 1)
removeDir(directory, verbose);
end;
end;
end
% test the installation
% -------------------------------------------------------------------------
function success = doesItRun(matlab_octave, verbose, dirForTest)
success = 1;
message{1} = 'Attempting to execute functions';
myDisp(message, verbose);
testFile = fullfile(dirForTest, 'test.xml');
if strcmpi(matlab_octave, 'matlab')
try
M = TranslateSBML(testFile);
message{1} = 'TranslateSBML successful';
catch ME
success = 0;
message{1} = sprintf('%s\n%s', 'TranslateSBML failed', ME.message);
end;
else
try
M = TranslateSBML(testFile);
message{1} = 'TranslateSBML successful';
catch
success = 0;
message{1} = 'TranslateSBML failed';
end;
end;
if strcmpi(matlab_octave, 'matlab')
outFile = [tempdir, filesep, 'test-out.xml'];
else
if isWindows()
outFile = [tempdir, 'temp', filesep, 'test-out.xml'];
else
outFile = [tempdir, 'test-out.xml'];
end;
end;
if (success == 1)
if strcmpi(matlab_octave, 'matlab')
try
if (verbose == 1)
OutputSBML(M, outFile);
else
OutputSBML(M, outFile, verbose, verbose);
end;
message{2} = 'OutputSBML successful';
catch ME
success = 0;
message{2} = sprintf('%s\n%s', 'OutputSBML failed', ME.message);
end;
else
try
if (verbose == 1)
OutputSBML(M, outFile);
else
OutputSBML(M, outFile, verbose, verbose);
end;
message{2} = 'OutputSBML successful';
catch
success = 0;
message{2} = 'OutputSBML failed';
end;
end;
end;
myDisp(message, verbose);
end
% add directory to the matlab path
% -------------------------------------------------------------------------
function added = addDir(name, verbose)
added = 0;
addpath(name);
if (savepath ~= 0)
message{1} = sprintf('Adding %s to path ...\nFailed', name);
else
message{1} = sprintf('Adding %s to path ...\nSuccess', name);
added = 1;
end;
myDisp(message, verbose);
end
% remove directory to the matlab path
% -------------------------------------------------------------------------
function added = removeDir(name, verbose)
added = 0;
rmpath(name);
if (savepath ~= 0)
message{1} = sprintf('Removing %s from path ...\nFailed', name);
else
message{1} = sprintf('Removing %s from path ...\nSuccess', name);
added = 1;
end;
myDisp(message, verbose);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function found = myExist(directory, filename)
found = 0;
dirnames = dir(directory);
i = 1;
while (found == 0 && i <= length(dirnames))
if (dirnames(i).isdir == 0)
found = strcmp(dirnames(i).name, filename);
end;
i = i+1;
end;
end
|
github | claassengroup/matLeap-master | isSBML_Model.m | .m | matLeap-master/libSBML-5.12.0-matlab/isSBML_Model.m | 107,187 | utf_8 | 498389acf901590bf5411ed06382e606 | function [valid, message] = isSBML_Model(varargin)
% [valid, message] = isSBML_Model(SBMLModel)
%
% Takes
%
% 1. SBMLModel, an SBML Model structure
% 2. extensions_allowed (optional) =
% - 0, structures should contain ONLY required fields
% - 1, structures may contain additional fields (default)
%
% Returns
%
% 1. valid =
% - 1, if the structure represents
% a MATLAB_SBML Model structure of the appropriate
% level and version
% - 0, otherwise
% 2. a message explaining any failure
%
%<!---------------------------------------------------------------------------
% This file is part of libSBML. Please visit http://sbml.org for more
% information about SBML, and the latest version of libSBML.
%
% Copyright (C) 2013-2014 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
% 3. University of Heidelberg, Heidelberg, Germany
%
% Copyright (C) 2009-2013 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
%
% Copyright (C) 2006-2008 by the California Institute of Technology,
% Pasadena, CA, USA
%
% Copyright (C) 2002-2005 jointly by the following organizations:
% 1. California Institute of Technology, Pasadena, CA, USA
% 2. Japan Science and Technology Agency, Japan
%
% This library is free software; you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation. A copy of the license
% agreement is provided in the file named "LICENSE.txt" included with
% this software distribution and also available online as
% http://sbml.org/software/libsbml/license.html
%----------------------------------------------------------------------- -->
%check the input arguments are appropriate
if (nargin < 1)
error('isSBML_Model needs at least one argument');
elseif (nargin == 1)
SBMLStructure = varargin{1};
extensions_allowed = 1;
elseif (nargin == 2)
SBMLStructure = varargin{1};
extensions_allowed = varargin{2};
else
error('too many arguments to isSBML_Model');
end;
if (isfield(SBMLStructure, 'fbc_version') && isFbcEnabled() == 1)
if isfield(SBMLStructure, 'SBML_level') && isfield(SBMLStructure, 'SBML_version')
[valid, message] = isSBML_FBC_Model(SBMLStructure, SBMLStructure.SBML_level, ...
SBMLStructure.SBML_version, SBMLStructure.fbc_version, extensions_allowed);
else
[valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 0);
end;
else
[valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 0);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isValidSBML_Model(SBMLStructure, ...
extensions_allowed, in_fbc)
%check the input arguments are appropriate
if (length(SBMLStructure) > 1)
valid = 0;
message = 'cannot deal with arrays of structures';
return;
end;
if ~isempty(SBMLStructure)
if isfield(SBMLStructure, 'SBML_level')
level = SBMLStructure.SBML_level;
else
level = 3;
end;
if isfield(SBMLStructure, 'SBML_version')
version = SBMLStructure.SBML_version;
else
version = 1;
end;
else
level = 3;
version = 1;
end;
isValidLevelVersionCombination(level, version);
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
typecode = 'SBML_MODEL';
if (valid == 1 && ~isempty(SBMLStructure))
if isfield(SBMLStructure, 'typecode')
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
return;
end;
else
valid = 0;
message = 'missing typecode field';
return;
end;
end;
% check that structure contains all the necessary fields
[SBMLfieldnames, numFields] = getFieldnames('SBML_MODEL', level, version);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
%check that any nested structures are appropriate
% functionDefinitions
if (valid == 1 && level > 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.functionDefinition))
[valid, message] = isSBML_Struct('SBML_FUNCTION_DEFINITION', ...
SBMLStructure.functionDefinition(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% unitDefinitions
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.unitDefinition))
[valid, message] = isSBML_Struct('SBML_UNIT_DEFINITION', ...
SBMLStructure.unitDefinition(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% compartments
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.compartment))
[valid, message] = isSBML_Struct('SBML_COMPARTMENT', ...
SBMLStructure.compartment(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% species
if (valid == 1 && in_fbc == 0)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.species))
[valid, message] = isSBML_Struct('SBML_SPECIES', ...
SBMLStructure.species(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% compartmentTypes
if (valid == 1 && level == 2 && version > 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.compartmentType))
[valid, message] = isSBML_Struct('SBML_COMPARTMENT_TYPE', ...
SBMLStructure.compartmentType(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% speciesTypes
if (valid == 1 && level == 2 && version > 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.speciesType))
[valid, message] = isSBML_Struct('SBML_SPECIES_TYPE', ...
SBMLStructure.speciesType(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% parameter
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.parameter))
[valid, message] = isSBML_Struct('SBML_PARAMETER', ...
SBMLStructure.parameter(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% initialAssignment
if (valid == 1 && (level > 2 || (level == 2 && version > 1)))
index = 1;
while (valid == 1 && index <= length(SBMLStructure.initialAssignment))
[valid, message] = isSBML_Struct('SBML_INITIAL_ASSIGNMENT', ...
SBMLStructure.initialAssignment(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% rule
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.rule))
[valid, message] = isSBML_Rule(SBMLStructure.rule(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% constraints
if (valid == 1 && (level > 2 || (level == 2 && version > 1)))
index = 1;
while (valid == 1 && index <= length(SBMLStructure.constraint))
[valid, message] = isSBML_Struct('SBML_CONSTRAINT', ...
SBMLStructure.constraint(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% reaction
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.reaction))
[valid, message] = isSBML_Struct('SBML_REACTION', ...
SBMLStructure.reaction(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% event
if (valid == 1 && level > 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.event))
[valid, message] = isSBML_Struct('SBML_EVENT', ...
SBMLStructure.event(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid Model structure\n%s\n', message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isSBML_Struct(typecode, SBMLStructure, level, version, extensions_allowed)
if (length(SBMLStructure) > 1)
valid = 0;
message = 'cannot deal with arrays of structures';
return;
end;
isValidLevelVersionCombination(level, version);
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
if (valid == 1 && ~isempty(SBMLStructure))
if isfield(SBMLStructure, 'typecode')
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
return;
end;
else
valid = 0;
message = 'missing typecode field';
return;
end;
end;
% if the level and version fields exist they must match
if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
if ~isequal(level, SBMLStructure.level)
valid = 0;
message = 'level mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
if ~isequal(version, SBMLStructure.version)
valid = 0;
message = 'version mismatch';
end;
end;
% check that structure contains all the necessary fields
[SBMLfieldnames, numFields] = getFieldnames(typecode, level, version);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
if (extensions_allowed == 0)
% check that the structure contains ONLY the expected fields
if (valid == 1)
if (numFields ~= length(fieldnames(SBMLStructure))-2)
valid = 0;
message = sprintf('Unexpected field detected');
end;
end;
end;
% some structures have child structures
switch (typecode)
case 'SBML_EVENT'
% eventAssignments
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.eventAssignment))
[valid, message] = isSBML_Struct('SBML_EVENT_ASSIGNMENT', ...
SBMLStructure.eventAssignment(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% trigger/delay/priority
% these are level and version dependent
if (valid == 1)
if (level == 2 && version > 2)
if (length(SBMLStructure.trigger) > 1)
valid = 0;
message = 'multiple trigger elements encountered';
elseif (length(SBMLStructure.delay) > 1)
valid = 0;
message = 'multiple delay elements encountered';
end;
if (valid == 1 && length(SBMLStructure.trigger) == 1)
[valid, message] = isSBML_Struct('SBML_TRIGGER', ...
SBMLStructure.trigger, ...
level, version, extensions_allowed);
end;
if (valid == 1 && length(SBMLStructure.delay) == 1)
[valid, message] = isSBML_Struct('SBML_DELAY', ...
SBMLStructure.delay, ...
level, version, extensions_allowed);
end;
elseif (level > 2)
if (length(SBMLStructure.trigger) > 1)
valid = 0;
message = 'multiple trigger elements encountered';
elseif (length(SBMLStructure.delay) > 1)
valid = 0;
message = 'multiple delay elements encountered';
elseif (length(SBMLStructure.priority) > 1)
valid = 0;
message = 'multiple priority elements encountered';
end;
if (valid == 1 && length(SBMLStructure.trigger) == 1)
[valid, message] = isSBML_Struct('SBML_TRIGGER', ...
SBMLStructure.trigger, ...
level, version, extensions_allowed);
end;
if (valid == 1 && length(SBMLStructure.delay) == 1)
[valid, message] = isSBML_Struct('SBML_DELAY', ...
SBMLStructure.delay, ...
level, version, extensions_allowed);
end;
if (valid == 1 && length(SBMLStructure.priority) == 1)
[valid, message] = isSBML_Struct('SBML_PRIORITY', ...
SBMLStructure.priority, ...
level, version, extensions_allowed);
end;
end;
end;
case 'SBML_KINETIC_LAW'
% parameters
if (valid == 1 && level < 3)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.parameter))
[valid, message] = isSBML_Struct('SBML_PARAMETER', ...
SBMLStructure.parameter(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
%check that any nested structures are appropriate
% localParameters
if (valid == 1 && level > 2)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.localParameter))
[valid, message] = isSBML_Struct('SBML_LOCAL_PARAMETER', ...
SBMLStructure.localParameter(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
case 'SBML_REACTION'
% reactants
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.reactant))
[valid, message] = isSBML_Struct('SBML_SPECIES_REFERENCE', ...
SBMLStructure.reactant(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% products
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.product))
[valid, message] = isSBML_Struct('SBML_SPECIES_REFERENCE', ...
SBMLStructure.product(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% modifiers
if (valid == 1 && level > 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.modifier))
[valid, message] = isSBML_Struct('SBML_MODIFIER_SPECIES_REFERENCE', ...
SBMLStructure.modifier(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
% kineticLaw
if (valid == 1 && length(SBMLStructure.kineticLaw) == 1)
[valid, message] = isSBML_Struct('SBML_KINETIC_LAW', ...
SBMLStructure.kineticLaw, level, version, extensions_allowed);
end;
case 'SBML_UNIT_DEFINITION'
% unit
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.unit))
[valid, message] = isSBML_Struct('SBML_UNIT', ...
SBMLStructure.unit(index), ...
level, version, extensions_allowed);
index = index + 1;
end;
end;
case 'SBML_SPECIES_REFERENCE'
% stoichiometryMath
if (level == 2 && version > 2)
if (valid == 1 && length(SBMLStructure.stoichiometryMath) == 1)
[valid, message] = isSBML_Struct('SBML_STOICHIOMETRY_MATH', ...
SBMLStructure.stoichiometryMath, ...
level, version, extensions_allowed);
end;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid %s\n%s\n', typecode, message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isSBML_Rule(SBMLStructure, ...
level, version, extensions_allowed)
if (length(SBMLStructure) > 1)
valid = 0;
message = 'cannot deal with arrays of structures';
return;
end;
isValidLevelVersionCombination(level, version);
message = '';
if ~isempty(SBMLStructure)
if isfield(SBMLStructure, 'typecode')
typecode = SBMLStructure.typecode;
else
valid = 0;
message = 'missing typecode';
return;
end;
else
typecode = 'SBML_ASSIGNMENT_RULE';
end;
switch (typecode)
case {'SBML_ALGEBRAIC_RULE', 'SBML_ASSIGNMENT_RULE', ...
'SBML_COMPARTMENT_VOLUME_RULE', 'SBML_PARAMETER_RULE', ...
'SBML_RATE_RULE', 'SBML_SPECIES_CONCENTRATION_RULE'}
[valid, message] = isSBML_Struct(typecode, SBMLStructure, level, version, extensions_allowed);
case 'SBML_RULE'
[valid, message] = checkRule(SBMLStructure, level, version, extensions_allowed);
otherwise
valid = 0;
message = 'Incorrect rule typecode';
end;
function [valid, message] = checkRule(SBMLStructure, level, version, extensions_allowed)
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
typecode = 'SBML_RULE';
if (valid == 1 && ~isempty(SBMLStructure))
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
end;
end;
% if the level and version fields exist they must match
if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
if ~isequal(level, SBMLStructure.level)
valid = 0;
message = 'level mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
if ~isequal(version, SBMLStructure.version)
valid = 0;
message = 'version mismatch';
end;
end;
% check that structure contains all the necessary fields
[SBMLfieldnames, numFields] = getAlgebraicRuleFieldnames(level, version);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
if (extensions_allowed == 0)
% check that the structure contains ONLY the expected fields
if (valid == 1)
if (numFields ~= length(fieldnames(SBMLStructure))-2)
valid = 0;
message = sprintf('Unexpected field detected');
end;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid Rule\n%s\n', message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isSBML_FBCStruct(typecode, SBMLStructure, level, ...
version, pkgVersion, extensions_allowed)
if (length(SBMLStructure) > 1)
valid = 0;
message = 'cannot deal with arrays of structures';
return;
end;
isValidLevelVersionCombination(level, version);
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
if (valid == 1 && ~isempty(SBMLStructure))
if isfield(SBMLStructure, 'typecode')
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
return;
end;
else
valid = 0;
message = 'missing typecode field';
return;
end;
end;
% if the level and version fields exist they must match
if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
if ~isequal(level, SBMLStructure.level)
valid = 0;
message = 'level mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
if ~isequal(version, SBMLStructure.version)
valid = 0;
message = 'version mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
if ~isequal(pkgVersion, SBMLStructure.fbc_version)
valid = 0;
message = 'fbc version mismatch';
end;
end;
% check that structure contains all the necessary fields
[SBMLfieldnames, numFields] = getFieldnames(typecode, level, version, pkgVersion);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
if (extensions_allowed == 0)
% check that the structure contains ONLY the expected fields
if (valid == 1)
if (numFields ~= length(fieldnames(SBMLStructure)))
valid = 0;
message = sprintf('Unexpected field detected');
end;
end;
end;
% some structures have child structures
switch (typecode)
case 'SBML_FBC_OBJECTIVE'
% eventAssignments
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.fbc_fluxObjective))
[valid, message] = isSBML_FBCStruct('SBML_FBC_FLUXOBJECTIVE', ...
SBMLStructure.fbc_fluxObjective(index), ...
level, version, pkgVersion, extensions_allowed);
index = index + 1;
end;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid %s\n%s\n', typecode, message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isSBML_FBC_Model(SBMLStructure, level, version, ...
pkgVersion, extensions_allowed)
% [valid, message] = isSBML_FBC_Model(SBMLFBCModel, level, version, pkgVersion)
if (length(SBMLStructure) > 1)
message = 'cannot deal with arrays of structures';
valid = 0;
return;
end;
isValidLevelVersionCombination(level, version);
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
typecode = 'SBML_MODEL';
if (valid == 1 && ~isempty(SBMLStructure))
if isfield(SBMLStructure, 'typecode')
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
return;
end;
else
valid = 0;
message = 'typecode field missing';
return;
end;
end;
% if the level and version fields exist they must match
if (valid == 1 && isfield(SBMLStructure, 'SBML_level') && ~isempty(SBMLStructure))
if ~isequal(level, SBMLStructure.SBML_level)
valid = 0;
message = 'level mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'SBML_version') && ~isempty(SBMLStructure))
if ~isequal(version, SBMLStructure.SBML_version)
valid = 0;
message = 'version mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
if ~isequal(pkgVersion, SBMLStructure.fbc_version)
valid = 0;
message = 'FBC version mismatch';
end;
end;
if (valid == 1)
% do not worry about extra fields at this point
% we know we are in an fbc model
[valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 1);
end;
% check that structure contains all the fbc fields
if (valid == 1)
[SBMLfieldnames, numFields] = getFieldnames('SBML_FBC_MODEL', level, ...
version, pkgVersion);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
%check that any nested structures are appropriate
% fluxBound
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.fbc_fluxBound))
[valid, message] = isSBML_FBCStruct('SBML_FBC_FLUXBOUND', ...
SBMLStructure.fbc_fluxBound(index), ...
level, version, pkgVersion, extensions_allowed);
index = index + 1;
end;
end;
% objective
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.fbc_objective))
[valid, message] = isSBML_FBCStruct('SBML_FBC_OBJECTIVE', ...
SBMLStructure.fbc_objective(index), ...
level, version, pkgVersion, extensions_allowed);
index = index + 1;
end;
end;
%species
if (valid == 1)
index = 1;
while (valid == 1 && index <= length(SBMLStructure.species))
[valid, message] = isSBML_FBC_Species('SBML_FBC_SPECIES', ...
SBMLStructure.species(index), ...
level, version, pkgVersion, extensions_allowed);
index = index + 1;
end;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid FBC Model\n%s\n', message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid, message] = isSBML_FBC_Species(typecode, SBMLStructure, ...
level, version, pkgVersion, extensions_allowed)
if (length(SBMLStructure) > 1)
message = 'cannot deal with arrays of structures';
valid = 0;
return;
end;
isValidLevelVersionCombination(level, version);
message = '';
% check that argument is a structure
valid = isstruct(SBMLStructure);
% check the typecode
typecode = 'SBML_SPECIES';
if (valid == 1 && ~isempty(SBMLStructure))
if isfield(SBMLStructure, 'typecode')
if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
valid = 0;
message = 'typecode mismatch';
return;
end;
else
valid = 0;
message = 'typecode field missing';
return;
end;
end;
% if the level and version fields exist they must match
if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
if ~isequal(level, SBMLStructure.level)
valid = 0;
message = 'level mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
if ~isequal(version, SBMLStructure.version)
valid = 0;
message = 'version mismatch';
end;
end;
if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
if ~isequal(pkgVersion, SBMLStructure.fbc_version)
valid = 0;
message = 'FBC version mismatch';
end;
end;
if (valid == 1)
[valid, message] = isSBML_Struct('SBML_SPECIES', SBMLStructure, level, ...
version, 1);
end;
% check that structure contains all the fbc fields
if (valid == 1)
[SBMLfieldnames, numFields] = getFieldnames('SBML_FBC_SPECIES', level, ...
version);
if (numFields ==0)
valid = 0;
message = 'invalid level/version';
end;
index = 1;
while (valid == 1 && index <= numFields)
valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
if (valid == 0);
message = sprintf('%s field missing', char(SBMLfieldnames(index)));
end;
index = index + 1;
end;
if (extensions_allowed == 0)
% check that the structure contains ONLY the expected fields
if (valid == 1)
if (numFields ~= length(fieldnames(SBMLStructure))-19)
valid = 0;
message = sprintf('Unexpected field detected');
end;
end;
end;
end;
% report failure
if (valid == 0)
message = sprintf('Invalid FBC Species\n%s\n', message);
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function valid = isValidLevelVersionCombination(level, version)
valid = 1;
if ~isIntegralNumber(level)
error('level must be an integer');
elseif ~isIntegralNumber(version)
error('version must be an integer');
end;
if (level < 1 || level > 3)
error('current SBML levels are 1, 2 or 3');
end;
if (level == 1)
if (version < 1 || version > 2)
error('SBMLToolbox supports versions 1-2 of SBML Level 1');
end;
elseif (level == 2)
if (version < 1 || version > 5)
error('SBMLToolbox supports versions 1-5 of SBML Level 2');
end;
elseif (level == 3)
if (version ~= 1)
error('SBMLToolbox supports only version 1 of SBML Level 3');
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function value = isIntegralNumber(number)
value = 0;
integerClasses = {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'};
% since the function isinteger does not exist in MATLAB Rel 13
% this is not used
%if (isinteger(number))
if (ismember(class(number), integerClasses))
value = 1;
elseif (isnumeric(number))
% if it is an integer
if (number == fix(number))
value = 1;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getAlgebraicRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'type', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getAssignmentRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getCompartmentFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'name', ...
'volume', ...
'units', ...
'outside', ...
'isSetVolume', ...
};
nNumberFields = 8;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'spatialDimensions', ...
'size', ...
'units', ...
'outside', ...
'constant', ...
'isSetSize', ...
'isSetVolume', ...
};
nNumberFields = 13;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'compartmentType', ...
'spatialDimensions', ...
'size', ...
'units', ...
'outside', ...
'constant', ...
'isSetSize', ...
'isSetVolume', ...
};
nNumberFields = 14;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'compartmentType', ...
'spatialDimensions', ...
'size', ...
'units', ...
'outside', ...
'constant', ...
'isSetSize', ...
'isSetVolume', ...
};
nNumberFields = 15;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'compartmentType', ...
'spatialDimensions', ...
'size', ...
'units', ...
'outside', ...
'constant', ...
'isSetSize', ...
'isSetVolume', ...
};
nNumberFields = 15;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'spatialDimensions', ...
'size', ...
'units', ...
'constant', ...
'isSetSize', ...
'isSetSpatialDimensions', ...
};
nNumberFields = 13;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getCompartmentTypeFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
};
nNumberFields = 6;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
};
nNumberFields = 7;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
};
nNumberFields = 7;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getCompartmentVolumeRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'type', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 4 || version == 5)
SBMLfieldnames = [];
nNumberFields = 0;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getConstraintFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
'message', ...
};
nNumberFields = 7;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
'message', ...
};
nNumberFields = 7;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
'message', ...
};
nNumberFields = 7;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
'message', ...
};
nNumberFields = 7;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getDelayFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getEventAssignmentFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'variable', ...
'math', ...
};
nNumberFields = 6;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'variable', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 7;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'variable', ...
'math', ...
};
nNumberFields = 7;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'variable', ...
'math', ...
};
nNumberFields = 7;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'variable', ...
'math', ...
};
nNumberFields = 7;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getEventFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'trigger', ...
'delay', ...
'timeUnits', ...
'eventAssignment', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'trigger', ...
'delay', ...
'timeUnits', ...
'sboTerm', ...
'eventAssignment', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'trigger', ...
'delay', ...
'eventAssignment', ...
};
nNumberFields = 10;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'useValuesFromTriggerTime', ...
'trigger', ...
'delay', ...
'eventAssignment', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'useValuesFromTriggerTime', ...
'trigger', ...
'delay', ...
'priority', ...
'eventAssignment', ...
};
nNumberFields = 12;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFieldnames(varargin)
if (nargin < 3)
error('getFieldnames requires 3 arguments');
end;
typecode = varargin{1};
level = varargin{2};
version = varargin{3};
if nargin == 4
pkgVersion = varargin{4};
else
pkgVersion = 1;
end;
done = 1;
switch (typecode)
case {'SBML_ALGEBRAIC_RULE', 'AlgebraicRule', 'algebraicRule'}
[SBMLfieldnames, nNumberFields] = getAlgebraicRuleFieldnames(level, version);
case {'SBML_ASSIGNMENT_RULE', 'AssignmentRule', 'assignmentRule'}
[SBMLfieldnames, nNumberFields] = getAssignmentRuleFieldnames(level, version);
case {'SBML_COMPARTMENT', 'Compartment', 'compartment'}
[SBMLfieldnames, nNumberFields] = getCompartmentFieldnames(level, version);
case {'SBML_COMPARTMENT_TYPE', 'CompartmentType', 'compartmentType'}
[SBMLfieldnames, nNumberFields] = getCompartmentTypeFieldnames(level, version);
case {'SBML_COMPARTMENT_VOLUME_RULE', 'CompartmentVolumeRule', 'compartmentVolumeRule'}
[SBMLfieldnames, nNumberFields] = getCompartmentVolumeRuleFieldnames(level, version);
case {'SBML_CONSTRAINT', 'Constraint', 'constraint'}
[SBMLfieldnames, nNumberFields] = getConstraintFieldnames(level, version);
case {'SBML_DELAY', 'Delay', 'delay'}
[SBMLfieldnames, nNumberFields] = getDelayFieldnames(level, version);
case {'SBML_EVENT', 'Event', 'event'}
[SBMLfieldnames, nNumberFields] = getEventFieldnames(level, version);
case {'SBML_EVENT_ASSIGNMENT', 'EventAssignment', 'eventAssignment'}
[SBMLfieldnames, nNumberFields] = getEventAssignmentFieldnames(level, version);
case {'SBML_FUNCTION_DEFINITION', 'FunctionDefinition', 'functionDefinition'}
[SBMLfieldnames, nNumberFields] = getFunctionDefinitionFieldnames(level, version);
case {'SBML_INITIAL_ASSIGNMENT', 'InitialAssignment', 'initialAssignment'}
[SBMLfieldnames, nNumberFields] = getInitialAssignmentFieldnames(level, version);
case {'SBML_KINETIC_LAW', 'KineticLaw', 'kineticLaw'}
[SBMLfieldnames, nNumberFields] = getKineticLawFieldnames(level, version);
case {'SBML_LOCAL_PARAMETER', 'LocalParameter', 'localParameter'}
[SBMLfieldnames, nNumberFields] = getLocalParameterFieldnames(level, version);
case {'SBML_MODEL', 'Model', 'model'}
[SBMLfieldnames, nNumberFields] = getModelFieldnames(level, version);
case {'SBML_MODIFIER_SPECIES_REFERENCE', 'ModifierSpeciesReference', 'modifierSpeciesReference'}
[SBMLfieldnames, nNumberFields] = getModifierSpeciesReferenceFieldnames(level, version);
case {'SBML_PARAMETER', 'Parameter', 'parameter'}
[SBMLfieldnames, nNumberFields] = getParameterFieldnames(level, version);
case {'SBML_PARAMETER_RULE', 'ParameterRule', 'parameterRule'}
[SBMLfieldnames, nNumberFields] = getParameterRuleFieldnames(level, version);
case {'SBML_PRIORITY', 'Priority', 'priority'}
[SBMLfieldnames, nNumberFields] = getPriorityFieldnames(level, version);
case {'SBML_RATE_RULE', 'RateRule', 'ruleRule'}
[SBMLfieldnames, nNumberFields] = getRateRuleFieldnames(level, version);
case {'SBML_REACTION', 'Reaction', 'reaction'}
[SBMLfieldnames, nNumberFields] = getReactionFieldnames(level, version);
case {'SBML_SPECIES', 'Species', 'species'}
[SBMLfieldnames, nNumberFields] = getSpeciesFieldnames(level, version);
case {'SBML_SPECIES_CONCENTRATION_RULE', 'SpeciesConcentrationRule', 'speciesConcentrationRule'}
[SBMLfieldnames, nNumberFields] = getSpeciesConcentrationRuleFieldnames(level, version);
case {'SBML_SPECIES_REFERENCE', 'SpeciesReference', 'speciesReference'}
[SBMLfieldnames, nNumberFields] = getSpeciesReferenceFieldnames(level, version);
case {'SBML_SPECIES_TYPE', 'SpeciesType', 'speciesType'}
[SBMLfieldnames, nNumberFields] = getSpeciesTypeFieldnames(level, version);
case {'SBML_STOICHIOMETRY_MATH', 'StoichiometryMath', 'stoichiometryMath'}
[SBMLfieldnames, nNumberFields] = getStoichiometryMathFieldnames(level, version);
case {'SBML_TRIGGER', 'Trigger', 'trigger'}
[SBMLfieldnames, nNumberFields] = getTriggerFieldnames(level, version);
case {'SBML_UNIT', 'Unit', 'unit'}
[SBMLfieldnames, nNumberFields] = getUnitFieldnames(level, version);
case {'SBML_UNIT_DEFINITION', 'UnitDefinition', 'unitDefinition'}
[SBMLfieldnames, nNumberFields] = getUnitDefinitionFieldnames(level, version);
otherwise
done = 0;
end;
if done == 0
switch (typecode)
case {'SBML_FBC_FLUXBOUND', 'FluxBound', 'fluxBound'}
[SBMLfieldnames, nNumberFields] = getFluxBoundFieldnames(level, version, pkgVersion);
case {'SBML_FBC_FLUXOBJECTIVE', 'FluxObjective', 'fluxObjective'}
[SBMLfieldnames, nNumberFields] = getFluxObjectiveFieldnames(level, version, pkgVersion);
case {'SBML_FBC_OBJECTIVE', 'Objective', 'objective'}
[SBMLfieldnames, nNumberFields] = getObjectiveFieldnames(level, version, pkgVersion);
case {'SBML_FBC_MODEL', 'FBCModel'}
[SBMLfieldnames, nNumberFields] = getFBCModelFieldnames(level, version, pkgVersion);
case {'SBML_FBC_SPECIES', 'FBCSpecies'}
[SBMLfieldnames, nNumberFields] = getFBCSpeciesFieldnames(level, version, pkgVersion);
otherwise
error('%s\n%s', ...
'getFieldnames(typecode, level, version', ...
'typecode not recognised');
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFunctionDefinitionFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'math', ...
};
nNumberFields = 7;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'math', ...
};
nNumberFields = 8;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'math', ...
};
nNumberFields = 8;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'math', ...
};
nNumberFields = 8;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'math', ...
};
nNumberFields = 8;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getInitialAssignmentFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'symbol', ...
'math', ...
};
nNumberFields = 7;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'symbol', ...
'math', ...
};
nNumberFields = 7;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'symbol', ...
'math', ...
};
nNumberFields = 7;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'symbol', ...
'math', ...
};
nNumberFields = 7;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getKineticLawFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'formula', ...
'parameter', ...
'timeUnits', ...
'substanceUnits', ...
};
nNumberFields = 7;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'math', ...
'parameter', ...
'timeUnits', ...
'substanceUnits', ...
};
nNumberFields = 9;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'math', ...
'parameter', ...
'sboTerm', ...
};
nNumberFields = 8;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'math', ...
'parameter', ...
};
nNumberFields = 8;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'math', ...
'parameter', ...
};
nNumberFields = 8;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
'localParameter', ...
};
nNumberFields = 7;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getLocalParameterFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'value', ...
'units', ...
'isSetValue', ...
};
nNumberFields = 10;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getModelFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'unitDefinition', ...
'compartment', ...
'species', ...
'parameter', ...
'rule', ...
'reaction', ...
};
nNumberFields = 12;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'id', ...
'functionDefinition', ...
'unitDefinition', ...
'compartment', ...
'species', ...
'parameter', ...
'rule', ...
'reaction', ...
'event', ...
};
nNumberFields = 16;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'id', ...
'sboTerm', ...
'functionDefinition', ...
'unitDefinition', ...
'compartmentType', ...
'speciesType', ...
'compartment', ...
'species', ...
'parameter', ...
'initialAssignment', ...
'rule', ...
'constraint', ...
'reaction', ...
'event', ...
};
nNumberFields = 21;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'id', ...
'sboTerm', ...
'functionDefinition', ...
'unitDefinition', ...
'compartmentType', ...
'speciesType', ...
'compartment', ...
'species', ...
'parameter', ...
'initialAssignment', ...
'rule', ...
'constraint', ...
'reaction', ...
'event', ...
};
nNumberFields = 21;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'id', ...
'sboTerm', ...
'functionDefinition', ...
'unitDefinition', ...
'compartmentType', ...
'speciesType', ...
'compartment', ...
'species', ...
'parameter', ...
'initialAssignment', ...
'rule', ...
'constraint', ...
'reaction', ...
'event', ...
};
nNumberFields = 21;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'SBML_level', ...
'SBML_version', ...
'name', ...
'id', ...
'sboTerm', ...
'functionDefinition', ...
'unitDefinition', ...
'compartment', ...
'species', ...
'parameter', ...
'initialAssignment', ...
'rule', ...
'constraint', ...
'reaction', ...
'event', ...
'substanceUnits', ...
'timeUnits', ...
'lengthUnits', ...
'areaUnits', ...
'volumeUnits', ...
'extentUnits', ...
'conversionFactor', ...
};
nNumberFields = 26;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getModifierSpeciesReferenceFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'species', ...
};
nNumberFields = 5;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'species', ...
'id', ...
'name', ...
'sboTerm', ...
};
nNumberFields = 8;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
};
nNumberFields = 8;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
};
nNumberFields = 8;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
};
nNumberFields = 8;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getParameterFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'name', ...
'value', ...
'units', ...
'isSetValue', ...
};
nNumberFields = 7;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'value', ...
'units', ...
'constant', ...
'isSetValue', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'value', ...
'units', ...
'constant', ...
'sboTerm', ...
'isSetValue', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'value', ...
'units', ...
'constant', ...
'isSetValue', ...
};
nNumberFields = 11;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'value', ...
'units', ...
'constant', ...
'isSetValue', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'value', ...
'units', ...
'constant', ...
'isSetValue', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getParameterRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'type', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 4 || version == 5)
SBMLfieldnames = [];
nNumberFields = 0;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getPriorityFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getRateRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getReactionFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'name', ...
'reactant', ...
'product', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
};
nNumberFields = 9;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'reactant', ...
'product', ...
'modifier', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
'isSetFast', ...
};
nNumberFields = 13;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'reactant', ...
'product', ...
'modifier', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
'sboTerm', ...
'isSetFast', ...
};
nNumberFields = 14;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'reactant', ...
'product', ...
'modifier', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
'isSetFast', ...
};
nNumberFields = 14;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'reactant', ...
'product', ...
'modifier', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
'isSetFast', ...
};
nNumberFields = 14;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'reactant', ...
'product', ...
'modifier', ...
'kineticLaw', ...
'reversible', ...
'fast', ...
'isSetFast', ...
'compartment', ...
};
nNumberFields = 15;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'type', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getSpeciesConcentrationRuleFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'type', ...
'formula', ...
'variable', ...
'species', ...
'compartment', ...
'name', ...
'units', ...
};
nNumberFields = 10;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 4 || version == 5)
SBMLfieldnames = [];
nNumberFields = 0;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getSpeciesFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'name', ...
'compartment', ...
'initialAmount', ...
'units', ...
'boundaryCondition', ...
'charge', ...
'isSetInitialAmount', ...
'isSetCharge', ...
};
nNumberFields = 11;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'compartment', ...
'initialAmount', ...
'initialConcentration', ...
'substanceUnits', ...
'spatialSizeUnits', ...
'hasOnlySubstanceUnits', ...
'boundaryCondition', ...
'charge', ...
'constant', ...
'isSetInitialAmount', ...
'isSetInitialConcentration', ...
'isSetCharge', ...
};
nNumberFields = 18;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'speciesType', ...
'compartment', ...
'initialAmount', ...
'initialConcentration', ...
'substanceUnits', ...
'spatialSizeUnits', ...
'hasOnlySubstanceUnits', ...
'boundaryCondition', ...
'charge', ...
'constant', ...
'isSetInitialAmount', ...
'isSetInitialConcentration', ...
'isSetCharge', ...
};
nNumberFields = 19;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'speciesType', ...
'compartment', ...
'initialAmount', ...
'initialConcentration', ...
'substanceUnits', ...
'hasOnlySubstanceUnits', ...
'boundaryCondition', ...
'charge', ...
'constant', ...
'isSetInitialAmount', ...
'isSetInitialConcentration', ...
'isSetCharge', ...
};
nNumberFields = 19;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'speciesType', ...
'compartment', ...
'initialAmount', ...
'initialConcentration', ...
'substanceUnits', ...
'hasOnlySubstanceUnits', ...
'boundaryCondition', ...
'charge', ...
'constant', ...
'isSetInitialAmount', ...
'isSetInitialConcentration', ...
'isSetCharge', ...
};
nNumberFields = 19;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'compartment', ...
'initialAmount', ...
'initialConcentration', ...
'substanceUnits', ...
'hasOnlySubstanceUnits', ...
'boundaryCondition', ...
'constant', ...
'isSetInitialAmount', ...
'isSetInitialConcentration', ...
'conversionFactor', ...
};
nNumberFields = 17;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getSpeciesReferenceFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'species', ...
'stoichiometry', ...
'denominator', ...
};
nNumberFields = 6;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'species', ...
'stoichiometry', ...
'denominator', ...
'stoichiometryMath', ...
};
nNumberFields = 8;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'species', ...
'id', ...
'name', ...
'sboTerm', ...
'stoichiometry', ...
'stoichiometryMath', ...
};
nNumberFields = 10;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
'stoichiometry', ...
'stoichiometryMath', ...
};
nNumberFields = 10;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
'stoichiometry', ...
'stoichiometryMath', ...
};
nNumberFields = 10;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'species', ...
'id', ...
'name', ...
'stoichiometry', ...
'constant', ...
'isSetStoichiometry', ...
};
nNumberFields = 11;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getSpeciesTypeFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
};
nNumberFields = 6;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
};
nNumberFields = 7;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
};
nNumberFields = 7;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getStoichiometryMathFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getTriggerFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'math', ...
};
nNumberFields = 6;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'persistent', ...
'initialValue', ...
'math', ...
};
nNumberFields = 8;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getUnitDefinitionFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'name', ...
'unit', ...
};
nNumberFields = 5;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'unit', ...
};
nNumberFields = 7;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'name', ...
'id', ...
'unit', ...
};
nNumberFields = 7;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'unit', ...
};
nNumberFields = 8;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'unit', ...
};
nNumberFields = 8;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'name', ...
'id', ...
'unit', ...
};
nNumberFields = 8;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getUnitFieldnames(level, ...
version)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
if (level == 1)
SBMLfieldnames = { 'typecode', ...
'notes', ...
'annotation', ...
'kind', ...
'exponent', ...
'scale', ...
};
nNumberFields = 6;
elseif (level == 2)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'kind', ...
'exponent', ...
'scale', ...
'multiplier', ...
'offset', ...
};
nNumberFields = 9;
elseif (version == 2)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'kind', ...
'exponent', ...
'scale', ...
'multiplier', ...
};
nNumberFields = 8;
elseif (version == 3)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'kind', ...
'exponent', ...
'scale', ...
'multiplier', ...
};
nNumberFields = 9;
elseif (version == 4 || version == 5)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'kind', ...
'exponent', ...
'scale', ...
'multiplier', ...
};
nNumberFields = 9;
end;
elseif (level == 3)
if (version == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'kind', ...
'exponent', ...
'scale', ...
'multiplier', ...
};
nNumberFields = 9;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFBCModelFieldnames(level, ...
version, pkgVersion)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
% need a check on package version
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
if (pkgVersion == 1)
SBMLfieldnames = { 'fbc_version', ...
'fbc_fluxBound', ...
'fbc_objective', ...
'fbc_activeObjective', ...
};
nNumberFields = 4;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFBCSpeciesFieldnames(level, ...
version, pkgVersion)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
% need a check on package version
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
if (pkgVersion == 1)
SBMLfieldnames = { 'fbc_charge', ...
'isSetfbc_charge', ...
'fbc_chemicalFormula', ...
'fbc_version', ...
};
nNumberFields = 4;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFluxBoundFieldnames(level, ...
version, pkgVersion)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
% need a check on package version
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
if (pkgVersion == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'fbc_id', ...
'fbc_reaction', ...
'fbc_operation', ...
'fbc_value', ...
'isSetfbc_value', ...
'level', ...
'version', ...
'fbc_version', ...
};
nNumberFields = 13;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getFluxObjectiveFieldnames(level, ...
version, pkgVersion)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
% need a check on package version
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
if (pkgVersion == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'fbc_reaction', ...
'fbc_coefficient', ...
'isSetfbc_coefficient', ...
'level', ...
'version', ...
'fbc_version', ...
};
nNumberFields = 11;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SBMLfieldnames, nNumberFields] = getObjectiveFieldnames(level, ...
version, pkgVersion)
if (~isValidLevelVersionCombination(level, version))
error ('invalid level/version combination');
end;
% need a check on package version
if (level == 1)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 2)
SBMLfieldnames = [];
nNumberFields = 0;
elseif (level == 3)
if (version == 1)
if (pkgVersion == 1)
SBMLfieldnames = { 'typecode', ...
'metaid', ...
'notes', ...
'annotation', ...
'sboTerm', ...
'fbc_id', ...
'fbc_type', ...
'fbc_fluxObjective', ...
'level', ...
'version', ...
'fbc_version', ...
};
nNumberFields = 11;
end;
end;
end;
|
github | compneuro-da/rsHRF-master | rsHRF_mvgc.m | .m | rsHRF-master/rsHRF_mvgc.m | 14,061 | utf_8 | 288e227bc8fac13e21ff0084b5cd9265 | function [F,pvalue] = rsHRF_mvgc(data,order,regmode,flag_1to2,flag_pvalue)
% Calculate time-domain multivariate Granger causalities
% data: nvars x nobs x ntrials
% F(i,j): from i to j.
% pvalue: F-test.
%
%% References
% [1] L. Barnett and A. K. Seth, The MVGC The MVGC multivariate Granger causality toolbox:
% A new approach to Granger-causal inference. J. Neurosci. Methods 223, 2014
% [2] X. Kitagawa, An algorithm for solving the matrix equation X = F X F'+S,
% Internat. J. Control 25(5), 1977.
% [3] S. Hammarling, "Numerical solution of the stable, non-negative definite
% Lyapunov equation", IMA J. Numer. Anal. 2, 1982.
[nvars,nobs,ntrials] = size(data);
% full regression
% owstate = warn_supp;
[G,SIG,info] = data_to_autocov(data,order,regmode);
% warn_test(owstate, 'in full regression - bad autocovariance matrix? Check output of ''var_info''');
% if warn_if(isbad(SIG),'in full regression - regression failed'), return; end % show-stopper!
if ~flag_1to2
F = nan(nvars);
pvalue = nan(nvars);
else
F = NaN;
pvalue = nan;
end
% var_info(info,true); % report results (and bail out on error)
if info.error
fprintf('.')
else
LSIG = log(diag(SIG));
for j = 1:nvars
% reduced regression
jo = [1:j-1 j+1:nvars]; % omit j
% owstate = warn_supp;
[~,SIGj] = autocov_to_var(G(jo,jo,:));
% warn_test(owstate, sprintf('in reduced regression for target node %d - bad autocovariance matrix? Check output of ''var_info''',j));
% if warn_if(isbad(SIGj),sprintf('in reduced regression for target node %d - regression failed',j)), continue; end % show-stopper!
LSIGj = log(diag(SIGj));
if flag_1to2
F = LSIGj(1)-LSIG(2); break
else
for ii=1:nvars-1
i = jo(ii);
F(j,i) = LSIGj(ii)-LSIG(i);
end
end
end
if flag_pvalue
tstat = '';
pvalue = mvgc_pval(F,order,nobs,ntrials,1,1,nvars-2,tstat); % take careful note of arguments!
end
end
function [G,SIG,info] = data_to_autocov(X,p,regmode)
if nargin < 3 || isempty(regmode), regmode = 'LWR'; end
[n,m,N] = size(X);
assert(p < m,'too many lags');
p1 = p+1;
A = NaN;
SIG = NaN;
G = NaN;
info.error = 1;
X = demean(X); % no constant term
if strcmpi(regmode,'OLS') % OLS (QR decomposition)
M = N*(m-p);
np = n*p;
% stack lags
X0 = reshape(X(:,p1:m,:),n,M); % concatenate trials for unlagged observations
XL = zeros(n,p,M);
for k = 1:p
XL(:,k,:) = reshape(X(:,p1-k:m-k,:),n,M); % concatenate trials for k-lagged observations
end
XL = reshape(XL,np,M); % stack lags
A = X0/XL; % OLS using QR decomposition
if isbad(A); return; end % something went badly wrong
if nargout > 1
E = X0-A*XL; % residuals
SIG = (E*E')/(M-1); % residuals covariance matrix
E = reshape(E,n,m-p,N); % put residuals back into per-trial form
end
A = reshape(A,n,n,p); % so A(:,:,k) is the k-lag coefficients matrix
elseif strcmpi(regmode,'LWR') % LWR (Morf)
q1n = p1*n;
I = eye(n);
% store lags
XX = zeros(n,p1,m+p,N);
for k = 0:p
XX(:,k+1,k+1:k+m,:) = X; % k-lagged observations
end
% initialise recursion
AF = zeros(n,q1n); % forward AR coefficients
AB = zeros(n,q1n); % backward AR coefficients (reversed compared with Morf's treatment)
k = 1; % model order is k-1
kn = k*n;
M = N*(m-k);
kf = 1:kn; % forward indices
kb = q1n-kn+1:q1n; % backward indices
XF = reshape(XX(:,1:k,k+1:m,:),kn,M);
XB = reshape(XX(:,1:k,k:m-1,:),kn,M);
[CXF,cholp] = chol(XF*XF');
if cholp, return; end % show-stopper!
[CXB,cholp] = chol(XB*XB');
if cholp, return; end % show-stopper!
AF(:,kf) = CXF'\I;
AB(:,kb) = CXB'\I;
% and loop
while k <= p
EF = AF(:,kf)*reshape(XX(:,1:k,k+1:m,:),kn,M); % forward prediction errors
EB = AB(:,kb)*reshape(XX(:,1:k,k:m-1,:),kn,M); % backward prediction errors
[CEF,cholp] = chol(EF*EF');
if cholp, return; end % show-stopper!
[CEB,cholp] = chol(EB*EB');
if cholp, return; end % show-stopper!
R = CEF'\(EF*EB')/CEB; % normalised reflection coefficients
[RF,cholp] = chol(I-R*R');
if cholp, return; end % show-stopper!
[RB,cholp] = chol(I-R'*R);
if cholp, return; end % show-stopper!
k = k+1;
kn = k*n;
M = N*(m-k);
kf = 1:kn;
kb = q1n-kn+1:q1n;
AFPREV = AF(:,kf);
ABPREV = AB(:,kb);
AF(:,kf) = RF'\(AFPREV-R*ABPREV);
AB(:,kb) = RB'\(ABPREV-R'*AFPREV);
end
if nargout > 1
E = AFPREV(:,1:n)\EF; % residuals
SIG = (E*E')/(M-1); % residuals covariance matrix
E = reshape(E,n,m-p,N); % put residuals back into per-trial form
end
A = reshape(-AF(:,1:n)\AF(:,n+1:end),n,n,p); % so A(:,:,k) is the k-lag coefficients matrix
else
error('bad regression mode ''%s''\n',regmode);
end
% Autocovariance calculation
[G,info] = var_to_autocov(A,SIG);
function Y = demean(X,normalise)
if nargin < 2 || isempty(normalise), normalise = false; end
[n,m,N] = size(X);
U = ones(1,N*m);
Y = X(:,:);
Y = Y-mean(Y,2)*U;
if normalise
Y = Y./(std(Y,[],2)*U);
end
Y = reshape(Y,n,m,N);
function b = isbad(x,demand_allfinite)
if nargin < 2 || isempty(demand_allfinite), demand_allfinite = true; end
if demand_allfinite
b = ~all(isfinite(x(:)));
else
b = ~any(isfinite(x(:)));
end
function [G,info] = var_to_autocov(A,SIG,acmaxlags,acdectol,aitr,maxiters,maxrelerr)
%global have_dlyap;
% default parameters
if nargin < 3 || isempty(acmaxlags), acmaxlags = 0; end % calculate maximum lags automatically
if nargin < 4 || isempty(acdectol), acdectol = 1e-8; end % autocovariance decay tolerance
if nargin < 5 || isempty(aitr), aitr = false; end % use "accelerated" iterative Lyapunov equation solver
% iterative algorithm only: ensure defaults for utils/dlyap_aitr.m.
if nargin < 6, maxiters = []; end
if nargin < 7, maxrelerr = []; end
[n,n1,p] = size(A);
assert(n1 == n,'VAR coefficients matrix has bad shape');
pn1 = (p-1)*n;
[nn1,nn2] = size(SIG);
assert(nn1 == nn2,'residuals covariance matrix not square');
assert(nn1 == n ,'residuals covariance matrix doesn''t match VAR coefficients matrix');
% initialise info struct
info.error = 0;
info.errmsg = '';
info.warnings = 0;
info.warnmsg = cell(0,1);
info.rho = NaN;
info.iters = NaN;
info.acrelerr = NaN;
info.acminlags = NaN;
info.aclags = NaN;
G = [];
% construct VAR coefficients for 1-lag problem
A1 = [reshape(A,n,p*n); eye(pn1) zeros(pn1,n)];
% calculate spectral radius
try
info.rho = max(abs(eig(A1)));
catch
info.error = 1;
info.errmsg = 'eig(Input matrix contains NaN or Inf.)';
return
end
if info.rho >= 1
info.error = 1;
info.errmsg = 'unstable VAR (unit root)';
return
end
% construct residual covariances for 1-lag problem
if ~isposdef(SIG);
info.error = 2;
info.errmsg = 'residuals covariance matrix not positive-definite';
return;
end
SIG1 = [SIG zeros(n,pn1); zeros(pn1,n) zeros(pn1)];
% solve the Lyapunov equation for the 1-lag covariance matrix
try
if aitr
[G1,info.iters] = dlyap_aitr(A1,SIG1,maxiters,maxrelerr); % experimental: fast, but needs more testing
else
% G1 = dlyap(A1,SIG1); % dlyap seems to work better here without balancing, which seems to break positive-definitiveness
G1 = lyapslv('D',A1,[],-SIG1); % sometimes. However lyapslv is not an official interface, so this could conceivably break in future.
end
catch except
info.error = 3;
info.errmsg = ['Lyapunov equation solver failed: ' except.message];
return
end
info.acrelerr = norm(A1*G1*A1'-G1+SIG1)/norm(SIG1); % this should be small (see below)
maxacrelerr = 1e-8; % probably shouldn't be hard-coded :-/
if info.acrelerr > maxacrelerr
info.warnings = info.warnings+1;
info.warnmsg{info.warnings} = sprintf('large relative error = %g (tolerance = %g)',info.acrelerr,maxacrelerr);
end
% estimate number of autocov lags
info.acminlags = ceil(log(acdectol)/log(info.rho)); % minimum lags to achieve specified tolerance
if acmaxlags < 0 % use exactly -acmaxlags lags (not encouraged, hence undocumented!)
info.aclags = -acmaxlags;
elseif acmaxlags > 0 % use at most acmaxlags lags
info.aclags = min(info.acminlags,acmaxlags);
else % acmaxlags == 0 - use minimum acceptable lags (recommended)
info.aclags = info.acminlags;
end
if info.aclags < info.acminlags
info.warnings = info.warnings+1;
info.warnmsg{info.warnings} = sprintf('too few autocovariance lags = %d (minimum = %d)',info.aclags,info.acminlags);
end
if ~isposdef(G1);
info.error = 4;
info.errmsg = '1-lag covariance matrix not positive-definite';
return
end
q = info.aclags;
q1 = q+1;
% calculate recursively from 1-lag solution (which supplies up to p-1 lags), from p lags up to q
[n,~,p] = size(A);
assert(info.aclags >= p,'number of lags is too small'); % lags must be at least number of VAR lags
pn = p*n;
G = cat(3,reshape(G1(1:n,:),n,n,p),zeros(n,n,q1-p)); % autocov forward sequence
B = [zeros((q1-p)*n,n); G1(:,end-n+1:end)]; % autocov backward sequence
A = reshape(A,n,pn); % coefficients
for k = p:q
r = q1-k;
G(:,:,k+1) = A*B(r*n+1:r*n+pn,:);
B((r-1)*n+1:r*n,:) = G(:,:,k+1);
end
function pd = isposdef(A)
[~,p] = chol(A);
pd = ~(p > 0);
function [AF,SIG] = autocov_to_var(G)
[n,~,q1] = size(G);
q = q1-1;
qn = q*n;
G0 = G(:,:,1); % covariance
GF = reshape(G(:,:,2:end),n,qn)'; % forward autocov sequence
GB = reshape(permute(flipdim(G(:,:,2:end),3),[1 3 2]),qn,n); % backward autocov sequence
AF = zeros(n,qn); % forward coefficients
AB = zeros(n,qn); % backward coefficients (reversed compared with Whittle's treatment)
% initialise recursion
k = 1; % model order
r = q-k;
kf = 1:k*n; % forward indices
kb = r*n+1:qn; % backward indices
AF(:,kf) = GB(kb,:)/G0;
AB(:,kb) = GF(kf,:)/G0;
% and loop
for k=2:q
AAF = (GB((r-1)*n+1:r*n,:)-AF(:,kf)*GB(kb,:))/(G0-AB(:,kb)*GB(kb,:)); % DF/VB
AAB = (GF((k-1)*n+1:k*n,:)-AB(:,kb)*GF(kf,:))/(G0-AF(:,kf)*GF(kf,:)); % DB/VF
AFPREV = AF(:,kf);
ABPREV = AB(:,kb);
r = q-k;
kf = 1:k*n;
kb = r*n+1:qn;
AF(:,kf) = [AFPREV-AAF*ABPREV AAF];
AB(:,kb) = [AAB ABPREV-AAB*AFPREV];
end
if nargout > 1
SIG = G0-AF*GF;
end
AF = reshape(AF,n,n,q);
function pval = mvgc_pval(x,p,m,N,nx,ny,nz,tstat)
if nargin < 7, nz = []; end % ensure default
if nargin < 8, tstat = []; end % ensure default
pval = NaN(size(x)); % output p-value matrix is same shape as x matrix
nn = ~isnan(x); % indices of non-NaN x values (logical array)
x = x(nn); % vectorise non-NaN x values
pval(nn) = 1-mvgc_cdf(x,0,p,m,N,nx,ny,nz,tstat); % assume null hypothesis F = 0
function P = mvgc_cdf(x,X,p,m,N,nx,ny,nz,tstat)
assert(isvector(x),'evaluation values must be a vector');
n = length(x);
assert(isvector(X),'MVGC values must be a vector');
assert(all(X >= 0),'MVGC values must be non-negative');
if isscalar(X)
X = X*ones(n,1);
else
assert(length(X) == n,'MVGC values must match evaluation values');
end
if nargin < 8 || isempty(nz), nz = 0; end % unconditional
if nargin < 9 || isempty(tstat);
ftest = nx == 1; % default: use F-distribution for univariate predictee, chi2 for multivariate
else
switch lower(tstat)
case 'f' % Granger F-test form
assert(nx == 1,'F-distribution is not appropriate for multivariate predictee');
ftest = true;
case 'chi2' % Geweke chi2 test form
ftest = false;
otherwise
error('unknown distribution (must be ''chi2'' or ''F'')');
end
end
P = zeros(n,1);
m = N*(m-p); % effective number of observations (p-lag autoregression loses p observations per trial)
if ftest
if any(X > 0), fprintf(2,'WARNING (mvgc_cdf): non-central F-distribution is experimental\n'); end
d1 = p*ny; % #{full model parameters} - #{reduced model parameters}
d2 = m-p*(1+ny+nz); % #{observations} - #{full model parameters}
mm = d2/d1;
for i = 1:n
xx = exp(x(i))-1; % Granger form: (RSS_reduced - RSS_full) / RSS_full
if X(i) > 0 % non-central
XX = exp(X(i))-1; % Granger form
P(i) = ncfcdf(mm*xx,d1,d2,m*XX); % NOTE: non-centrality parameter factor might reasonably be m, d2 or d2-2
else
P(i) = fcdf(mm*xx,d1,d2);
end
end
else
d = p*nx*ny; % note that d does not depend on the number of conditioning variables
for i = 1:n
if X(i) > 0 % non-central
P(i) = ncx2cdf(m*x(i),d,m*X(i));
else
P(i) = chi2cdf(m*x(i),d);
end
end
end
function [X,iters] = dlyap_aitr(A,Q,maxiters,maxrelerr)
if nargin < 3 || isempty(maxiters), maxiters = 100; end
if nargin < 4 || isempty(maxrelerr), maxrelerr = 1e-8; end
assert(size(A,2) == size(A,1),'matrix A not square');
assert(isequal(size(Q),size(A)),'matrix Q does not match matrix A');
X = Q;
AA = A;
snorm = norm(Q,'fro');
minrelerr = realmax;
for iters = 1:maxiters+1
relerr = norm(X-A*X*A'-Q,'fro')/snorm;
if relerr < maxrelerr % only start convergence test after max rel error threshold reached
if relerr >= minrelerr, break; end % deemed converged
end
if relerr < minrelerr, minrelerr = relerr; end
X = AA*X*AA'+X;
AA = AA*AA;
end
if iters > maxiters
throw(MException('MVGC:XMaxItrs','exceeded maximum iterations (max. rel. error = %e)',relerr));
end
|
github | compneuro-da/rsHRF-master | rsHRF_inpaint_nans3.m | .m | rsHRF-master/rsHRF_inpaint_nans3.m | 8,268 | utf_8 | 312e077493b6496d54e1e9bc634bab03 | function B=rsHRF_inpaint_nans3(A,method)
% INPAINT_NANS3: in-paints over nans in a 3-D array
% usage: B=INPAINT_NANS3(A) % default method (0)
% usage: B=INPAINT_NANS3(A,method) % specify method used
%
% Solves approximation to a boundary value problem to
% interpolate and extrapolate holes in a 3-D array.
%
% Note that if the array is large, and there are many NaNs
% to be filled in, this may take a long time, or run into
% memory problems.
%
% arguments (input):
% A - n1 x n2 x n3 array with some NaNs to be filled in
%
% method - (OPTIONAL) scalar numeric flag - specifies
% which approach (or physical metaphor to use
% for the interpolation.) All methods are capable
% of extrapolation, some are better than others.
% There are also speed differences, as well as
% accuracy differences for smooth surfaces.
%
% method 0 uses a simple plate metaphor.
% method 1 uses a spring metaphor.
%
% method == 0 --> (DEFAULT) Solves the Laplacian
% equation over the set of nan elements in the
% array.
% Extrapolation behavior is roughly linear.
%
% method == 1 --+ Uses a spring metaphor. Assumes
% springs (with a nominal length of zero)
% connect each node with every neighbor
% (horizontally, vertically and diagonally)
% Since each node tries to be like its neighbors,
% extrapolation is roughly a constant function where
% this is consistent with the neighboring nodes.
%
% There are only two different methods in this code,
% chosen as the most useful ones (IMHO) from my
% original inpaint_nans code.
%
%
% arguments (output):
% B - n1xn2xn3 array with NaNs replaced
%
%
% Example:
% % A linear function of 3 independent variables,
% % used to test whether inpainting will interpolate
% % the missing elements correctly.
% [x,y,z] = ndgrid(-10:10,-10:10,-10:10);
% W = x + y + z;
%
% % Pick a set of distinct random elements to NaN out.
% ind = unique(ceil(rand(3000,1)*numel(W)));
% Wnan = W;
% Wnan(ind) = NaN;
%
% % Do inpainting
% Winp = inpaint_nans3(Wnan,0);
%
% % Show that the inpainted values are essentially
% % within eps of the originals.
% std(Winp(ind) - W(ind))
% ans =
% 4.3806e-15
%
%
% See also: griddatan, inpaint_nans
%
% Author: John D'Errico
% e-mail address: [email protected]
% Release: 1
% Release date: 8/21/08
% Need to know which elements are NaN, and
% what size is the array. Unroll A for the
% inpainting, although inpainting will be done
% fully in 3-d.
NA = size(A);
A = A(:);
nt = prod(NA);
k = isnan(A(:));
% list the nodes which are known, and which will
% be interpolated
nan_list=find(k);
known_list=find(~k);
% how many nans overall
nan_count=length(nan_list);
% convert NaN indices to (r,c) form
% nan_list==find(k) are the unrolled (linear) indices
% (row,column) form
[n1,n2,n3]=ind2sub(NA,nan_list);
% both forms of index for all the nan elements in one array:
% column 1 == unrolled index
% column 2 == index 1
% column 3 == index 2
% column 4 == index 3
nan_list=[nan_list,n1,n2,n3];
% supply default method
if (nargin<2) || isempty(method)
method = 0;
elseif ~ismember(method,[0 1])
error 'If supplied, method must be one of: {0,1}.'
end
% alternative methods
switch method
case 0
% The same as method == 1, except only work on those
% elements which are NaN, or at least touch a NaN.
% horizontal and vertical neighbors only
talks_to = [-1 0 0;1 0 0;0 -1 0;0 1 0;0 0 -1;0 0 1];
neighbors_list=identify_neighbors(NA,nan_list,talks_to);
% list of all nodes we have identified
all_list=[nan_list;neighbors_list];
% generate sparse array with second partials on row
% variable for each element in either list, but only
% for those nodes which have a row index > 1 or < n
L = find((all_list(:,2) > 1) & (all_list(:,2) < NA(1)));
nL=length(L);
if nL>0
fda=sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-1 0 1],nL,1), ...
repmat([1 -2 1],nL,1),nt,nt);
else
fda=spalloc(nt,nt,size(all_list,1)*7);
end
% 2nd partials on column index
L = find((all_list(:,3) > 1) & (all_list(:,3) < NA(2)));
nL=length(L);
if nL>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-NA(1) 0 NA(1)],nL,1), ...
repmat([1 -2 1],nL,1),nt,nt);
end
% 2nd partials on third index
L = find((all_list(:,4) > 1) & (all_list(:,4) < NA(3)));
nL=length(L);
if nL>0
ntimesm = NA(1)*NA(2);
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-ntimesm 0 ntimesm],nL,1), ...
repmat([1 -2 1],nL,1),nt,nt);
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list(:,1)),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 1
% Spring analogy
% interpolating operator.
% list of all springs between a node and a horizontal
% or vertical neighbor
hv_list=[-1 -1 0 0;1 1 0 0;-NA(1) 0 -1 0;NA(1) 0 1 0; ...
-NA(1)*NA(2) 0 0 -1;NA(1)*NA(2) 0 0 1];
hv_springs=[];
for i=1:size(hv_list,1)
hvs=nan_list+repmat(hv_list(i,:),nan_count,1);
k=(hvs(:,2)>=1) & (hvs(:,2)<=NA(1)) & ...
(hvs(:,3)>=1) & (hvs(:,3)<=NA(2)) & ...
(hvs(:,4)>=1) & (hvs(:,4)<=NA(3));
hv_springs=[hv_springs;[nan_list(k,1),hvs(k,1)]];
end
% delete replicate springs
hv_springs=unique(sort(hv_springs,2),'rows');
% build sparse matrix of connections
nhv=size(hv_springs,1);
springs=sparse(repmat((1:nhv)',1,2),hv_springs, ...
repmat([1 -1],nhv,1),nhv,prod(NA));
% eliminate knowns
rhs=-springs(:,known_list)*A(known_list);
% and solve...
B=A;
B(nan_list(:,1))=springs(:,nan_list(:,1))\rhs;
end
% all done, make sure that B is the same shape as
% A was when we came in.
B=reshape(B,NA);
% ====================================================
% end of main function
% ====================================================
% ====================================================
% begin subfunctions
% ====================================================
function neighbors_list=identify_neighbors(NA,nan_list,talks_to)
% identify_neighbors: identifies all the neighbors of
% those nodes in nan_list, not including the nans
% themselves
%
% arguments (input):
% NA - 1x3 vector = size(A), where A is the
% array to be interpolated
% nan_list - array - list of every nan element in A
% nan_list(i,1) == linear index of i'th nan element
% nan_list(i,2) == row index of i'th nan element
% nan_list(i,3) == column index of i'th nan element
% nan_list(i,4) == third index of i'th nan element
% talks_to - px2 array - defines which nodes communicate
% with each other, i.e., which nodes are neighbors.
%
% talks_to(i,1) - defines the offset in the row
% dimension of a neighbor
% talks_to(i,2) - defines the offset in the column
% dimension of a neighbor
%
% For example, talks_to = [-1 0;0 -1;1 0;0 1]
% means that each node talks only to its immediate
% neighbors horizontally and vertically.
%
% arguments(output):
% neighbors_list - array - list of all neighbors of
% all the nodes in nan_list
if ~isempty(nan_list)
% use the definition of a neighbor in talks_to
nan_count=size(nan_list,1);
talk_count=size(talks_to,1);
nn=zeros(nan_count*talk_count,3);
j=[1,nan_count];
for i=1:talk_count
nn(j(1):j(2),:)=nan_list(:,2:4) + ...
repmat(talks_to(i,:),nan_count,1);
j=j+nan_count;
end
% drop those nodes which fall outside the bounds of the
% original array
L = (nn(:,1)<1) | (nn(:,1)>NA(1)) | ...
(nn(:,2)<1) | (nn(:,2)>NA(2)) | ...
(nn(:,3)<1) | (nn(:,3)>NA(3));
nn(L,:)=[];
% form the same format 4 column array as nan_list
neighbors_list=[sub2ind(NA,nn(:,1),nn(:,2),nn(:,3)),nn];
% delete replicates in the neighbors list
neighbors_list=unique(neighbors_list,'rows');
% and delete those which are also in the list of NaNs.
neighbors_list=setdiff(neighbors_list,nan_list,'rows');
else
neighbors_list=[];
end
|
github | compneuro-da/rsHRF-master | rsHRF_band_filter.m | .m | rsHRF-master/rsHRF_band_filter.m | 1,907 | utf_8 | 0a42ce81cbe9a24d88c672994eebab72 | function x = rsHRF_band_filter(x,TR,Bands,m)
% data: x nobs*nvar
if nargin<4
m = 5000; %block size
end
nvar = size(x,2);
nbin = ceil(nvar/m);
for i=1:nbin
if i~=nbin
ind_X = (i-1)*m+1:i*m ;
else
ind_X = (i-1)*m+1:nvar ;
end
x1 = x(:,ind_X);
x1 = conn_filter(TR,Bands,x1,'full') +...%mean-center by default
repmat(mean(x1,1),size(x1,1),1); %mean back in
x(:,ind_X) = x1;
end
clear x1;
function [y,fy]=conn_filter(rt,filter,x,option)
% from CONN toolbox, www.conn-toolbox.org
USEDCT=true;
if nargin<4, option='full'; end
if strcmpi(option,'base'), Nx=x; x=eye(Nx); end
if USEDCT % discrete cosine basis
Nx=size(x,1);
fy=fft(cat(1,x,flipud(x)),[],1);
f=(0:size(fy,1)-1);
f=min(f,size(fy,1)-f);
switch(lower(option))
case {'full','base'}
idx=find(f<filter(1)*(rt*size(fy,1))|f>=filter(2)*(rt*size(fy,1)));
%idx=idx(idx>1);
fy(idx,:)=0;
k=1; %2*size(fy,1)*(min(.5,filter(2)*rt)-max(0,filter(1)*rt))/max(1,size(fy,1)-numel(idx));
y=real(ifft(fy,[],1))*k;
y=y(1:Nx,:);
case 'partial'
idx=find(f>=filter(1)*(rt*size(x,1))&f<filter(2)*(rt*size(x,1)));
%if ~any(idx==1), idx=[1,idx]; end
y=fy(idx,:);
end
else % discrete fourier basis
fy=fft(x,[],1);
f=(0:size(fy,1)-1);
f=min(f,size(fy,1)-f);
switch(lower(option))
case 'full'
idx=find(f<filter(1)*(rt*size(fy,1))|f>=filter(2)*(rt*size(fy,1)));
%idx=idx(idx>1);
fy(idx,:)=0;
k=1; %2*size(fy,1)*(min(.5,filter(2)*rt)-max(0,filter(1)*rt))/max(1,size(fy,1)-numel(idx));
y=real(ifft(fy,[],1))*k;
case 'partial'
idx=find(f>=filter(1)*(rt*size(x,1))&f<filter(2)*(rt*size(x,1)));
%if ~any(idx==1), idx=[1,idx]; end
y=fy(idx,:);
end
end |
github | compneuro-da/rsHRF-master | rsHRF_deleteoutliers.m | .m | rsHRF-master/rsHRF_deleteoutliers.m | 3,398 | utf_8 | afbe5d17fc43047bd25f0386a8ff14b3 | function [b,idx,outliers] = rsHRF_deleteoutliers(a,alpha,rep);
% [B, IDX, OUTLIERS] = DELETEOUTLIERS(A, ALPHA, REP)
%
% For input vector A, returns a vector B with outliers (at the significance
% level alpha) removed. Also, optional output argument idx returns the
% indices in A of outlier values. Optional output argument outliers returns
% the outlying values in A.
%
% ALPHA is the significance level for determination of outliers. If not
% provided, alpha defaults to 0.05.
%
% REP is an optional argument that forces the replacement of removed
% elements with NaNs to presereve the length of a. (Thanks for the
% suggestion, Urs.)
%
% This is an iterative implementation of the Grubbs Test that tests one
% value at a time. In any given iteration, the tested value is either the
% highest value, or the lowest, and is the value that is furthest
% from the sample mean. Infinite elements are discarded if rep is 0, or
% replaced with NaNs if rep is 1 (thanks again, Urs).
%
% Appropriate application of the test requires that data can be reasonably
% approximated by a normal distribution. For reference, see:
% 1) "Procedures for Detecting Outlying Observations in Samples," by F.E.
% Grubbs; Technometrics, 11-1:1--21; Feb., 1969, and
% 2) _Outliers in Statistical Data_, by V. Barnett and
% T. Lewis; Wiley Series in Probability and Mathematical Statistics;
% John Wiley & Sons; Chichester, 1994.
% A good online discussion of the test is also given in NIST's Engineering
% Statistics Handbook:
% http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm
%
% ex:
% [B,idx,outliers] = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2], 0.05)
% returns:
% B = 1.1000 1.3000 0.9000 1.2000 1.2000 0.9400 1.3000 1.0000 1.3000 1.2000
% idx = 5 8 11
% outliers = -6.4000 4.2000 6.8000
%
% ex:
% B = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2
% Inf 1.2 -Inf 1.1], 0.05, 1)
% returns:
% B = 1.1000 1.3000 0.9000 1.2000 NaN 1.2000 0.9400 NaN 1.3000 1.0000 NaN 1.3000 1.2000 NaN 1.2000 NaN 1.1000
% Written by Brett Shoelson, Ph.D.
% [email protected]
% 9/10/03
% Modified 9/23/03 to address suggestions by Urs Schwartz.
% Modified 10/08/03 to avoid errors caused by duplicate "maxvals."
% (Thanks to Valeri Makarov for modification suggestion.)
if nargin == 1
alpha = 0.05;
rep = 0;
elseif nargin == 2
rep = 0;
elseif nargin == 3
if ~ismember(rep,[0 1])
error('Please enter a 1 or a 0 for optional argument rep.')
end
elseif nargin > 3
error('Requires 1,2, or 3 input arguments.');
end
if isempty(alpha)
alpha = 0.05;
end
b = a;
b(isinf(a)) = NaN;
%Delete outliers:
outlier = 1;
while outlier
tmp = b(~isnan(b));
meanval = mean(tmp);
maxval = tmp(find(abs(tmp-mean(tmp))==max(abs(tmp-mean(tmp)))));
maxval = maxval(1);
sdval = std(tmp);
tn = abs((maxval-meanval)/sdval);
critval = zcritical(alpha,length(tmp));
outlier = tn > critval;
if outlier
tmp = find(a == maxval);
b(tmp) = NaN;
end
end
if nargout >= 2
idx = find(isnan(b));
end
if nargout > 2
outliers = a(idx);
end
if ~rep
b=b(~isnan(b));
end
return
function zcrit = zcritical(alpha,n)
%ZCRIT = ZCRITICAL(ALPHA,N)
% Computes the critical z value for rejecting outliers (GRUBBS TEST)
tcrit = tinv(alpha/(2*n),n-2);
zcrit = (n-1)/sqrt(n)*(sqrt(tcrit^2/(n-2+tcrit^2)));
|
github | compneuro-da/rsHRF-master | rsHRF_ROI_sig_job.m | .m | rsHRF-master/rsHRF_ROI_sig_job.m | 2,097 | utf_8 | 4fa12ffe69a0327b9e3b1ead60f2170d | function rsHRF_ROI_sig_job(job)
ROI = job.Datasig; %cell file
[data_txt,mat_name]= rsHRF_check_ROIsig(ROI);
tmp = data_txt(:,1);
if job.para_global.combine_ROI
data = cell2mat(tmp'); % combine all ROI together
tmp={}; tmp{1} = data;
[~,outname,~] = fileparts(data_txt{1,2});
fprintf('Combine all input ROIs for connectivity analysis, output is "*comb_%s*.mat"\n',outname)
end
nROI = length(tmp);
for i=1:nROI
data = tmp{i};
if isempty(data_txt{1,2})
error('No data input!')
else
[fpath,name,~] = fileparts(data_txt{1,2});
if job.para_global.combine_ROI
job.raw_outname = ['combROI_',name];
else
if isempty(mat_name{i})
job.raw_outname = name;
else
job.raw_outname = [name,'_',mat_name{i}];
end
end
end
outdir = job.outdir{1};
if isempty(outdir)
outdir = fpath;
else
if ~exist(outdir,'dir')
mkdir(outdir)
end
end
[data,data_nuisancerm] = rsHRF_denoise_job(job,data);
flag_ROI = 1;
if isfield(job,'HRFE') % deconvolution
rsHRF_deconv_job(job,data,data_nuisancerm,flag_ROI, outdir);
else
rsHRF_conn_job(job,data,flag_ROI, outdir);
end
end
function [data_txt,var_name]= rsHRF_check_ROIsig(ROI)
nROI = length(ROI);
data_txt = cell(nROI,2);
var_name = cell(nROI,1);
for i=1:nROI
tmp2 = ROI(i).sigdata{1};
[~,~,ext] = fileparts(tmp2);
if strfind(ext,'txt')
data_txt{i,1} = load(tmp2);
data_txt{i,2} = tmp2;
elseif strfind(ext,'mat')
tmp3 = load(tmp2);
var_name{i} = strcat(ROI(i).name);
try
eval(['data_txt{i,1} = tmp3.',var_name{i},';']);
catch
tmp4 = fieldnames(tmp3);
if length(tmp4)==1
eval(['data_txt{i,1} = tmp3.',tmp4{1},';']);
else
error(['there are more than one variable in mat file, and no variable ''',var_name,'" in mat file']);
end
end
data_txt{i,2} = tmp2;
end
end |
github | compneuro-da/rsHRF-master | rsHRF_estimation_temporal_basis.m | .m | rsHRF-master/rsHRF_estimation_temporal_basis.m | 11,630 | utf_8 | 1f2b9bf962a3d78fb4dc5359a2f908e3 | function [beta_hrf, bf, event_bold] = rsHRF_estimation_temporal_basis(data,xBF,temporal_mask,flag_parfor)
% xBF.TR = 2;
% xBF.T = 8;
% xBF.T0 = fix(xBF.T/2); (reference time bin, see slice timing)
% xBF.dt = xBF.TR/xBF.T;
% xBF.AR_lag = 1;
% xBF.thr = 1;
% xBF.len = 25;
% xBF.localK = 2;
% temporal_mask: scrubbing mask.
% By: Guo-Rong Wu ([email protected]).
% Faculty of Psychology, Southwest University.
% History:
% - 2015-04-17 - Initial version.
% - 2018-07-18 - fix Warning: Rank deficient, copy code from regress.m
% addd AR_lag=0.
% set paramater for local peak detection.
% - 2019-08-01 - add temporal basis set (Fourier Set, Gamma function)
if nargin<4
flag_parfor = 1;
end
[N, nvar] = size(data);
if isnan(xBF.order)
para = rsHRF_global_para;
xBF.order = para.num_basis;
end
bf = wgr_spm_get_bf(xBF);
warning('off','all')
fprintf('#%d \n',nvar)
beta_hrf = cell(1,nvar);
event_bold= cell(1,nvar);
if flag_parfor
parfor i=1:nvar
[beta_hrf{1,i}, event_bold{i}] =wgr_hrf_estimation(data(:,i),xBF,N,bf,temporal_mask);
end
else
for i=1:nvar
[beta_hrf{1,i}, event_bold{i}] =wgr_hrf_estimation(data(:,i),xBF,N,bf,temporal_mask);
end
end
beta_hrf =cell2mat(beta_hrf);
warning on
return
function [bf] = wgr_spm_get_bf(xBF)
% Fill in basis function structure
% FORMAT [xBF] = spm_get_bf(xBF)
%
% xBF.dt - time bin length {seconds}
% xBF.name - description of basis functions specified
% 'Canonical HRF (with time derivative)'
% 'Canonical HRF (with time and dispersion derivatives)'
% 'Gamma functions'
% 'Fourier set'
% 'Fourier Set (Hanning)'
% xBF.T - microtime resolution (for 'Canonical HRF*')
% bf - array of basis functions
%__________________________________________________________________________
%
% spm_get_bf prompts for basis functions to model event or epoch-related
% responses. The basis functions returned are unitary and orthonormal
% when defined as a function of peri-stimulus time in time-bins.
% It is at this point that the distinction between event and epoch-related
% responses enters.
%__________________________________________________________________________
% Copyright (C) 1999-2011 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_get_bf.m 4473 2011-09-08 18:07:45Z guillaume $
% Edited by Guorong Wu. 2019-08-02
%-Length of time bin
%--------------------------------------------------------------------------
dt = xBF.dt; %'time bin for basis functions {secs}';
l = xBF.len;
h = xBF.order;
%-Create basis functions
%==========================================================================
%-Microtime resolution
%----------------------------------------------------------------------
fMRI_T = xBF.T;
%-Create basis functions
%==========================================================================
fprintf('Basis function: %s\n',xBF.name)
switch xBF.name
case {'Fourier set','Fourier set (Hanning)'}
%----------------------------------------------------------------------
pst = [0:dt:l]';
pst = pst/max(pst);
%-Hanning window
%----------------------------------------------------------------------
if strcmp(xBF.name,'Fourier set (Hanning)')
g = (1 - cos(2*pi*pst))/2;
else
g = ones(size(pst));
end
%-Zeroth and higher Fourier terms
%----------------------------------------------------------------------
bf = g;
for i = 1:h
bf = [bf g.*sin(i*2*pi*pst)];
bf = [bf g.*cos(i*2*pi*pst)];
end
case {'Gamma functions'}
%----------------------------------------------------------------------
pst = [0:dt:l]';
bf = spm_gamma_bf(pst,h);
otherwise
%-Canonical hemodynamic response function
%----------------------------------------------------------------------
[bf, p] = spm_hrf(dt,[],fMRI_T);
p(end) = xBF.len;
[bf, p] = spm_hrf(dt,p,fMRI_T);
%-Add time derivative
%----------------------------------------------------------------------
if strfind(xBF.name,'time')
dp = 1;
p(6) = p(6) + dp;
D = (bf(:,1) - spm_hrf(dt,p,fMRI_T))/dp;
bf = [bf D(:)];
p(6) = p(6) - dp;
%-Add dispersion derivative
%------------------------------------------------------------------
if strfind(xBF.name,'dispersion')
dp = 0.01;
p(3) = p(3) + dp;
D = (bf(:,1) - spm_hrf(dt,p,fMRI_T))/dp;
bf = [bf D(:)];
end
end
end
%-Orthogonalise and fill in basis function structure
%--------------------------------------------------------------------------
bf = spm_orth(bf);
return
%==========================================================================
%- S U B - F U N C T I O N S
%==========================================================================
function bf = spm_gamma_bf(u,h)
% Return basis functions (Gamma functions) used for Volterra expansion
% FORMAT bf = spm_gamma_bf(u,h);
% u - times {seconds}
% h - order
% bf - basis functions (mixture of Gammas)
%__________________________________________________________________________
u = u(:);
bf = [];
for i = 2:(1 + h)
m = 2^i;
s = sqrt(m);
bf = [bf spm_Gpdf(u,(m/s)^2,m/s^2)];
end
function [beta_hrf, u0]= wgr_hrf_estimation(dat,xBF,N,bf,temporal_mask)
%% estimate HRF
thr = xBF.thr;
if ~isfield(xBF,'localK')
if xBF.TR<=2
localK = 1;
else
localK = 2;
end
else
localK = xBF.localK;
end
u0 = rsHRF_find_event_vector(dat,thr,localK,temporal_mask);
u = [ full(u0)
zeros(xBF.T-1,N) ];
u = reshape(u,1,[]); %(microtime)
[beta, lag] = wgr_hrf_fit(dat,xBF,u,bf);
beta_hrf = beta; beta_hrf(end+1) = lag;
u0 = find(full(u0(:)));
return
function varargout = wgr_hrf_fit(dat,xBF,u,bf)
% u - BOLD event vector (microtime).
% nlag - time lag from neural event to BOLD event .
lag = xBF.lag;
AR_lag = xBF.AR_lag;
nlag = length(lag);
erm = zeros(1,nlag);
beta = zeros(size(bf,2)+1,nlag);
% fprintf('Converged after ')
for i=1:nlag
u_lag = [u(1,lag(i)+1:end) zeros(1,lag(i))]';
[erm(i), beta(:,i)] = wgr_glm_estimation(dat,u_lag,bf,xBF.T,xBF.T0,AR_lag);
end
[~, id] = rsHRF_knee_pt(erm);
if id==nlag
id = id-1;
end
varargout{1} = beta(:,id+1);
if nargout>1
varargout{2} = lag(id+1);
end
% fprintf('iterations!\n')
return
function [res_sum, Beta] = wgr_glm_estimation(dat,u,bf,T,T0,AR_lag)
% u: BOLD event vector (microtime).
nscans = size(dat,1);
x = wgr_onset_design(u,bf,T,T0,nscans);
X = [x ones(nscans,1)];
[res_sum, Beta] = wgr_glsco(X,dat,AR_lag);
return
function X = wgr_onset_design(u,bf,T,T0,nscans)
% u: BOLD event vector (microtime).
% bf: - basis set matrix
% T: - microtime resolution (number of time bins per scan)
% T0: - microtime onset (reference time bin, see slice timing)
ind = 1:length(u);
X = [];
for p = 1:size(bf,2)
x = conv(u,bf(:,p));
x = x(ind);
X = [X x];
end
%-Resample regressors at acquisition times
X = X( (0:(nscans - 1))*T + T0, :);
return
function [res_sum, Beta] = wgr_glsco(X,Y,AR_lag)
% Linear regression when disturbance terms follow AR(p)
% -----------------------------------
% Model:
% Yt = Xt * Beta + ut ,
% ut = Phi1 * u(t-1) + ... + Phip * u(t-p) + et
% where et ~ N(0,s^2)
% -----------------------------------
% Algorithm:
% Cochrane-Orcutt iterated regression (Feasible generalized least squares)
% -----------------------------------
% Usage:
% Y = dependent variable (n * 1 vector)
% X = regressors (n * k matrix)
% AR_lag = number of lags in AR process
% -----------------------------------
% Returns:
% Beta = estimator corresponding to the k regressors
if nargin < 3; AR_lag = 0;end
if nargin < 4; max_iter = 20;end
[nobs, nvar] = size(X);
% Beta = X\Y;
Beta = wgr_regress(Y,X);
resid = Y - X * Beta;
if ~AR_lag
%res_sum = sum(resid.^2);
res_sum=cov(resid);
return
end
max_tol = min(1e-6,max(abs(Beta))/1000);
for r = 1:max_iter
% fprintf('Iteration No. %d\n',r)
Beta_temp = Beta;
X_AR = zeros(nobs-2*AR_lag,AR_lag);
for m = 1:AR_lag
X_AR(:,m) = resid(AR_lag+1-m:nobs-AR_lag-m);
end
Y_AR = resid(AR_lag+1:nobs-AR_lag);
% AR_para = X_AR\Y_AR;
AR_para = wgr_regress(Y_AR,X_AR);
X_main = X(AR_lag+1:nobs,:);
Y_main = Y(AR_lag+1:nobs);
for m = 1:AR_lag
X_main = X_main-AR_para(m)*X(AR_lag+1-m:nobs-m,:);
Y_main = Y_main-AR_para(m)*Y(AR_lag+1-m:nobs-m);
end
% Beta = X_main\Y_main;
Beta = wgr_regress(Y_main,X_main);
resid = Y(AR_lag+1:nobs) - X(AR_lag+1:nobs,:)*Beta;
if max(abs(Beta-Beta_temp)) < max_tol
% fprintf('%d ,',r)
% fprintf('Converged after %d iterations!\n',r)
break
end
end
% res_sum = sum(resid.^2);
res_sum = cov(resid);
%if r == max_iter
% fprintf('Maximum %d iteration reached.\n',max_iter)
%end
return
function [hrf,p] = spm_hrf(RT,P,T)
% Haemodynamic response function
% FORMAT [hrf,p] = spm_hrf(RT,p,T)
% RT - scan repeat time
% p - parameters of the response function (two Gamma functions)
%
% defaults
% {seconds}
% p(1) - delay of response (relative to onset) 6
% p(2) - delay of undershoot (relative to onset) 16
% p(3) - dispersion of response 1
% p(4) - dispersion of undershoot 1
% p(5) - ratio of response to undershoot 6
% p(6) - onset {seconds} 0
% p(7) - length of kernel {seconds} 32
%
% T - microtime resolution [Default: 16]
%
% hrf - haemodynamic response function
% p - parameters of the response function
%__________________________________________________________________________
% Copyright (C) 1996-2015 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_hrf.m 6594 2015-11-06 18:47:05Z guillaume $
%-Parameters of the response function
%--------------------------------------------------------------------------
try
p = spm_get_defaults('stats.fmri.hrf');
catch
p = [6 16 1 1 6 0 32];
end
if nargin > 1
p(1:length(P)) = P;
end
%-Microtime resolution
%--------------------------------------------------------------------------
if nargin > 2
fMRI_T = T;
else
fMRI_T = spm_get_defaults('stats.fmri.t');
end
%-Modelled haemodynamic response function - {mixture of Gammas}
%--------------------------------------------------------------------------
dt = RT/fMRI_T;
u = [0:ceil(p(7)/dt)] - p(6)/dt;
hrf = spm_Gpdf(u,p(1)/p(3),dt/p(3)) - spm_Gpdf(u,p(2)/p(4),dt/p(4))/p(5);
hrf = hrf([0:floor(p(7)/RT)]*fMRI_T + 1);
hrf = hrf'/sum(hrf);
function b = wgr_regress(y,X)
% copy from function [b,bint,r,rint,stats] = regress(y,X,alpha)
[n,ncolX] = size(X);
% Use the rank-revealing QR to remove dependent columns of X.
[Q,R,perm] = qr(X,0);
if isempty(R)
p = 0;
elseif isvector(R)
p = double(abs(R(1))>0);
else
p = sum(abs(diag(R)) > max(n,ncolX)*eps(R(1)));
end
if p < ncolX
% warning(message('stats:regress:RankDefDesignMat'));
R = R(1:p,1:p);
Q = Q(:,1:p);
perm = perm(1:p);
end
% Compute the LS coefficients, filling in zeros in elements corresponding
% to rows of X that were thrown out.
b = zeros(ncolX,1);
b(perm) = R \ (Q'*y);
|
github | compneuro-da/rsHRF-master | rsHRF_viewer.m | .m | rsHRF-master/rsHRF_viewer.m | 13,643 | utf_8 | 31ffdd725e57f1fd4c1d762605d380a4 | function st = rsHRF_viewer(job);
% [email protected] ; Guo-Rong Wu
% 2017, 18th May.
% 2019, 25th Oct, updated.
% 2020, 9th Oct, colorbar Yticklabel removed.
underlay_img = job.underlay_nii{1};
img = job.stat_nii{1};
HRF_mat = job.HRF_mat;
clear st;
spm_orthviews('Reset');
global st
st.fig = figure('Visible','on',...
'numbertitle','off',...
'menubar','none',...
'units','normalized',...
'color','w',...
'position',[0.05,0.05,0.25,0.4],...
'name','HRF Viewer (v1.1)',...
'resize','on');
h = spm_orthviews('Image', underlay_img, [0 0.05 1 1]);
st.h = h;
st.underlay_img = underlay_img;
%% MNI input
info.mni_tx = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'position',[0.58 0.45 0.21 0.08],...
'string','MNI (x,y,z)',...
'backgroundc','w',...
'fontunits', 'normalized', 'fontsize',0.35,...
'horizontalalign','center',...
'value',1,...
'TooltipString','Sphere Radius');
info.mni_tx = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'position',[0.82 0.45 0.13 0.08],...
'string','Radius',...
'backgroundc','w',...
'fontunits', 'normalized', 'fontsize',0.35,...
'horizontalalign','center',...
'value',1,...
'TooltipString','Sphere Radius');
info.ed_mni = uicontrol('Parent',st.fig,...
'style','edit',...
'unit','norm',...
'position',[0.58 0.36 0.21 0.08],...
'fontunits', 'normalized', 'fontsize',0.5,...
'string','0 0 0',...
'KeyPressFcn',@wgr_edit_mni,...
'horizontalalign','center');
info.ed_radius = uicontrol('Parent',st.fig,...
'style','edit',...
'unit','norm',...
'position',[0.82 0.36 0.13 0.08],...
'fontunits', 'normalized', 'fontsize',0.5,...
'string','0',...
'horizontalalign','center');
%% threshold /extent
info.thresh = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'position',[0.58 0.25 0.21 0.08],...
'string','Threshold',...
'backgroundc','w',...
'fontunits', 'normalized', 'fontsize',0.4,...
'horizontalalign','center',...
'value',1,...
'TooltipString','...');
info.extent = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'position',[0.82 0.25 0.13 0.08],...
'string','Extent',...
'backgroundc','w',...
'fontunits', 'normalized', 'fontsize',0.4,...
'horizontalalign','center',...
'value',1,...
'TooltipString','Sphere Radius');
info.ed_threshold = uicontrol('Parent',st.fig,...
'style','edit',...
'unit','norm',...
'position',[0.58 0.15 0.21 0.08],...
'fontunits', 'normalized', 'fontsize',0.5,...
'string','-1.9 1.9',...
'callback',@wgr_update,...
'horizontalalign','center');
info.ed_extent = uicontrol('Parent',st.fig,...
'style','edit',...
'unit','norm',...
'position',[0.82 0.15 0.13 0.08],...
'fontunits', 'normalized', 'fontsize',0.5,...
'string','20',...
'callback',@wgr_update,...
'horizontalalign','center');
info.intensity = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'backgroundc','w',...
'position',[0.58 0.05 0.21 0.08],...
'string','',...
'TooltipString','value/intensity',...
'fontunits', 'normalized', 'fontsize',0.5,'val',1);
info.plot = uicontrol('Parent',st.fig,...
'style','pushbutton',...
'units','norm',...
'backgroundc','w',...
'position',[0.82 0.05 0.13 0.08],...
'string','Plot',...
'callback',@wgr_plot_hrf,...
'TooltipString','Plot HRF shape',...
'fontunits', 'normalized', 'fontsize',0.4,'val',1);
st.info = info;
if ~isempty(img)
vv = spm_vol(img);
st.v = vv;
refinfo = load(HRF_mat{1}{1},'v0');
if any(vv.mat - refinfo.v0.mat)
fprintf('(Underlay image) %s \n is different from (1st, ''v0.mat'') \n%s\n',underlay_img, HRF_mat{1}{1})
end
[data, mni] = spm_read_vols(vv);
data(isnan(data))=0;
st.mni = mni;
st.stat_data = data;
[peakcoord, peakintensity] = wgr_update;
end
spm_orthviews('Reposition',peakcoord);
movegui(st.fig,'center');
set(info.ed_mni,'string',sprintf('[%d,%d,%d]',round(peakcoord)));
set(info.intensity,'string',sprintf('%3.3f',peakintensity));
%% HRF shapes
fprintf('checking HRF mat-files...\n')
refinfo = load(HRF_mat{1}{1},'v0','smask_ind');
if 0 % keep only survived voxels
idunique = intersect(refinfo.smask_ind,pos);
else
idunique = refinfo.smask_ind;
end
k00=0;
for i=1:length(HRF_mat)
group = HRF_mat{i};
for j=1:size(group,1)
aa = load(group{j},'v0','smask_ind');
if any(aa.v0.mat - refinfo.v0.mat)
fprintf('%s \n is different from (1st, ''v0.mat'') \n%s\n',group{j}, HRF_mat{1}{1})
else
idunique = intersect(idunique,aa.smask_ind);
end
k00=k00+1;
end
end
fprintf('\nDone\n')
% fprintf('keep only survived voxels\n other voxels information will be removed.\n')
% fprintf('Loading HRF Shapes (only survived #%d voxels)...\n',length(idunique))
fprintf('Loading HRF Shapes...\n',length(idunique))
ng = length(HRF_mat);
aa = load(HRF_mat{1}{1},'hrfa');
mf = zeros(size(aa.hrfa,1),length(idunique),ng);
sf = mf;
for i=1:ng
group = HRF_mat{i};
k00 = size(group,1);
for j=1:k00
fprintf('.')
aa = load(group{j},'v0','smask_ind','hrfa');
if j==1
HRFa = zeros(size(aa.hrfa,1),length(idunique),k00);
end
[C,ia,ib] = intersect(aa.smask_ind, idunique);
HRFa(:,:,j) = aa.hrfa(:,ia);
end
mf(:,:,i) = mean(HRFa,3);
% sf(:,:,i) = std(HRFa,0,3);%std
sf(:,:,i) = std(HRFa,0,3)./sqrt(k00);%SE
end
fprintf('Done\n')
aa = load(group{j},'para');
st.dt = aa.para.dt;
st.mf = mf;
st.sf = sf;
st.idunique = idunique;
set(st.fig,'WindowButtonDownFcn',@wgr_get_crosshairs); %double click
function [] = wgr_edit_mni(varargin)
global st
mni_coord = str2num(get(st.info.ed_mni,'string'));
spm_orthviews('Reposition',mni_coord);
v = st.v;
data = st.stat_data;
c_cor = mni2cor(mni_coord, v.mat)';
cvalue = data(c_cor(1),c_cor(2),c_cor(3));
set(st.info.intensity,'string',sprintf('%3.3f',cvalue));
function [] = wgr_get_crosshairs(varargin)
global st
if strcmp(get(gcf,'SelectionType'),'normal')
mni_coord= spm_orthviews('pos')';
v = st.v;
data = st.stat_data;
c_cor = mni2cor(mni_coord,v.mat);
cvalue = data(c_cor(1),c_cor(2),c_cor(3));
set(st.info.ed_mni,'string',sprintf('[%d,%d,%d]',round(mni_coord)));
set(st.info.intensity,'string',sprintf('%3.3f',cvalue));
return
end
function []=wgr_plot_hrf(varargin)
global st
mni_coord= spm_orthviews('pos')';
radius = str2num(get(st.info.ed_radius,'string'));
if radius
xY = [];
xY.def='sphere';
xY.xyz= mni_coord';
xY.spec = radius;
[xY, XYZmm, ~] = spm_ROI(xY, st.tmpmni);
mni_coord = [XYZmm';mni_coord];
else
xY.xyz= mni_coord';
end
mf = st.mf;
sf = st.sf;
idunique = st.idunique;
v = st.v;
dt = st.dt;
data = st.stat_data;
c_cor = mni2cor(mni_coord,v.mat);
cid = sub2ind(size(data),c_cor(:,1),c_cor(:,2),c_cor(:,3) );
% id = find(idunique==cid); %length(cid)==1;
[C,id,ib] = intersect(idunique,cid);
mf0 = squeeze(mean(mf(:,id,:),2));
sf0 = squeeze(mean(sf(:,id,:),2));
nobs = size(mf,1);
xx = (1:nobs)*dt;
if isempty(id)
fprintf('no HRF information in this position \n')
else
figure1 = figure('color','w');
ax = axes('Parent',figure1,'Position',[0.15 0.15 0.7 0.7]);
movegui(figure1,'east');
ng = size(mf0,2);
if ng<7
colo = {'r','b','g',[1 0 1],'k',[0.8 0.6 0]};
else
colo1 = jet(ng);
for i=1:ng
colo{i} = colo1(i,:);
end
end
hold all;
for i=1:ng
flag_norm = 0; %peak normalization
if flag_norm
mf0(:,i) = mf0(:,i) ./max(mf0(:,i) );
end
plot(ax, xx,mf0(:,i) ,'LineWidth',2,'color',colo{i});
end
for i=1:ng
if any(sf0(:,i))
fill(ax, [xx fliplr(xx)], [mf0(:,i)'+sf0(:,1)' fliplr(mf0(:,i)'-sf0(:,i)')],colo{i}, ...
'LineStyle','none','LineWidth',1,'EdgeColor',colo{i},'edgealpha',0,'facealpha',0.5);
end
end
xlim(ax,[0 max(xx)])
axis square
a = mf0 - 1.5*sf0 ; minx = min(a(:));
a = mf0 + 1.5*sf0; maxx= max(a(:));
ylim(ax,[minx maxx])
hold off
gg={};
for i=1:ng
gg{i} = ['G',num2str(i)];
end
legend(ax,gg,'box','off')
set(ax,'FontName','Calibri','FontSize',14); %'Cambria','Times New Roman'
box on
xlabel(ax,'Time(s)')
if radius
title(sprintf('HRF (center MNI:[%d,%d,%d], spherical radius: %3.2f,#%dvoxels)',round(xY.xyz), radius,size(mni_coord,1)));
else
title(sprintf('HRF (MNI:[%d,%d,%d])',round(xY.xyz)));
end
% set(st.info.ed_mni,'string',sprintf('[%d,%d,%d]',round(mni_coord)));
% set(st.info.intensity,'string',sprintf('%3.3f',cvalue));
end
return
% function [peakcoord, peakintensity] = wgr_threshold_map()
function [peakcoord, peakintensity] = wgr_update(varargin)
mni_coord= spm_orthviews('pos')';
global st
mni = st.mni ;
data = st.stat_data ;
T_threhold = str2num(get(st.info.ed_threshold,'string'));
extent_clu = str2num(get(st.info.ed_extent,'string'));
v = st.v ;
data(data>T_threhold(1)&data<T_threhold(2))=0;
XYZ = mni2cor(mni', v.mat)';
if extent_clu>1
id = find(data~=0);
[x0,y0,z0] = ind2sub(v.dim,id);
A = spm_clusters([x0 y0 z0]');
clu = unique(A(:));
clu_len = zeros(max(clu),1);
id2 = [];
for kk= 1:max(clu)
tmp = find(A(:)==kk);
clu_len(kk) = length(tmp);
if clu_len(kk)>= extent_clu
id2 = [id2;tmp];
end
end
dat = zeros(v.dim);
dat(id(id2)) = data(id(id2));
data = dat; clear dat
end
pos = find(data~=0);
numVoxels = length(pos);
if numVoxels==0
fprintf('No survived results <%3.2f or >%3.2f \n',T_threhold)
return
else
fprintf('#%d voxels\n',numVoxels)
end
tmpmni = mni(:,pos);
tmpintensity = data(pos);
tmpXYZ = XYZ(:,pos);
st.tmpmni = tmpmni;
st.tmpXYZ = tmpXYZ;
st.tmpZ = tmpintensity;
peakpos = find(abs(tmpintensity) == max(abs(tmpintensity)));
peakpos = peakpos(1);
peakcoord = tmpmni(:,peakpos)';
peakintensity = tmpintensity(peakpos);
if any(tmpintensity>0) && any(tmpintensity<0)
spm_figure('Colormap','gray-jet')
elseif any(tmpintensity>0) && ~any(tmpintensity<0)
spm_figure('Colormap','gray-hot')
else %if ~any(tmpintensity>0) & any(tmpintensity<0)
spm_figure('Colormap','gray-cool')
end
st.h = spm_orthviews('Image', st.underlay_img, [0 0.05 1 1]);
spm_orthviews('AddBlobs', st.h, st.tmpXYZ, st.tmpZ, st.v.mat);
spm_orthviews('Reposition',mni_coord);
fprintf('Peak MNI: [%d %d %d], Peak value: %2.3f\n',[round(peakcoord) peakintensity])
spm_orthviews('Redraw');
hh= cellfun(@(x) isempty(x), st.vols);
id= find(hh);
for i=2:id(1)-2
st.vols{i, 1}.blobs{1, 1}.cbar.YTickLabel={};
end
return
function coordinate = mni2cor(mni, T)
if isempty(mni)
coordinate = [];
return;
end
coordinate = [mni(:,1) mni(:,2) mni(:,3) ones(size(mni,1),1)]*(inv(T))';
coordinate(:,4) = [];
coordinate = round(coordinate);
return;
|
github | compneuro-da/rsHRF-master | rsHRF_conn_run.m | .m | rsHRF-master/rsHRF_conn_run.m | 15,141 | utf_8 | d03feabaea5d3171c10d2d0cb822b2bc | function rsHRF_conn_run(data, connroinfo,v0,name,outdir,flag_pval_pwgc,flag_nii_gii);
%data: nobs x nvar (3D index)
fprintf('Connectivity analysis...\n ')
meastr = {'pwGC','CGC','PCGC','Pearson','PartialPearson','Spearman','PartialSpearman',};
para_global = rsHRF_global_para;
regmode = para_global.regmode; % for GC
for j=1:size(connroinfo,1)
fprintf('Conn %d\n',j)
roiid = connroinfo{j,1}; nroi = size(roiid,1);
flag_seedROI = connroinfo{j,2};
conn_type = connroinfo{j,3};
order = connroinfo{j,4};
ndinfo = connroinfo{j,5};
ROI = [];
for i=1:nroi
tmp = nanmean(data(:,roiid{i,1}),2) ;
ROI(:,i) = tmp;
end
if nroi==0 %&& isempty(v0)
ROI = data;
end
if ~flag_seedROI % seed map
if flag_nii_gii==1
ext_nii_gii = '.nii';
else
ext_nii_gii = '.gii';
end
smask_ind = find(var(data)>0);
dat.data = data(:,smask_ind);
dat.ROI = ROI;
dat3 = zeros(v0.dim);
if conn_type==1 || conn_type==2 || conn_type==3
if conn_type==2
conn_type = 1; % pairwise
warning('Change Contional GC to Pairwise GC')
elseif conn_type==3
conn_type = 1; % pairwise
warning('Change Partially Contioned GC to Pairwise GC')
end
disp('Pairwise GC for seed based connectivity analysis')
[M] = wgr_GC(dat,order,ndinfo,conn_type,regmode,flag_pval_pwgc);
ordeinfo = ['_order',num2str(order)];
for i=1:nroi
if nroi>1
tmp = [num2str(i),'_'];
else
tmp = '';
end
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_outflow_pwGC',ordeinfo,ext_nii_gii]);
out.outflow_pwGC{i} = fname;
gc = M.GC_Matrix_Out(i,:);
dat3(smask_ind) = gc;
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_outflow_N_pwGC',ordeinfo,ext_nii_gii]);
out.outflow_N_pwGC{i} = fname;
dat3(smask_ind) = wgr_pwgc_2normal(gc,M.nobs,order);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
if flag_pval_pwgc
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_outflow_pval_pwGC',ordeinfo,ext_nii_gii]);
out.outflow_pval_pwGC{i} = fname;
dat3(smask_ind) = M.pval_GC_Matrix_Out(i,:);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
end
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_inflow_pwGC',ordeinfo,ext_nii_gii]);
out.inflow_pwGC{i} = fname;
gc = M.GC_Matrix_In(i,:);
dat3(smask_ind) = gc;
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_inflow_N_pwGC',ordeinfo,ext_nii_gii]);
out.inflow_N_pwGC{i} = fname;
dat3(smask_ind) = wgr_pwgc_2normal(gc,M.nobs,order);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
seed_information = roiid(i,:);
save(fullfile(outdir,[connroinfo{j,6},tmp,name,'_SeedInfo_pwGC',ordeinfo,'.mat']),'seed_information');
if flag_pval_pwgc
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_inflow_pval_pwGC',ordeinfo,ext_nii_gii]);
out.inflow_pval_pwGC{i} = fname;
dat3(smask_ind) = M.pval_GC_Matrix_In(i,:);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
end
end
else
[M] = wgr_FC(dat,conn_type);
for i=1:nroi
if nroi>1
tmp = [num2str(i),'_'];
else
tmp = '';
end
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_corr_',meastr{connroinfo{j,3}},ext_nii_gii]);
out.corr{i} = fname;
dat3(smask_ind) = M.Matrix_r(i,:);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
fname = fullfile(outdir,[connroinfo{j,6},tmp,name,'_Z_',meastr{connroinfo{j,3}},ext_nii_gii]);
out.Z{i} = fname;
dat3(smask_ind) = M.Matrix_z(i,:);
rsHRF_write_file(fname,dat3,flag_nii_gii,v0)
seed_information = roiid(i,:);
save(fullfile(outdir,[connroinfo{j,6},tmp,name,'_SeedInfo_',meastr{connroinfo{j,3}},'.mat']),'seed_information');
end
end
else %ROI to ROI
dat.data = ROI;
dat.ROI = [];
if conn_type==1 || conn_type==2 || conn_type==3 % 1:pairwise 2:conditional 3: partially conditioned
M = wgr_GC(dat,order,ndinfo, conn_type,regmode, flag_pval_pwgc);
save(fullfile(outdir,[connroinfo{j,6},name,'_',meastr{connroinfo{j,3}},'.mat']),'M','roiid');
else
M = wgr_FC(dat,conn_type);
save(fullfile(outdir,[connroinfo{j,6},name,'_Corr_',meastr{connroinfo{j,3}},'.mat']),'M','roiid');
end
end
end
function c = wgr_pwgc_2normal(gc,nobs,order)
c = (nobs-order).*gc - (order-1)/3;
c(c<0)=0;
c = sqrt(c);
function [M] = wgr_GC(dat,order,ndinfo,flag_pw_cgc,regmode,flag_pval_pwgc,m);
% flag_pw_cgc, 1: pairwise GC, 2: conditional GC, 3: partially conditioned GC.
gcstr = {'Pairwise GC','Conditional GC','Partially Conditioned GC'};
data = dat.data;
[nobs,nvar] = size(data);
ROI = dat.ROI;
[nobsROI,nROI] = size(ROI);
M.seed_num = nROI;
if nROI
if nobsROI~=nobs
error('different observations (ROI vs Data)')
end
end
if nobs<10
warning('Too few observations !')
end
fprintf('Data dimension: %d x %d\n',nobs,nvar);
if flag_pw_cgc==2 % CGC
if nobs<nvar
fprintf('#observation < #variable\n');
error('CGC stop!')
end
end
if nargin<7
m = 5000; %block size
end
M.nvar=nvar;
M.nobs=nobs;
M.order = order;
M.GC_type = gcstr{flag_pw_cgc};
M.ndinfo = ndinfo;
if flag_pw_cgc==3 % if nnz(ndinfo)==1
nd = ndinfo(1);
if isnan(nd)
nd = 6;
end
ndmax = ndinfo(2);
if isnan(ndmax)
ndmax = nd+1;
end
end
nbin = ceil(nvar/m);
indX={}; indY={};
matrix={};
matrix_out = {};
matrix_in={};
p_matrix_out={};
p_matrix_in={};
if nROI %ROI to data
nbinROI = ceil(nROI/m);
for i=1:nbinROI
if i~=nbinROI
ind_X = (i-1)*m+1:i*m ;
else
ind_X = (i-1)*m+1:nROI ;
end
indX{i} = ind_X;
for j=1:nbin
if j~=nbin
ind_Y = (j-1)*m+1:j*m ;
else
ind_Y = (j-1)*m+1:nvar ;
end
indY{j} = ind_Y;
if flag_pval_pwgc
[matrix_out{i,j}, matrix_in{i,j}, p_matrix_out{i,j}, p_matrix_in{i,j}] = ...
wgr_seedGC(ind_X,ind_Y,ROI,data,order,1,regmode);
else
[matrix_out{i,j}, matrix_in{i,j}] = wgr_seedGC(ind_X,ind_Y,ROI,data,order,0,regmode); %only pairwise.
end
end
end
else % data to data
if flag_pw_cgc==3
[y_inform_gain, cind] = wgr_init_partial_conditioning(data,[],ndmax,order);
M.information_gain = y_inform_gain;
M.condition_id = cind;
end
if flag_pw_cgc==1
[M.GC_Matrix, M.pval_Matrix] = wgr_PWGC(data,order,regmode,flag_pval_pwgc);
end
if flag_pw_cgc==2
[M.GC_Matrix, M.pval_Matrix] = rsHRF_mvgc(data',order,regmode,0,flag_pval_pwgc);
end
if flag_pw_cgc==3
[M.GC_Matrix, M.pval_Matrix] = wgr_PCGC(data,order,cind,nd,regmode,flag_pval_pwgc);
end
end
if nROI
M.GC_Matrix_Out = nan(nROI,nvar);
M.GC_Matrix_In = M.GC_Matrix_Out ;
for i=1:nbinROI
for j=1:nbin
M.GC_Matrix_Out(indX{i},indY{j}) = matrix_out{i,j};
M.GC_Matrix_In(indX{i},indY{j}) = matrix_in{i,j};
if flag_pval_pwgc
M.pval_GC_Matrix_Out(indX{i},indY{j}) = p_matrix_out{i,j};
M.pval_GC_Matrix_In(indX{i},indY{j}) = p_matrix_in{i,j};
end
end
end
else
if flag_pw_cgc==1
M.GC_Matrix_N = wgr_pwgc_2normal(M.GC_Matrix,nobs,order);
end
end
clear matrix* p_* indX indY
function [F,pvalue] = wgr_PWGC(data,order,regmode,flag_pval);
[nvar] = size(data,2);
F = zeros(nvar);
if flag_pval
pvalue = nan(nvar);
end
for drive=1:nvar
for target=1:nvar
if drive~=target
dat = data(:,[drive target])';
[F0,p0] = rsHRF_mvgc(dat,order,regmode,0,flag_pval);
F(drive,target) = F0(1,2);
pvalue(drive,target) = p0(1,2);
F(target,drive) = F0(2,1);
pvalue(target,drive) = p0(2,1);
end
end
end
function [F,pvalue] = wgr_PCGC(data,order,cind,nd,regmode,flag_pval);
[nvar] = size(data,2);
F = zeros(nvar);
if flag_pval
pvalue = nan(nvar);
end
parfor drive=1:nvar
for target=1:nvar
if drive~=target
zid = setdiff(cind(drive,:),target,'stable');
dat = data(:,[drive target zid(1:nd)])';
[F(drive,target),pvalue(drive,target)] = ...
rsHRF_mvgc(dat,order,regmode,1,flag_pval);
end
end
end
function [gc_out, gc_in, p_out, p_in] = wgr_seedGC(ind_X,ind_Y,ROI,data1,order,flag_pval,regmode);
[nvar1] = length(ind_X);
[nvar2] = length(ind_Y);
gc_out = zeros(nvar1,nvar2);
gc_in = gc_out;
if flag_pval
p_out = nan(nvar1,nvar2);
p_in = p_out;
end
parfor drive=1:nvar1
for target=1:nvar2
data = [ROI(:,ind_X(drive)) data1(:,ind_Y(target))]';
[F,pvalue] = rsHRF_mvgc(data,order,regmode,0,flag_pval);
if length(F)>1
gc_out(drive,target) = F(1,2);
gc_in(drive,target) = F(2,1);
p_out(drive,target) = pvalue(1,2);
p_in(drive,target) = pvalue(2,1);
end
end
end
function [M] = wgr_FC(dat,conn_type,m);
% conn_type, 4/5: pearson, 6/7: spearman
if conn_type==4
con_type = 'Pearson'; flag_partial=0;
elseif conn_type==5
con_type = 'Pearson'; flag_partial=1;
elseif conn_type==6
con_type = 'Spearman'; flag_partial=0;
elseif conn_type==7
con_type = 'Spearman'; flag_partial=1;
end
data = dat.data;
[nobs,nvar] = size(data);
ROI = dat.ROI;
[nobsROI,nROI] = size(ROI);
M.seed_num = nROI;
if nROI
if nobsROI~=nobs
error('different observations (ROI vs Data)')
end
end
if nobs<10
warning('Too few observations !')
end
fprintf('Data dimension: %d x %d\n',nobs,nvar);
if nargin<3
m = 5000; %block size
end
M.nvar=nvar;
M.nobs=nobs;
nbin = ceil(nvar/m);
indX={}; indY={};
matrix={};
if nROI %ROI to data
nbinROI = ceil(nROI/m);
for i=1:nbinROI
if i~=nbinROI
ind_X = (i-1)*m+1:i*m ;
else
ind_X = (i-1)*m+1:nROI ;
end
indX{i} = ind_X;
for j=1:nbin
if j~=nbin
ind_Y = (j-1)*m+1:j*m ;
else
ind_Y = (j-1)*m+1:nvar ;
end
indY{j} = ind_Y;
matrix_r{i,j} = corr(ROI(:,ind_X),data(:,ind_Y), 'type', con_type);
matrix_z{i,j} = atanh(matrix_r{i,j}) ;
end
end
else % data to data
if flag_partial % partial correlation
if nobs<nvar
fprintf('#observation < #variable\n');
error('partial correlation stop!')
end
end
if ~flag_partial
for i=1:nbin
if i~=nbin
ind_X = (i-1)*m+1:i*m ;
else
ind_X = (i-1)*m+1:nvar ;
end
indX{i} = ind_X;
for j=1:nbin
if j~=nbin
ind_Y = (j-1)*m+1:j*m ;
else
ind_Y = (j-1)*m+1:nvar ;
end
indY{j} = ind_Y;
[matrix_r{i,j},matrix_p{i,j}] = corr(data(:,ind_X),data(:,ind_Y), 'type',con_type);
matrix_z{i,j} = atanh(matrix_r{i,j}) ;
end
end
else
indX{1} = 1:nvar ; indY{1} = 1:nvar ;
[matrix_r{1,1},matrix_p{1,1}] = partialcorr(data, 'type',con_type);
matrix_z{1,1} = atanh(matrix_r{1,1}) ;
end
end
if nROI
M.Matrix_r = nan(nROI,nvar);
M.Matrix_z = M.Matrix_r;
for i=1:nbinROI
for j=1:nbin
M.Matrix_r(indX{i},indY{j}) = matrix_r{i,j};
M.Matrix_z(indX{i},indY{j}) = matrix_z{i,j};
end
end
else
M.Matrix_r = nan(nvar,nvar);
for i=1:nbin
for j=1:nbin
M.Matrix_r(indX{i},indY{j}) = matrix_r{i,j};
M.Matrix_z(indX{i},indY{j}) = matrix_z{i,j};
M.Matrix_pval(indX{i},indY{j}) = matrix_p{i,j};
end
end
M.Matrix_r(1:nvar+1:end)=0; %remove diag value.
M.Matrix_z(1:nvar+1:end)=0; %remove diag value.
M.Matrix_pval(1:nvar+1:end)=1; %remove diag value.
end
clear matrix* indX indY
function [y, ind] = wgr_init_partial_conditioning(data,seed_signal,ndmax,order)
[N,nvar] = size(data);
X=cell(nvar,1);
past_ind = repmat([1:order],N-order,1) + repmat([0:N-order-1]',1,order);
for i=1:nvar
past_data= reshape(data(past_ind,i),N-order,order);
X{i}= past_data - repmat(mean(past_data), N-order, 1); %%remove mean
end
ind=zeros(nvar,ndmax);
y=ind;
if ~isempty(seed_signal)
[N2,nvar2] = size(seed_signal);
if N~=N2
error('check #observation of seed_signal !')
else
ind = nan(nvar2,ndmax); y = ind;
parfor drive=1:nvar2
past_data = reshape(seed_signal(past_ind,drive),N-order,order);
drive_sig = past_data - repmat(mean(past_data), N-order, 1);
[y(drive,:), ind(drive,:)]=wgr_information_gain(drive_sig,X,nvar,ndmax);
end
end
else
ind = nan(nvar,ndmax); y = ind;
parfor drive=1:nvar
[y(drive,:), ind(drive,:)]=wgr_information_gain(drive,X,nvar,ndmax); %do not allow to dynamic plot
end
end
function [y, ind]= wgr_information_gain(drive,X,nvar,ndmax)
if nnz(drive)==1
indici=setdiff(1:nvar,drive);%,'stable');
t=X{drive};
else %seed signal
indici= 1:nvar ;
t=drive;
end
Zt=[]; ind=nan(1,ndmax); y = ind;
for nd=1:ndmax
n1=length(indici);
z=zeros(n1,1);
for k=1:n1
Zd=[Zt X{indici(k)}];
z(k)= wgr_MI_gaussian(Zd,t);
end
[y(1,nd), id] = max(z);
Zt = [Zt, X{indici(id)}];
ind(1,nd) = indici(id);
indici = setdiff(indici, indici(id));%,'stable');
end
function mi = wgr_MI_gaussian(Y,X)
% X: N x k_x Y: N x k_y
% condtional mutual information
% mi = gaussian mutual information X,Y
XY_cov = X'*Y; %%here we delete the factor: 1/N.
X_cov = X'*X;
Y_cov = Y'*Y;
all_cov = [X_cov XY_cov;XY_cov' Y_cov];
mi = 0.5*log(abs(det(X_cov)*det(Y_cov)/det(all_cov)));
return
|
github | compneuro-da/rsHRF-master | rsHRF_estimation_impulseest.m | .m | rsHRF-master/rsHRF_estimation_impulseest.m | 3,318 | utf_8 | 70435fdafab02c8b3db7641bff6ee530 | function [hrfa,event_bold] = rsHRF_estimation_impulseest(data,para);
% Nonparametric impulse response estimation.
% System Identification Toolbox is required.
%
% By: Guo-Rong Wu ([email protected]).
% Faculty of Psychology, Southwest University.
% History:
% - 2015-04-17 - Initial version.
% para.thr=[1];
% para.lag=[2,6];
% para.TR = 2;
% para.len = 24; % second
% para.localK = 1; % local peak, f([-localK: localK]+t) <= f(t)
% if 0 % Options set for impulseest
% options = impulseestOptions; % see impulseestOptions.m for help
% options.RegularizationKernel = 'HF'; %Regularizing kernel, used for regularized estimates of impulse response for all input-output channels. Regularization reduces variance of estimated model coefficients and produces a smoother response by trading variance for bias
% % 'TC' ? Tuned and correlated kernel, Default: 'TC'
% % 'none' ? No regularization is used
% % 'CS' ? Cubic spline kernel
% % 'SE' ? Squared exponential kernel
% % 'SS' ? Stable spline kernel
% % 'HF' ? High frequency stable spline kernel
% % 'DI' ? Diagonal kernel
% % 'DC' ? Diagonal and correlated kernel
% options.PW = 5; %Order of the input prewhitening filter. Must be one of the following:
% % 'auto' ? Uses a filter of order 10 when RegularizationKernel is 'none'; otherwise, 0.
% % Nonnegative integer: Use a nonzero value of prewhitening only for unregularized estimation (RegularizationKernel is 'none').
% % Default: 'auto'
% para.options = options;
% end
% [hrfa,para] = rsHRF_estimation_impulseest(randn(200,5),para);
% x = 0:para.TR:para.len;
% plot(x, hrfa)
if ~exist('impulseest.m')
fprintf('System Identification Toolbox is required.\n')
return
end
nvar = size(data,2);
if ~isfield(para,'temporal_mask') % temporal_mask: generated from scrubbing.
para.temporal_mask=[];
end
hrfa = cell(1,nvar);
event_bold= cell(1,nvar);
parfor i=1:nvar
[hrfa{i},event_bold{i}] = wgr_impulseest_HRF(data(:,i),para);
end
hrfa =cell2mat(hrfa);
return
function [rsH,u] = wgr_impulseest_HRF(data,para)
nscans = size(data,1);
if ~isfield(para,'options')
opt = [];
else
opt = para.options;
end
if ~isfield(para,'localK')
if para.TR>=2
localK = 1;
else
localK = 2;
end
else
localK = para.localK;
end
u = rsHRF_find_event_vector(data,para.thr,localK,para.temporal_mask);
u = u(:);
lag = para.lag;
nlag = length(lag);
frameRate = 1/para.TR;
NN = fix(para.len*frameRate);
bic = zeros(nlag,1);
tic
%% rs-HRF
for i=nlag:-1:1
u_lag = full([u(lag(i)+1:end,:); zeros(lag(i),1)]);
srs = iddata(data, u_lag, para.TR);
% srs = detrend(srs);
if isempty(opt)
srsiiu = impulseest(srs,NN);
else
srsiiu = impulseest(srs,NN,opt);
end
bic(i,1) = srsiiu.Report.Fit.BIC;
HR(:,i) = srsiiu.Report.Parameters.ParVector;
end
toc
[~,id] = min(bic);
rsH = HR(:,id);
u = find(full(u)); |
github | compneuro-da/rsHRF-master | rsHRF_knee_pt.m | .m | rsHRF-master/rsHRF_knee_pt.m | 5,902 | utf_8 | f22baf6900ab2ca29cb21378d8bdef01 | function [res_x, idx_of_result] = rsHRF_knee_pt(y)
res_x=[];
[~,id] = knee_pt(y);
[~,idm] = min(y);
ratio = abs(y(id)-y(idm))/range(y);
if ratio>0.5
idx_of_result = idm;
else
idx_of_result = id;
end
end
function [res_x, idx_of_result] = knee_pt(y,x,just_return)
%Returns the x-location of a (single) knee of curve y=f(x)
% (this is useful for e.g. figuring out where the eigenvalues peter out)
%
%Also returns the index of the x-coordinate at the knee
%
%Parameters:
% y (required) vector (>=3 elements)
% x (optional) vector of the same size as y
% just_return (optional) boolean
%
%If just_return is True, the function will not error out and simply return a Nan on
%detected error conditions
%
%Important: The x and y don't need to be sorted, they just have to
%correspond: knee_pt([1,2,3],[3,4,5]) = knee_pt([3,1,2],[5,3,4])
%
%Important: Because of the way the function operates y must be at least 3
%elements long and the function will never return either the first or the
%last point as the answer.
%
%Defaults:
%If x is not specified or is empty, it's assumed to be 1:length(y) -- in
%this case both returned values are the same.
%If just_return is not specified or is empty, it's assumed to be false (ie the
%function will error out)
%
%
%The function operates by walking along the curve one bisection point at a time and
%fitting two lines, one to all the points to left of the bisection point and one
%to all the points to the right of of the bisection point.
%The knee is judged to be at a bisection point which minimizes the
%sum of errors for the two fits.
%
%the errors being used are sum(abs(del_y)) or RMS depending on the
%(very obvious) internal switch. Experiment with it if the point returned
%is not to your liking -- it gets pretty subjective...
%
%
%Example: drawing the curve for the submission
% x=.1:.1:3; y = exp(-x)./sqrt(x); [i,ix]=knee_pt(y,x);
% figure;plot(x,y);
% rectangle('curvature',[1,1],'position',[x(ix)-.1,y(ix)-.1,.2,.2])
% axis('square');
%
%Food for thought: In the best of possible worlds, per-point errors should
%be corrected with the confidence interval (i.e. a best-line fit to 2
%points has a zero per-point fit error which is kind-a wrong).
%Practially, I found that it doesn't make much difference.
%
%dk /2012
%{
% test vectors:
[i,ix]=knee_pt([30:-3:12,10:-2:0]) %should be 7 and 7
knee_pt([30:-3:12,10:-2:0]') %should be 7
knee_pt(rand(3,3)) %should error out
knee_pt(rand(3,3),[],false) %should error out
knee_pt(rand(3,3),[],true) %should return Nan
knee_pt([30:-3:12,10:-2:0],[1:13]) %should be 7
knee_pt([30:-3:12,10:-2:0],[1:13]*20) %should be 140
knee_pt([30:-3:12,10:-2:0]+rand(1,13)/10,[1:13]*20) %should be 140
knee_pt([30:-3:12,10:-2:0]+rand(1,13)/10,[1:13]*20+rand(1,13)) %should be close to 140
x = 0:.01:pi/2; y = sin(x); [i,ix]=knee_pt(y,x) %should be around .9 andaround 90
[~,reorder]=sort(rand(size(x)));xr = x(reorder); yr=y(reorder);[i,ix]=knee_pt(yr,xr) %i should be the same as above and xr(ix) should be .91
knee_pt([10:-1:1]) %degenerate condition -- returns location of the first "knee" error minimum: 2
%}
%set internal operation flags
use_absolute_dev_p = true; %ow quadratic
%deal with issuing or not not issuing errors
issue_errors_p = true;
if (nargin > 2 && ~isempty(just_return) && just_return)
issue_errors_p = false;
end
%default answers
res_x = nan;
idx_of_result = nan;
%check...
if (isempty(y))
if (issue_errors_p)
error('knee_pt: y can not be an empty vector');
end
return;
end
%another check
if (sum(size(y)==1)~=1)
if (issue_errors_p)
error('knee_pt: y must be a vector');
end
return;
end
%make a vector
y = y(:);
%make or read x
if (nargin < 2 || isempty(x))
x = (1:length(y))';
else
x = x(:);
end
%more checking
if (ndims(x)~= ndims(y) || ~all(size(x) == size(y)))
if (issue_errors_p)
error('knee_pt: y and x must have the same dimensions');
end
return;
end
%and more checking
if (length(y) < 3)
[res_x, idx_of_result] = min(y);
return;
end
%make sure the x and y are sorted in increasing X-order
if (nargin > 1 && any(diff(x)<0))
[~,idx]=sort(x);
y = y(idx);
x = x(idx);
else
idx = 1:length(x);
end
%the code below "unwraps" the repeated regress(y,x) calls. It's
%significantly faster than the former for longer y's
%
%figure out the m and b (in the y=mx+b sense) for the "left-of-knee"
sigma_xy = cumsum(x.*y);
sigma_x = cumsum(x);
sigma_y = cumsum(y);
sigma_xx = cumsum(x.*x);
n = (1:length(y))';
det = n.*sigma_xx-sigma_x.*sigma_x;
mfwd = (n.*sigma_xy-sigma_x.*sigma_y)./det;
bfwd = -(sigma_x.*sigma_xy-sigma_xx.*sigma_y) ./det;
%figure out the m and b (in the y=mx+b sense) for the "right-of-knee"
sigma_xy = cumsum(x(end:-1:1).*y(end:-1:1));
sigma_x = cumsum(x(end:-1:1));
sigma_y = cumsum(y(end:-1:1));
sigma_xx = cumsum(x(end:-1:1).*x(end:-1:1));
n = (1:length(y))';
det = n.*sigma_xx-sigma_x.*sigma_x;
mbck = flipud((n.*sigma_xy-sigma_x.*sigma_y)./det);
bbck = flipud(-(sigma_x.*sigma_xy-sigma_xx.*sigma_y) ./det);
%figure out the sum of per-point errors for left- and right- of-knee fits
error_curve = nan(size(y));
for breakpt = 2:length(y-1)
delsfwd = (mfwd(breakpt).*x(1:breakpt)+bfwd(breakpt))-y(1:breakpt);
delsbck = (mbck(breakpt).*x(breakpt:end)+bbck(breakpt))-y(breakpt:end);
%disp([sum(abs(delsfwd))/length(delsfwd), sum(abs(delsbck))/length(delsbck)])
if (use_absolute_dev_p)
% error_curve(breakpt) = sum(abs(delsfwd))/sqrt(length(delsfwd)) + sum(abs(delsbck))/sqrt(length(delsbck));
error_curve(breakpt) = sum(abs(delsfwd))+ sum(abs(delsbck));
else
error_curve(breakpt) = sqrt(sum(delsfwd.*delsfwd)) + sqrt(sum(delsbck.*delsbck));
end
end
%find location of the min of the error curve
[~,loc] = min(error_curve);
res_x = x(loc);
idx_of_result = idx(loc);
end
|
github | compneuro-da/rsHRF-master | tbx_cfg_rsHRF.m | .m | rsHRF-master/tbx_cfg_rsHRF.m | 38,917 | utf_8 | f8345a7a0e695df20bd7cf743caa5b5e | function HRFrs = tbx_cfg_rsHRF
% Configuration file for toolbox 'rsHRF'
% https://github.com/guorongwu/rsHRF
% $Id: rsHRF.m
if ~isdeployed
addpath(fullfile(spm('Dir'),'toolbox','rsHRF'));
end
% ---------------------------------------------------------------------
% NIfTI Data
% ---------------------------------------------------------------------
GNIfTI_Data = cfg_files;
GNIfTI_Data.tag = 'images';
GNIfTI_Data.name = 'Scans';
GNIfTI_Data.help = {'Select NIfTI/GIfTI images.'};
GNIfTI_Data.filter = {'image','mesh'};
GNIfTI_Data.ufilter = '.*';
GNIfTI_Data.num = [1 inf];
GNIfTI_Data.help = {'3D or 4D NIfTI images; 2D GIfTI file (.gii)'
'or select 1st volume/frame of a 4D NIfTI file,'
'we will expand all the volumes from this file.'};
% ---------------------------------------------------------------------
% ROI signal Data
% ---------------------------------------------------------------------
Signal_file = cfg_files;
Signal_file.tag = 'sigdata';
Signal_file.name = 'Preprocessed ROI signals';
Signal_file.help = {'Select ROI signal files.'};
Signal_file.filter = 'any';
Signal_file.ufilter = '.*';
Signal_file.num = [1 1];
Signal_file.help = { 'Select the *.txt/*.mat file(s) containing your ROI signal.' };
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Variable Name in the Mat-file';
name.help = {
'Only for *.mat file'
'Enter the variable name of your ROI signals in Mat file; eg. ''data'' '};
name.strtype = 's';
name.val = {''};
name.num = [1 inf];
Signal_Dat = cfg_branch;
Signal_Dat.tag = 'Datasig';
Signal_Dat.name = 'Data';
Signal_Dat.val = {Signal_file, name};
Signal_Dat.help = {
'Select the *.txt/*.mat file(s) containing details of your ROI signal.'
'You will need to enter the "Variable Name in Mat-file" if you select Mat-file '
};
Signal_Data = cfg_repeat;
Signal_Data.tag = 'Data';
Signal_Data.name = 'Data';
Signal_Data.values = {Signal_Dat};
Signal_Data.num = [1 inf];
Signal_Data.help = {
'The same parameters specified below '
'will be applied to all data'
};
% ---------------------------------------------------------------------
% odir Output Directory
% ---------------------------------------------------------------------
Outdir = cfg_files;
Outdir.tag = 'outdir';
Outdir.name = 'Output Directory';
Outdir.help = {'Select the directory where write analysis results.'};
Outdir.filter = 'dir';
Outdir.ufilter = '.*';
Outdir.num = [1 1];
Outdir.val = {{''}};
% ---------------------------------------------------------------------
% RT Interscan interval
% ---------------------------------------------------------------------
TR = cfg_entry;
TR.tag = 'TR';
TR.name = 'TR';
TR.help = {'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume and the same plane in the next volume. It is assumed to be constant throughout.'};
TR.strtype = 'r';
TR.num = [1 1];
% ---------------------------------------------------------------------
% Bands
% ---------------------------------------------------------------------
Bands = cfg_entry;
Bands.tag = 'bands';
Bands.name = 'Band-pass filter(Hz)';
Bands.help = {'0.01 ~ 0.1 Hz. '};
Bands.strtype = 'e';
Bands.val = {[0.01, 0.1]};
Bands.num = [1 2];
TR2filter = TR;
TR2filter.val = {nan};
TR2filter.help = {'Keep "nan" if it has been specified in HRF estimation step.'};
% ---------------------------------------------------------------------
% Bandfilters
% ---------------------------------------------------------------------
Bandfilter = cfg_repeat;
Bandfilter.tag = 'BPF';
Bandfilter.name = 'Band-pass Filter';
Bandfilter.help = {'Band-pass Filter.'};
Bandfilter.values = {Bands,TR2filter};
Bandfilter.num = [0 2];
% ---------------------------------------------------------------------
% Despiking
% ---------------------------------------------------------------------
Despiking = cfg_menu;
Despiking.tag = 'Despiking';
Despiking.name = 'Despiking';
Despiking.help = {'Temporal despiking with a hyperbolic tangent squashing function'};
Despiking.labels = {'No', 'Yes'};
Despiking.values = {0,1};
Despiking.val = {0};
% ---------------------------------------------------------------------
% Detrend
% ---------------------------------------------------------------------
Detrending = cfg_menu;
Detrending.tag = 'Detrend';
Detrending.name = 'Polynomial Detrending';
Detrending.help = {'...'};
Detrending.labels = {'No', 'Linear', '2nd order Poly', '3rd order Poly'};
Detrending.values = {0,1,2,3};
Detrending.val = {0};
% ---------------------------------------------------------------------
% Despiking
% ---------------------------------------------------------------------
ROI1st = cfg_menu;
ROI1st.tag = 'which1st';
ROI1st.name = 'Which First?';
ROI1st.labels = {
'First denoise then generate ROI signal'
'First generate ROI signal then denoise'
'No ROI analysis'
}';
ROI1st.values = {1,2,3};
ROI1st.val = {3};
% ---------------------------------------------------------------------
% ROI
% ---------------------------------------------------------------------
ROIs_coordinate = cfg_entry;
ROIs_coordinate.tag = 'ROI';
ROIs_coordinate.name = 'ROI (x,y,z,radius [in mm])';
ROIs_coordinate.strtype = 'e';
ROIs_coordinate.num = [inf 4];
ROIs_coordinate.val = {[4,-53,26,6];};
ROIs_coordinate.help = {'ROI (x, y & z, in mm, with k mm radius)'};
% ---------------------------------------------------------------------
% ROI mask
% ---------------------------------------------------------------------
ROImasks = cfg_files;
ROImasks.tag = 'images';
ROImasks.name = 'ROI mask images';
ROImasks.help = {'Select ROI mask images (>=1).'};
ROImasks.filter = 'image';
ROImasks.ufilter = '.*';
ROImasks.val = {{''}};
ROImasks.num = [1 inf];
ROImasks.help = {'you can select more than one NIfTI image'};
% ---------------------------------------------------------------------
% White matter/CSF/Whole brain mask
% ---------------------------------------------------------------------
covmasks = ROImasks ;
covmasks.name = 'Covariate images (white matter, CSF, whole brain mask etc.)';
% ---------------------------------------------------------------------
% Mean or Principal component for covariate images
% ---------------------------------------------------------------------
mpc = cfg_entry;
mpc.tag = 'mpc';
mpc.name = 'Mean or Eigenvariate';
mpc.help = {'0: mean signal'
'1: 1st eigenvariate (principal component,PC)'
'5: 1st to 5th eigenvariates'
'[0 1 2]: Extract mean from the 1st mask, 1st PC from 2nd mask, 1st to 2nd PCs from 3rd mask'
};
mpc.strtype = 'e';
mpc.val = {[0]};
mpc.num = [1 inf];
WMCSFmasks = cfg_branch;
WMCSFmasks.tag = 'imcov';
WMCSFmasks.name = 'Image Covariates';
WMCSFmasks.help = {'Only for NIfTI data'
'Image mask to extract Regressors that may confound the data.'};
WMCSFmasks.val = {covmasks, mpc};
% ---------------------------------------------------------------------
% multi_reg Multiple regressors
% ---------------------------------------------------------------------
multi_reg = cfg_files;
multi_reg.tag = 'multi_reg';
multi_reg.name = 'Multiple regressors';
multi_reg.val = {{''}};
multi_reg.help = {
'Select the *.txt/*.mat file(s) containing details of your multiple regressors. '
'If you have multiple regressors eg. realignment parameters (rp_*.txt), then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. '
'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the regressors. Each column of R will contain a different regressor.'
''
}';
multi_reg.filter = 'mat';
multi_reg.ufilter = '.*';
multi_reg.num = [0 Inf];
% ---------------------------------------------------------------------
% generic Regressors
% ---------------------------------------------------------------------
covreg = cfg_repeat;
covreg.tag = 'generic';
covreg.name = 'Nuisance Covariates';
covreg.help = {'Regressors that may confound the data.'};
covreg.values = {multi_reg WMCSFmasks};
covreg.num = [0 Inf];
% ---------------------------------------------------------------------
% ROI Atlas
% ---------------------------------------------------------------------
Atlas = cfg_files;
Atlas.tag = 'atlas';
Atlas.name = 'Atlas image';
Atlas.help = {'Select a Atlas image.'};
Atlas.filter = 'image';
Atlas.ufilter = '.*';
Atlas.val = {{''}};
Atlas.num = [1 1];
% ---------------------------------------------------------------------
% ROI Mesh Atlas
% ---------------------------------------------------------------------
Atlasmesh = cfg_files;
Atlasmesh.tag = 'meshatlas';
Atlasmesh.name = 'Mesh Atlas';
Atlasmesh.help = {'Select a surface based Atlas.'};
Atlasmesh.filter = 'mesh';
Atlasmesh.ufilter = '.*';
Atlasmesh.val = {{''}};
Atlasmesh.num = [1 1];
% ---------------------------------------------------------------------
% ROI Mesh
% ---------------------------------------------------------------------
maskmesh = cfg_files;
maskmesh.tag = 'meshmask';
maskmesh.name = 'Mesh Mask';
maskmesh.help = {'Select a surface based mask.'};
maskmesh.filter = 'mesh';
maskmesh.ufilter = '.*';
maskmesh.val = {{''}};
maskmesh.num = [1 1];
% ---------------------------------------------------------------------
% ROI All together
% ---------------------------------------------------------------------
genericROI = cfg_repeat;
genericROI.tag = 'genericROI';
genericROI.name = 'ROI (Coordinate / NIfTI)';
genericROI.help = {
'Select ROIs (Coordinates / NIfTI)'
}';
genericROI.values = {ROIs_coordinate ROImasks Atlas};
genericROI.num = [1 Inf];
% ---------------------------------------------------------------------
% SurfROI All together
% ---------------------------------------------------------------------
genericSurfROI = cfg_repeat;
genericSurfROI.tag = 'genericROI';
genericSurfROI.name = 'ROI (GIfTI)';
genericSurfROI.help = {
'Select ROIs (GIfTI)'
}';
genericSurfROI.values = {maskmesh Atlasmesh};
genericSurfROI.num = [1 Inf];
% ---------------------------------------------------------------------
% Denoising
% ---------------------------------------------------------------------
Denoising = cfg_branch;
Denoising.tag = 'Denoising';
Denoising.name = 'Denoising';
Denoising.val = {covreg, Detrending, Bandfilter, Despiking,ROI1st};
Denoising.help = {'Remove possible confounds.'};
Denoising2 = Denoising;
Denoising2.val = {covreg, Detrending, Bandfilter, Despiking};
Denoising_surf = Denoising;
Denoising_surf.val = {covreg, Detrending, Bandfilter, Despiking, ROI1st};
% ---------------------------------------------------------------------
% Despiking
% ---------------------------------------------------------------------
rmoutlier = cfg_menu;
rmoutlier.tag = 'rmoutlier';
rmoutlier.name = 'Remove Outlier& Inpaint 3D';
rmoutlier.help = {'Remove Outlier in HRF parameters (replaced by nan ) and inpaint nan value by inpaint_nans3.m'};
rmoutlier.labels = {'No', 'Yes'};
rmoutlier.values = {0,1};
rmoutlier.val = {1};
% ---------------------------------------------------------------------
% Explicit Mask
% ---------------------------------------------------------------------
brainmask = cfg_files;
brainmask.tag = 'mask';
brainmask.name = 'Explicit Mask';
brainmask.help = {'Specify an image for expicity masking the analysis.'};
brainmask.filter = {'image','mesh'};
brainmask.ufilter = '.*';
brainmask.val = {{''}};
brainmask.num = [1 1];
%--------------------------------------------------------------------------
% prefix Filename Prefix
%--------------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename prefix';
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.help = {'String to be prepended to the filenames of the HRF deconvolved image file(s). Default prefix is ''Deconv_''.'};
prefix.val = {'Deconv_'};
%--------------------------------------------------------------------------
% HRF model
%--------------------------------------------------------------------------
hrfm = cfg_menu;
hrfm.tag = 'hrfm';
hrfm.name = 'HRF Basis Functions';
hrfm.labels = {
'Canonical HRF (with time derivative)'
'Canonical HRF (with time and dispersion derivatives)'
'Gamma Functions'
'Fourier Set'
'Fourier Set (Hanning)'
'Finite Impulse Response (FIR)'
'Smooth FIR'
}';
hrfm.values = {1,2,3,4,5,6,7};
hrfm.val = {2};
hrfm.help = {
'The canonical HRF combined with time and dispersion derivatives comprise an ''informed'' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivate terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary.'
'The Fourier set consists of a constant and KF sine and KF cosine functions of harmonic periods T, T/2,T/KF seconds(i.e. K = 2KF + 1 basis functions). Linear combinations of the (orthonormal) FIR or Fourier basis functions can capture any shape of response up to a specified frequency (KF /T in the case of the Fourier set).'
'The HRF is assumed to be bounded at zero for t<0 and t>T , the Fourier basis functions can also be windowed (e.g. by a Hanning window) within this range.'
'A set of gamma functions of increasing dispersions can be obtained by increasing p (p is an integer phase-delay, the peak delay is given by pd, and the dispersion by pd^2, d is the time-scaling). In SPM, these functions (as with all basis functions) are orthogonalized with respect to one another.'
'Impulse Response (FIR) set captures any shape of response up to a given frequency limit.'
'Smooth FIR: add a gaussian prior on the filter parameter alpha - It filtered out some noise of the standard FIR.'
};
% ---------------------------------------------------------------------
% length of HRF {seconds}
% ---------------------------------------------------------------------
hrflen = cfg_entry;
hrflen.tag = 'hrflen';
hrflen.name = 'Length of HRF (seconds)';
hrflen.help = {'Enter the length/duration of HRF {seconds}, i.e. Post-stimulus window length (in seconds).'};
hrflen.strtype = 'r';
hrflen.num = [Inf 1];
hrflen.val = {32};
% ---------------------------------------------------------------------
% Number of basis functions
% ---------------------------------------------------------------------
num_basis = cfg_entry;
num_basis.tag = 'num_basis';
num_basis.name = 'Number of basis functions (k)';
num_basis.help = {'Only setting for ''Gamma Functions'' (k), ''Fourier Set'' (2k+1), ''Fourier Set (Hanning)'' (2k+1)'};
num_basis.strtype = 'n';
num_basis.num = [1 1];
num_basis.val = {nan};
% ---------------------------------------------------------------------
% Minimum & Maximum delay
% ---------------------------------------------------------------------
mdelay = cfg_entry;
mdelay.tag = 'mdelay';
mdelay.name = 'Minimum & Maximum delay (seconds)';
mdelay.help = {'4 ~ 8 s'};
mdelay.strtype = 'e';
mdelay.val = {[4, 8]};
mdelay.num = [1 2];
% ---------------------------------------------------------------------
% Threshold for event detection
% ---------------------------------------------------------------------
thr = cfg_entry;
thr.tag = 'thr';
thr.name = 'Threshold (SD) for event detection';
thr.help = {'default Threshold = 1, i.e. local peaks and ( amplitude > mean + Threshold*standard deviation threshold) were selected as the candicate events'};
thr.strtype = 'r';
thr.val = {1};
thr.num = [1 1];
% ---------------------------------------------------------------------
% local spontaneou event definition
% ---------------------------------------------------------------------
localK = cfg_entry;
localK.tag = 'localK';
localK.name = 'K (local peak f([-K:K]+t)<=f(t) )';
localK.help = {'default K = 2, i.e. local peaks definition f([-2: 2]+t) <= f(t)'};
localK.strtype = 'r';
localK.val = {2};% local peak, f([-2: 2]+t) <= f(t)
localK.num = [1 1];
% ---------------------------------------------------------------------
% Temporal mask
% ---------------------------------------------------------------------
tmask = cfg_entry;
tmask.tag = 'tmask';
tmask.name = 'Temporal mask for event detection';
tmask.help = {'default no mask for BOLD event detect (using nan). 0(exclude) / 1(include) for point process.'
'e.g. [0 1 0 0 1 1 1 1], ssame length with BOLD signal'};
tmask.strtype = 'r';
tmask.val = {nan};
tmask.num = [1 inf];
% ---------------------------------------------------------------------
% cvi Serial correlations
% ---------------------------------------------------------------------
cvi = cfg_menu;
cvi.tag = 'cvi';
cvi.name = 'Serial correlations';
cvi.help = {
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during parameter estimation. '
% 'This estimate assumes the same correlation structure for each voxel, within each session. ReML estimates are then used to correct for non-sphericity during inference by adjusting the statistics and degrees of freedom appropriately. The discrepancy between estimated and actual intrinsic (i.e. prior to filtering) correlations are greatest at low frequencies. Therefore specification of the high-pass filter is particularly important. '
% 'Serial correlation can be ignored if you choose the ''none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noisemodel (AR model order) is made under the estimation options. '
}';
cvi.labels = {'none', 'AR(1)', 'AR(2)','AR(3)'};
cvi.values = {0,1,2,3};
cvi.val = {0};
% ---------------------------------------------------------------------
% fmri_t Microtime resolution
% ---------------------------------------------------------------------
fmri_t = cfg_entry;
fmri_t.tag = 'fmri_t';
fmri_t.name = 'Microtime resolution';
fmri_t.help = {
'value >1 does not work for FIR or sFIR'
''
'The microtime resolution, t, is the number of time-bins per scan used when building regressors. '
'If you have performed slice-timing correction, change this parameter to match the number of slices specified there; otherwise, you would typically not need to change this.'
''
}';
fmri_t.strtype = 'n';
fmri_t.num = [1 1];
fmri_t.val = {1};
% ---------------------------------------------------------------------
% fmri_t0 Microtime onset
% ---------------------------------------------------------------------
fmri_t0 = cfg_entry;
fmri_t0.tag = 'fmri_t0';
fmri_t0.name = 'Microtime onset';
fmri_t0.help = {
'value >1 works for Canon2DD or CanonTD'
''
'The microtime onset, t0, is the reference time-bin at which the regressors are resampled to coincide with data acquisition.'
'If you have performed slice-timing correction, you must change this parameter to match the reference slice specified there.'
'Otherwise, you might still want to change this if you have non-interleaved acquisition and you wish to sample the regressors so that they are appropriate for a slice in a particular part of the brain.'
'For example, if t0 = 1, then the regressors will be appropriate for the first slice; if t0=t, then the regressors will be appropriate for the last slice.'
'Setting t0 = t/2 is a good compromise if you are interested in slices at the beginning and end of the acquisition, or if you have interleaved data, or if you have 3D EPI data.'
''
}';
fmri_t0.strtype = 'n';
fmri_t0.num = [1 1];
fmri_t0.val = {1};
% HRF deconvolution
%--------------------------------------------------------------------------
HRFdeconv = cfg_menu;
HRFdeconv.tag = 'hrfdeconv';
HRFdeconv.name = 'HRF Deconvolution';
HRFdeconv.labels = {
'HRF Deconvolution on Unfiltered Data'
'HRF Deconvolution on Filtered Data'
'DO NOT Perform HRF Deconvolution'
}';
HRFdeconv.values = {1,2,3};
HRFdeconv.val = {1};
HRFdeconv.help = {'HRF deconvolution on filtered or unfiltered data'};
% ---------------------------------------------------------------------
% HRF estimation
% ---------------------------------------------------------------------
HRFE = cfg_branch;
HRFE.tag = 'HRFE';
HRFE.name = 'HRF estimation';
HRFE.val = {hrfm, TR, hrflen, num_basis, mdelay, cvi, fmri_t, fmri_t0,thr,localK, tmask, HRFdeconv};
HRFE.help = {'HRF estimation.'};
% ---------------------------------------------------------------------
% save deconvolved signal
% ---------------------------------------------------------------------
deconv_save = cfg_menu;
deconv_save.tag = 'deconv_save';
deconv_save.name = 'Save Deconvolved Data';
deconv_save.labels = {'No', 'Yes'};
deconv_save.values = {0,1};
deconv_save.val = {1};
deconv_save.help = {'...'};
% ---------------------------------------------------------------------
% save HRF in mat-file
% ---------------------------------------------------------------------
hrfmat_save = deconv_save;
hrfmat_save.tag = 'hrfmat_save';
hrfmat_save.name = 'Save HRF mat-file';
% ---------------------------------------------------------------------
% save HRF in NIfTI-file
% ---------------------------------------------------------------------
hrfnii_save = deconv_save;
hrfnii_save.tag = 'hrfnii_save';
hrfnii_save.name = 'Save HRF NIfTI/GIfTI-file';
% ---------------------------------------------------------------------
% save Job parameters in mat-file
% ---------------------------------------------------------------------
job_save = deconv_save;
job_save.tag = 'job_save';
job_save.name = 'Save job parameters';
% ---------------------------------------------------------------------
% Save files
% ---------------------------------------------------------------------
Datasave = cfg_branch;
Datasave.tag = 'savedata';
Datasave.name = 'Save Data';
Datasave.val = {deconv_save,hrfmat_save,hrfnii_save, job_save};
Datasave.help = {'Save files.'};
DatasaveROI = Datasave;
DatasaveROI.val = {deconv_save,hrfmat_save, job_save};
% ---------------------------------------------------------------------
% seed to voxels or ROI2ROI
% ---------------------------------------------------------------------
seedROI = cfg_menu;
seedROI.tag = 'Seed_ROI';
seedROI.name = 'Seed or ROI';
seedROI.help = {'Seed: 1 to n'; ' ROI: n to n'};
seedROI.labels = {'Seed to voxels', 'ROI to ROI'};
seedROI.values = {0,1};
seedROI.val = {0};
seedROIsurf = seedROI;
seedROIsurf.labels = {'Seed to vertices', 'ROI to ROI'};
% ---------------------------------------------------------------------
% connectivity method FC
% ---------------------------------------------------------------------
FCM = cfg_menu;
FCM.tag = 'method';
FCM.name = 'Method';
FCM.help = {'...'};
FCM.labels = {'Pearson Correlation', 'Pearson Partial Correlation (only for ROIs)', 'Spearman Correlation', 'Spearman Partial Correlation (only for ROIs)'};
FCM.values = {4,5,6,7};
FCM.val = {4};
% ---------------------------------------------------------------------
% connectivity method GC
% ---------------------------------------------------------------------
GCM = FCM;
GCM.labels = {'Pairwise GC(Granger causality)', 'Conditional GC (only for ROIs)', 'Partially Conditioned GC (only for ROIs)'};
GCM.values = {1,2,3};
GCM.val = {1};
% ---------------------------------------------------------------------
% data for connectivity
% ---------------------------------------------------------------------
CONNData = cfg_menu;
CONNData.tag = 'data4conn';
CONNData.name = 'Data for Connectivity';
CONNData.help = {'Select BOLD or/and Deconvolved BOLD'};
CONNData.labels = {'BOLD', 'Deconvolved BOLD', 'BOLD and Deconvolved BOLD'};
CONNData.values = {1,2,3};
CONNData.val = {2};
% ---------------------------------------------------------------------
% Model order for GC
% ---------------------------------------------------------------------
Morder = cfg_entry;
Morder.tag = 'morder';
Morder.name = 'Model order for GC';
Morder.help = {'default model order = 1, input only for Granger causality analysis'};
Morder.strtype = 'r';
Morder.val = {1};
Morder.num = [1 1];
% ---------------------------------------------------------------------
% Information for PCGC
% ---------------------------------------------------------------------
ndinfo = cfg_entry;
ndinfo.tag = 'ndinfo';
ndinfo.name = 'Parameters for PCGC';
ndinfo.help = {'Number of conditional variable (nd), Maximum nd'
'Parameters for Partially Conditioned Granger Causality Analysis'
'Recommended value: nd = 6, maximum nd = nd+1'};
ndinfo.strtype = 'r';
ndinfo.val = {[nan nan]};
ndinfo.num = [1 2];
%--------------------------------------------------------------------------
% prefix Connectivity Prefix
%--------------------------------------------------------------------------
conname = prefix;
conname.val = {'Conn_'};
conname.num = [1 Inf];
conname.help ={'String to be prepended to the filenames of the connectivity file(s). Default prefix is "Conn_".'};
% ---------------------------------------------------------------------
% Connectivity Analysis FC
% ---------------------------------------------------------------------
FCA = cfg_branch;
FCA.tag = 'conn';
FCA.name = 'FC';
FCA.val = {CONNData, seedROI, genericROI, FCM, conname};
FCA.help = {'Functional connectivity analysis.'};
FCA2 = FCA;
FCA2.val = {seedROI, genericROI, FCM, conname};
FCAsurf = FCA;
FCAsurf.val = {CONNData, seedROIsurf, genericSurfROI, FCM, conname};
FCAsurf2 = FCA;
FCAsurf2.val = {seedROIsurf, genericSurfROI, FCM, conname};
FCAROI = FCA;
FCAROI.val = {CONNData, FCM, conname};
FCAROI2 = FCAROI;
FCAROI2.val = {FCM, conname};
% ---------------------------------------------------------------------
% Connectivity Analysis GC
% ---------------------------------------------------------------------
GCA = cfg_branch;
GCA.tag = 'connG';
GCA.name = 'GC';
GCA.val = {CONNData, seedROI, genericROI, GCM, Morder, ndinfo, conname};
GCA.help = {'Granger causality analysis.'};
GCA2 = GCA;
GCA2.val = {seedROI, genericROI, GCM, Morder, ndinfo, conname};
GCAsurf = GCA;
GCAsurf.val = {CONNData, seedROIsurf, genericSurfROI, GCM, Morder, ndinfo, conname};
GCAsurf2 = GCA;
GCAsurf2.val = {seedROIsurf, genericSurfROI, GCM, Morder, ndinfo, conname};
GCAROI = GCA;
GCAROI.val = {CONNData, GCM, Morder, ndinfo, conname};
GCAROI2 = GCAROI;
GCAROI2.val = {GCM, Morder, ndinfo,conname};
% connectivity
% ---------------------------------------------------------------------
cona = cfg_repeat;
cona.tag = 'connectivity';
cona.name = 'Connectivity Analysis';
cona.help = {'Granger causality or Functional connectivity analysis.'};
cona.values = {FCA,GCA};
cona.num = [0 inf];
cona2 = cona;
cona2.values = {FCA2,GCA2};
conaSurf = cona;
conaSurf.values = {FCAsurf,GCAsurf};
conaSurf2= cona;
conaSurf2.values = {FCAsurf2,GCAsurf2};
connROI = cona;
connROI.values = {FCAROI, GCAROI};
connROI2 = cona;
connROI2.values = {FCAROI2, GCAROI2};
% ---------------------------------------------------------------------
% ROI-wise HRF deconvolution
% ---------------------------------------------------------------------
ROI_rsHRF = cfg_exbranch;
ROI_rsHRF.tag = 'ROI_rsHRF';
ROI_rsHRF.name = 'ROI-wise HRF deconvolution';
ROI_rsHRF.val = {GNIfTI_Data, Denoising, genericROI, HRFE, brainmask, connROI, Outdir, DatasaveROI, prefix};
ROI_rsHRF.prog = @wgr_vox_ROI_rsHRF_conn;
ROI_rsHRF.help = {'NIfTI data'};
% ---------------------------------------------------------------------
% (Surface) ROI-wise HRF deconvolution
% ---------------------------------------------------------------------
SurfROI_rsHRF = cfg_exbranch;
SurfROI_rsHRF.tag = 'SurfROI_rsHRF';
SurfROI_rsHRF.name = '(Surface)ROI-wise HRF deconvolution';
SurfROI_rsHRF.val = {GNIfTI_Data, Denoising_surf, genericSurfROI, HRFE, brainmask, connROI, Outdir, DatasaveROI, prefix};
SurfROI_rsHRF.prog = @wgr_vertex_ROI_rsHRF_conn;
% ---------------------------------------------------------------------
% ROI-wise CONN
% ---------------------------------------------------------------------
ROI_conn = cfg_exbranch;
ROI_conn.tag = 'ROI_conn';
ROI_conn.name = 'ROI-wise Connectivity Analysis';
ROI_conn.val = {GNIfTI_Data, Denoising, genericROI, brainmask, connROI2, Outdir,job_save};
ROI_conn.prog = @wgr_vox_ROI_rsHRF_conn;
ROI_conn.help = {'NIfTI data'};
% ---------------------------------------------------------------------
% (Surface) ROI-wise CONN
% ---------------------------------------------------------------------
SurfROI_conn = cfg_exbranch;
SurfROI_conn.tag = 'SurfROI_conn';
SurfROI_conn.name = '(Surface)ROI-wise Connectivity Analysis';
SurfROI_conn.val = {GNIfTI_Data, Denoising, genericSurfROI, brainmask, connROI2, Outdir,job_save};
SurfROI_conn.prog = @wgr_vertex_ROI_rsHRF_conn;
SurfROI_conn.help = {'GIfTI data'};
% ---------------------------------------------------------------------
% voxel-wise HRF deconvolution
% ---------------------------------------------------------------------
vox_rsHRF = cfg_exbranch;
vox_rsHRF.tag = 'vox_rsHRF';
vox_rsHRF.name = 'Voxel-wise HRF deconvolution';
vox_rsHRF.val = {GNIfTI_Data, Denoising, HRFE, rmoutlier,brainmask, cona, Outdir, Datasave, prefix};
vox_rsHRF.prog = @wgr_vox_ROI_rsHRF_conn;
vox_rsHRF.help = {'NIfTI data'}; %{'Voxel-wise HRF deconvolution'};
% ---------------------------------------------------------------------
% vertex-wise HRF deconvolution
% ---------------------------------------------------------------------
mesh_rsHRF = cfg_exbranch;
mesh_rsHRF.tag = 'mesh_rsHRF';
mesh_rsHRF.name = 'Vertex-wise HRF deconvolution';
mesh_rsHRF.val = {GNIfTI_Data, Denoising, HRFE, brainmask, conaSurf, Outdir, Datasave, prefix};
mesh_rsHRF.prog = @wgr_vertex_ROI_rsHRF_conn;
mesh_rsHRF.help = {'GIfTI data'}; %{'Vertex-wise HRF deconvolution'};
% ---------------------------------------------------------------------
% voxel-wise CONN
% ---------------------------------------------------------------------
vox_conn = cfg_exbranch;
vox_conn.tag = 'vox_conn';
vox_conn.name = 'Voxel-wise Connectivity Analysis';
vox_conn.val = {GNIfTI_Data, Denoising, brainmask, cona2, Outdir, job_save};
vox_conn.prog = @wgr_vox_ROI_rsHRF_conn;
vox_conn.help = {'NIfTI data'};
% ---------------------------------------------------------------------
% vertex-wise CONN
% ---------------------------------------------------------------------
mesh_conn = cfg_exbranch;
mesh_conn.tag = 'mesh_conn';
mesh_conn.name = 'Vertex-wise Connectivity Analysis';
mesh_conn.val = {GNIfTI_Data, Denoising, brainmask, conaSurf2, Outdir, job_save};
mesh_conn.prog = @wgr_vertex_ROI_rsHRF_conn;
mesh_conn.help = {'NIfTI data'};
% ---------------------------------------------------------------------
% ROI-signal HRF deconvolution
% ---------------------------------------------------------------------
sig_rsHRF = cfg_exbranch;
sig_rsHRF.tag = 'sig_rsHRF';
sig_rsHRF.name = 'ROI signal HRF deconvolution';
sig_rsHRF.val = {Signal_Data, Denoising2, HRFE, connROI, Outdir, DatasaveROI, prefix};
sig_rsHRF.help = {'..'};
sig_rsHRF.prog = @wgr_sig_rsHRF_conn;
sig_rsHRF.help = {'Please DO NOT select NIFTI files in Nuisance Covariates!'}; %{'ROI-signal HRF deconvolution'
%'Please DO NOT select NIFTI files in Nuisance Covariates!'
% ---------------------------------------------------------------------
% ROI-signal CONN
% ---------------------------------------------------------------------
sig_conn = cfg_exbranch;
sig_conn.tag = 'sig_conn';
sig_conn.name = 'ROI-signal Connectivity Analysis';
sig_conn.val = {Signal_Data, Denoising2, connROI2, Outdir,job_save};
sig_conn.help = {'..'};
sig_conn.prog = @wgr_sig_rsHRF_conn;
sig_conn.help = {'Please DO NOT select NIFTI files in Nuisance Covariates!'};
% ---------------------------------------------------------------------
% HRF Mat-files
% ---------------------------------------------------------------------
HRF_mat = cfg_files;
HRF_mat.tag = 'HRF_mat';
HRF_mat.name = 'HRF Mat-files';
HRF_mat.val = {{''}};
HRF_mat.help = {
'Select individual *.mat file(s) containing HRF shapes (generate by rsHRF toolbox). '
'Add a new ''HRF Mat-files'' for different groups (Plot each group HRF shapes seperately)'
}';
HRF_mat.filter = 'mat';
HRF_mat.ufilter = '.*';
HRF_mat.num = [0 Inf];
% ---------------------------------------------------------------------
% Statistical NIfTI file
% ---------------------------------------------------------------------
snifti = cfg_files;
snifti.tag = 'stat_nii';
snifti.name = 'Statistical Image';
snifti.filter = {'image'};
snifti.ufilter = '.*';
snifti.num = [1 1];
snifti.help = {'Select the statistical image (NIfTI).'
'a statistical image for voxel location.'};
% ---------------------------------------------------------------------
% Statistical NIfTI file
% ---------------------------------------------------------------------
unifti = cfg_files;
unifti.tag = 'underlay_nii';
unifti.name = 'Underlay Image';
unifti.filter = {'image'};
unifti.ufilter = '.*';
unifti.num = [1 1];
unifti.help = {'Select the underlay image (NIfTI).'};
% default_nii = fullfile(spm('Dir'),'canonical','avg152T1.nii');
% ---------------------------------------------------------------------
% GroupID
% ---------------------------------------------------------------------
GroupID = cfg_entry;
GroupID.tag = 'GroupID';
GroupID.name = 'Group ID';
GroupID.help = {'Add a Group ID if you include all different group file together in one ''HRF Mat-files'' ,'
'e.g. 1 1 2 2 3 3'};
GroupID.strtype = 'e';
GroupID.val = {[]};
GroupID.num = [1 inf];
% ---------------------------------------------------------------------
% Group HRF files
% ---------------------------------------------------------------------
HRF_mats = cfg_repeat;
HRF_mats.tag = 'display_mat';
HRF_mats.name = 'HRF mat-files';
HRF_mats.help = {'Select individual Mat-files for HRF shape plotting.'};
HRF_mats.values = {HRF_mat};
HRF_mats.num = [0 Inf];
% ---------------------------------------------------------------------
% Display HRF file
% ---------------------------------------------------------------------
HRF_Display = cfg_exbranch;
HRF_Display.tag = 'display_HRF';
HRF_Display.name = 'HRF Viewer';
HRF_Display.val = {unifti, snifti, HRF_mats};
HRF_Display.prog = @wgr_vox_rsHRF_display;
HRF_Display.help = {'Select the NIfTI files and HRF Mat-files(grouped according to the statistical maps)'};
% ---------------------------------------------------------------------
% rsHRF deconvolution & connectivity analysis
% ---------------------------------------------------------------------
HRFrs = cfg_choice;
HRFrs.tag = 'rsHRF';
HRFrs.name = 'rsHRF';
HRFrs.help = {'resting state HRF deconvolution and connectivity analysis.'};
HRFrs.values = {vox_rsHRF, mesh_rsHRF, ROI_rsHRF, SurfROI_rsHRF, sig_rsHRF, vox_conn, mesh_conn, ROI_conn, SurfROI_conn, sig_conn, HRF_Display};
%======================================================================
function wgr_vox_ROI_rsHRF_conn(job)
rsHRF(job,'volume');
%======================================================================
function wgr_vertex_ROI_rsHRF_conn(job)
rsHRF(job,'mesh')
%======================================================================
function wgr_sig_rsHRF_conn(job)
rsHRF(job,'sig')
%======================================================================
function wgr_vox_rsHRF_display(job)
rsHRF(job,'display')
|
github | compneuro-da/rsHRF-master | rsHRF_estimation_FIR.m | .m | rsHRF-master/rsHRF_estimation_FIR.m | 5,644 | utf_8 | f525c14ab84e3a3979b752846777a816 | function [beta_rshrf,event_bold] = rsHRF_estimation_FIR(data,para,temporal_mask,flag_parfor)
% temporal_mask: generated from scrubbing.
% By: Guo-Rong Wu ([email protected]).
% Faculty of Psychology, Southwest University.
% History:
% - 2015-04-17 - Initial version.
if nargin<4
flag_parfor = 1;
end
para.temporal_mask=temporal_mask;
[N,nvar] = size(data);
% warning off
beta_rshrf = cell(1,nvar);
event_bold= cell(1,nvar);
if flag_parfor
parfor i=1:nvar
[beta_rshrf{i}, event_bold{i}] = wgr_FIR_estimation_HRF(data(:,i),para,N);
end
else
for i=1:nvar
[beta_rshrf{i}, event_bold{i}] = wgr_FIR_estimation_HRF(data(:,i),para,N);
end
end
beta_rshrf =cell2mat(beta_rshrf);
% warning on
return
function [beta_hrf,u] = wgr_FIR_estimation_HRF(data,para,N)
if ~isfield(para,'localK')
if para.TR<=2
localK = 1;
else
localK = 2;
end
else
localK = para.localK;
end
u = rsHRF_find_event_vector(data,para.thr,localK,para.temporal_mask);
u = find(full(u(:)));
lag = para.lag;
nlag = length(lag);
len_bin=floor(para.len/para.TR);
hrf = zeros(len_bin+1,nlag);
Cov_E = zeros(1,nlag);
kk=1;
for i_lag=1:nlag
RR = u-i_lag; RR(RR<=0)=[];
if ~isempty(RR)
design = zeros(N,1);
design(RR) = 1;
[hrf(:,kk),Cov_E(kk)] = wgr_Fit_FIR2(design,data,para);
else
Cov_E(kk) = inf;
end
kk = kk+1;
end
[~, ind] = rsHRF_knee_pt(Cov_E); % this is a function to find the elbow point of a curve, there should be an equivalent in Python
if ind==length(Cov_E)
ind = ind-1;
end
beta_hrf = hrf(:,ind+1);
beta_hrf(end+1) = lag(ind+1);
function [hrf,res_sum] = wgr_Fit_FIR2(input,output,para)
% NN : length of impulse response
NN = floor(para.len/para.TR);
flag_sfir = double(strcmp(para.estimation,'sFIR'));
% X : convolution matrix
X = toeplitz(input, [input(1) zeros(1, NN-1)]);
X = [X ones(size(input))];
% h : impulse response estimate
if flag_sfir
MRI = wgr_smFIR(NN-1,para.TR);
sigma = 1; sMRI0 = sigma^2*MRI;
sMRI = zeros(NN+1);
sMRI(1:NN,1:NN) = sMRI0;
if ~para.AR_lag
hrf = (X'*X+sMRI)\X'*output; %smoothed solution
resid = output - X * hrf;
res_sum=cov(resid);
else
[res_sum, hrf] = wgr_glsco_sm(X,output,para.AR_lag,sMRI);
end
else
if ~para.AR_lag
hrf = X \ output;
resid = output - X * hrf;
res_sum=cov(resid);
else
[res_sum, hrf] = wgr_glsco_sm(X,output,para.AR_lag,[]);
end
end
function MRI = wgr_smFIR(nh,dt)
fwhm =7; % fwhm=7 seconds smoothing - ref. Goutte
C=(1:nh)'*(ones(1,nh));
h = sqrt(1/(fwhm/dt));
v = 0.1;
R = v*exp(-h/2*(C-C').^2);
RI = inv(R);
MRI = zeros(nh+1);
MRI(1:nh,1:nh) = RI;
return
function [res_sum, Beta] = wgr_glsco_sm(X,Y,AR_lag,sMRI,max_iter)
% Linear regression when disturbance terms follow AR(p)
% -----------------------------------
% Model:
% Yt = Xt * Beta + ut ,
% ut = Phi1 * u(t-1) + ... + Phip * u(t-p) + et
% where et ~ N(0,s^2)
% -----------------------------------
% Algorithm:
% Cochrane-Orcutt iterated regression (Feasible generalized least squares)
% -----------------------------------
% Usage:
% Y = dependent variable (n * 1 vector)
% X = regressors (n * k matrix)
% AR_lag = number of lags in AR process
% -----------------------------------
% Returns:
% Beta = estimator corresponding to the k regressors
if nargin < 3; AR_lag = 1; sMRI = []; end
if nargin < 5; max_iter = 20;end
[nobs] = size(X,1);
if isempty(sMRI)
Beta = wgr_regress(Y,X);
else
Beta = (X'*X+sMRI)\X'*Y; %smoothed solution
end
resid = Y - X * Beta;
if ~AR_lag
%res_sum = sum(resid.^2);
res_sum=cov(resid);
return
end
max_tol = min(1e-6,max(abs(Beta))/1000);
for r = 1:max_iter
% fprintf('Iteration No. %d\n',r)
Beta_temp = Beta;
X_AR = zeros(nobs-2*AR_lag,AR_lag);
for m = 1:AR_lag
X_AR(:,m) = resid(AR_lag+1-m:nobs-AR_lag-m);
end
Y_AR = resid(AR_lag+1:nobs-AR_lag);
% AR_para = X_AR\Y_AR;
AR_para = wgr_regress(Y_AR,X_AR);
X_main = X(AR_lag+1:nobs,:);
Y_main = Y(AR_lag+1:nobs);
for m = 1:AR_lag
X_main = X_main-AR_para(m)*X(AR_lag+1-m:nobs-m,:);
Y_main = Y_main-AR_para(m)*Y(AR_lag+1-m:nobs-m);
end
% Beta = X_main\Y_main;
if isempty(sMRI)
Beta = wgr_regress(Y_main,X_main);
else
Beta = (X_main'*X_main+sMRI)\X_main'*Y_main; %smoothed solution
end
resid = Y(AR_lag+1:nobs) - X(AR_lag+1:nobs,:)*Beta;
if max(abs(Beta-Beta_temp)) < max_tol
% fprintf('%d ,',r)
% fprintf('Converged after %d iterations!\n',r)
break
end
end
% res_sum = sum(resid.^2);
res_sum = cov(resid);
%if r == max_iter
% fprintf('Maximum %d iteration reached.\n',max_iter)
%end
return
function b = wgr_regress(y,X)
% copy from function [b,bint,r,rint,stats] = regress(y,X,alpha)
[n,ncolX] = size(X);
% Use the rank-revealing QR to remove dependent columns of X.
[Q,R,perm] = qr(X,0);
if isempty(R)
p = 0;
elseif isvector(R)
p = double(abs(R(1))>0);
else
p = sum(abs(diag(R)) > max(n,ncolX)*eps(R(1)));
end
if p < ncolX
% warning(message('stats:regress:RankDefDesignMat'));
R = R(1:p,1:p);
Q = Q(:,1:p);
perm = perm(1:p);
end
% Compute the LS coefficients, filling in zeros in elements corresponding
% to rows of X that were thrown out.
b = zeros(ncolX,1);
b(perm) = R \ (Q'*y);
|
github | compneuro-da/rsHRF-master | rsHRF_denoise_job.m | .m | rsHRF-master/rsHRF_denoise_job.m | 5,773 | utf_8 | 636514ba272caf404eab51266b00844e | function [data,data_nuisancerm] = rsHRF_denoise_job(job,data)
Nscans = size(data,1);
flag_delete = job.para_global.delete_files; % delete temporary files (generated wm/csf/brainmask)
covariates = job.Denoising.generic;
if ~isempty(covariates)
fprintf('Reading Covariates ...\n')
[txt,mat,nii]= wgr_check_covariates(covariates);
if nargin==3 % NIFTI
if ~isempty(nii)
nii2 = cell(1,length(nii));
for i=1:length(nii)
nii2{1,i} = spm_file(nii{i,1},'prefix',['bin_',job.raw_outname]);
spm_imcalc({job.ref_nii;nii{i,1}},nii2{1,i},'(i1~=0).*(i2>0.9)',{0,0,0,16});
v0 = spm_vol(nii2{1,i});
datam = spm_read_vols(v0);
if flag_delete
delete(v0.fname)
end
id = find(datam==1); clear datam
if isempty(id)
error(['no survived voxels (>0.9) in ',nii{i,1}])
else
if nii{i,2}
numcomps = nii{i,2};
z = data(:,id);
z(isnan(z))=0;
m = size(z,2) ;
if m<numcomps
error(['# components = ',num2str(m),', < ', num2str(numcomps)])
else
pc = pca(z);
end
nii2{1,i} = z*pc(:,1:numcomps);
else
nii2{1,i} = nanmean(data(:,id),2);
end
end
end
nii = cell2mat(nii2);
clear nii2 datam
else
nii = [];
end
nuisance = [txt mat nii];
elseif nargin==2
nuisance = [txt mat];
end
else
nuisance = [];
end
%% Denoising parameters
p_detrend = job.Denoising.Detrend;
if p_detrend
nuisance_detrend = zeros(Nscans,p_detrend);
for i = 1:p_detrend
d = (1:Nscans).^i;
nuisance_detrend(:,i+1) = d(:)./(Nscans.^i);
end
else
nuisance_detrend= [];
end
if ~isempty(nuisance) && ~isempty(nuisance_detrend)
fprintf('Removing nuisance regressors & Detrend................. \n ')
elseif isempty(nuisance) && ~isempty(nuisance_detrend)
fprintf('Detrend................. \n ')
elseif ~isempty(nuisance) && isempty(nuisance_detrend)
fprintf('Removing nuisance regressors................. \n ')
end
nuisance = [nuisance_detrend nuisance];
if ~isempty(nuisance)
nuisance = bsxfun(@minus, nuisance, sum(nuisance, 1)./Nscans);% Remove the mean
nuisance = [orth(nuisance) ones(Nscans, 1)];
mu = sum(data, 1)./Nscans; % mean
data = data - nuisance*(nuisance\data);
data = bsxfun(@plus, data, mu);
end
data_nuisancerm = data;
BPF = job.Denoising.BPF;
[Bands,TR] = wgr_check_bpf(BPF);
if ~isempty(Bands)
fprintf('Frequency filter.................... \n ')
if isnan(TR)
if isfield(job,'HRFE')
TR = job.HRFE.TR ;
else
error('Please add TR information for Filtering')
end
else
if isfield(job,'HRFE')
if TR ~= job.HRFE.TR ;
error('Different TR for HRF estimation and Filtering')
end
end
end
data = rsHRF_band_filter(data,TR,Bands);
end
if job.Denoising.Despiking
fprintf(' Temporal despiking with a hyperbolic tangent squashing function... \n')
data = wgr_despiking(data);
end
function x1 = wgr_despiking(x1)
my=repmat(median(x1,1),[size(x1,1),1]);
sy=repmat(4*median(abs(x1-my)),[size(x1,1),1]);
x1=my+sy.*tanh((x1-my)./max(eps,sy));
function [Bands,TR] = wgr_check_bpf(BPF)
if length(BPF)==1
try
Bands = BPF{1}.bands;
TR = nan;
catch
error('please check your setting for band-pass filtering \n')
end
elseif length(BPF)==2
try
Bands = BPF{1}.bands;
TR = BPF{2}.TR;
catch
try
Bands = BPF{2}.bands;
TR = BPF{1}.TR;
catch
error('please check your setting for band-pass filtering \n')
end
end
else
Bands =[]; TR=nan;
end
function [txt,mat,nii]= wgr_check_covariates(covariates)
txt={}; mat = {}; nii = {};
k1 =1 ; k2 = 1; k3 = 1;
for i=1:length(covariates)
tmp = covariates{i};
flag = isfield(tmp,'multi_reg');
if flag
for j=1: length(tmp.multi_reg)
tmp2 = strcat(tmp.multi_reg{j});
[~,~,ext] = fileparts(tmp2);
if ~isempty(strfind(ext,'txt'))
txt{1,k1} = load(tmp2);
k1 = k1+1;
elseif ~isempty(strfind(ext,'mat'))
tmp3 = load(tmp2);
try
mat{1,k2} = tmp3.R;
catch
tmp4 = fieldnames(tmp3);
if length(tmp4)==1
eval(['mat{1,k2} = tmp3.',tmp4{1},';']);
else
error('there are more than one variable in your mat file');
end
end
k2 = k2+1;
else
error('Unknown File Types')
end
continue;
end
end
flag = isfield(tmp,'imcov');
if flag
for j=1: length(tmp.imcov.images)
tmp2 = strcat(tmp.imcov.images{j});
nii{k3,1} = tmp2;
if length(tmp.imcov.mpc)==length(tmp.imcov.images)
nii{k3,2} = tmp.imcov.mpc(j);
elseif length(tmp.imcov.mpc)==1
nii{k3,2} = tmp.imcov.mpc(1);
end
k3 = k3+1;
end
continue;
end
end
txt = cell2mat(txt);
mat = cell2mat(mat); |
github | compneuro-da/rsHRF-master | test_rsHRF_VolumeROI_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_VolumeROI_cfg_job.m | 3,599 | utf_8 | eecfea0bae7198621a2519e43ff4ce03 | function tests = test_rsHRF_VolumeROI_cfg_job
% Unit Tests for (Volume) ROI rsHRF estimation/deconvolution and FC analysis
tests = functiontests(localfunctions);
function test_VolumeROI(testCase)
out_dir = tempdir;
conprefix = 'Conntest_';
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,filename,'_hrf.mat'])
fullfile(out_dir,[conprefix,filename,'_deconv_Corr_PartialSpearman.mat'])
};
fpath = fileparts(which('rsHRF.m'));
fnii = fullfile(fpath,'unittests','rsHRF_demo.nii,1');
atlas_nii = fullfile(fpath,'unittests','rsHRF_demo_atlas.nii,1');
mask_nii= fullfile(fpath,'unittests','rsHRF_demo_mask.nii');
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.images = {fnii};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.Denoising.which1st = 3;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.genericROI{1}.atlas = {atlas_nii};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.num_basis = NaN;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.localK = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.connectivity{1}.conn.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.connectivity{1}.conn.method = 7;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.connectivity{1}.conn.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
job = load(expected_output{1}); job = job.job;
testCase.assertTrue(isfield(job,'prefix'));
job = load(expected_output{2});
testCase.assertEqual(size(job.PARA), [3 10]);
job = load(expected_output{3});
testCase.assertTrue(isfield(job,'M'));
testCase.assertEqual(size(job.M.Matrix_z), [10 10]);
try
delete(fullfile(out_dir,[deconvprefix '*']))
delete(fullfile(out_dir,[conprefix,'*']))
end
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.connectivity = cell(1, 0);
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.mask = {mask_nii};
for i=[1 3:7]
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.HRFE.hrfm = i;
deconvprefix2 = ['Deconvtest_',num2str(i),'_'];
matlabbatch{1}.spm.tools.rsHRF.ROI_rsHRF.prefix = deconvprefix2;
spm_jobman('run', matlabbatch);
expected_output2 = fullfile(out_dir,[deconvprefix2,filename,'_hrf.mat']);
job = load(expected_output2);
testCase.assertEqual(size(job.PARA), [3 10]);
end
try
delete(fullfile(out_dir,[deconvprefix,'*']))
end |
github | compneuro-da/rsHRF-master | test_rsHRF_estimation_impulseest.m | .m | rsHRF-master/unittests/test_rsHRF_estimation_impulseest.m | 907 | utf_8 | abe8a389bdc31bef81d29d08ff88c27c | function tests = test_rsHRF_estimation_impulseest
% Unit Tests for rsHRF_estimation_impulseest
tests = functiontests(localfunctions);
function test_rsHRF_impulseest(testCase)
import matlab.unittest.constraints.*
fpath = fileparts(which('rsHRF.m'));
cd(fullfile(fpath,'demo_codes'))
load('HCP_100307_rfMRI_REST1_LR_Atlas_hp2000_clean_dtseries.mat')
TR = .72;
bands=[0.01 0.1];
bold_sig = double(zscore(bold_sig));
data = rsHRF_band_filter(bold_sig,TR,bands);
para.TR = TR;
para.len = 24;
para.temporal_mask=[];
para.T = 1;
para.T0 = 1;
para.thr = 1;
min_onset_search = 4;
max_onset_search = 8;
para.dt = para.TR/para.T;
para.lag = fix(min_onset_search/para.dt):fix(max_onset_search/para.dt);
[beta_hrf, event_bold] = rsHRF_estimation_impulseest(data,para);
testCase.verifyThat(beta_hrf, HasSize([fix(para.len/TR)+ 1,1]));
testCase.verifyThat(event_bold, IsOfClass('cell')); |
github | compneuro-da/rsHRF-master | test_rsHRF_estimation_deconvolution.m | .m | rsHRF-master/unittests/test_rsHRF_estimation_deconvolution.m | 2,473 | utf_8 | b547768210512d21a0a5be08f2a9de4b | function tests = test_rsHRF_estimation_deconvolution
% Unit Tests for band filter, HRF (parameter) estimation and (iterative Wiener) deconvolution
tests = functiontests(localfunctions);
function test_rsHRF_core(testCase)
import matlab.unittest.constraints.*
fpath = fileparts(which('rsHRF.m'));
cd(fullfile(fpath,'demo_codes'))
load('HCP_100307_rfMRI_REST1_LR_Atlas_hp2000_clean_dtseries.mat')
TR = .72;
bands=[0.01 0.1];
bold_sig = zscore(bold_sig);
data = rsHRF_band_filter(bold_sig,TR,bands);
% Unit Tests for band filter
testCase.verifyThat(data, HasSize(size(bold_sig)));
testCase.verifyThat(data, HasLength(length(bold_sig)));
para.TR = TR;
BF = {'Canonical HRF (with time derivative)'
'Canonical HRF (with time and dispersion derivatives)'
'Gamma functions'
'Fourier set'
'Fourier set (Hanning)'
'FIR'
'sFIR'};
para.order = 3;
para.len = 24;
beta_size=[2 3 para.order repmat(para.order*2+1,1,2) repmat(fix(para.len/TR),1,2) ] + 2;
temporal_mask = [];
para.T = 2;
para.T0 = 1;
if para.T==1
para.T0 = 1;
end
para.AR_lag = 1;
para.thr = 1;
min_onset_search = 4;
max_onset_search = 8;
for bf_id = 1:length(BF)
para.name = BF{bf_id};
if bf_id>5
para.T = 1;
para.T0 = 1;
end
para.dt = para.TR/para.T;
para.lag = fix(min_onset_search/para.dt):fix(max_onset_search/para.dt);
if bf_id<=5
[beta_hrf, bf, event_bold] = rsHRF_estimation_temporal_basis(data,para,temporal_mask);
hrfa = bf*beta_hrf(1:size(bf,2),:); %HRF
else
para.estimation = BF{bf_id}; % sFIR
[beta_hrf, event_bold] = rsHRF_estimation_FIR(data,para,temporal_mask);
hrfa = beta_hrf(1:end-2,:);
end
% Unit Tests for rsHRF_estimation_temporal_basis & rsHRF_estimation_FIR
testCase.verifyThat(beta_hrf, HasSize([beta_size(bf_id),1]));
testCase.verifyThat(event_bold, IsOfClass('cell'));
PARA = rsHRF_get_HRF_parameters(hrfa,para.dt);
% Unit Tests for rsHRF_get_HRF_parameters
testCase.verifyThat(PARA, HasSize([3,1]));
T = round(para.len/TR);
if para.T>1
hrfa_TR = resample(hrfa,1,para.T);
else
hrfa_TR = hrfa;
end
hrf=hrfa_TR;
data_deconv = rsHRF_iterative_wiener_deconv(data,hrf,10,1);
% Unit Tests for rsHRF_iterative_wiener_deconv
testCase.verifyThat(data_deconv, HasSize(size(data)));
end |
github | compneuro-da/rsHRF-master | test_rsHRF_Signals_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_Signals_cfg_job.m | 3,627 | utf_8 | 4b435d5e34417d5d19a2e39f11845c98 | function tests = test_rsHRF_Signals_cfg_job
% Unit Tests for (Signal)ROI rsHRF estimation/deconvolution and FC analysis
tests = functiontests(localfunctions);
function test_Signals(testCase)
out_dir = tempdir;
conprefix = 'Conntest_';
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,'combROI_',filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,'combROI_',filename,'_hrf.mat'])
fullfile(out_dir,[conprefix,'combROI_',filename,'_deconv_Corr_Spearman.mat'])
};
fpath = fileparts(which('rsHRF.m'));
gii = fullfile(fpath,'unittests','rsHRF_demo.gii');
a = gifti(gii);
dd = double(a.cdata');
sig1 = fullfile(out_dir,[filename,'.txt']);
sig2 = fullfile(out_dir,[filename,'.mat']);
save(sig1,'dd','-ascii');
save(sig2,'dd');
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Datasig(1).sigdata = {sig2};
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Datasig(1).name = 'dd';
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Datasig(2).sigdata = {sig1};
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Datasig(2).name = '';
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.num_basis = NaN;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.connectivity{1}.conn.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.connectivity{1}.conn.method = 6;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.connectivity{1}.conn.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
job = load(expected_output{1}); job = job.job;
testCase.assertTrue(isfield(job,'prefix'));
job = load(expected_output{2});
testCase.assertEqual(size(job.PARA), [3 10]);
job = load(expected_output{3});
testCase.assertTrue(isfield(job,'M'));
testCase.assertEqual(size(job.M.Matrix_z), [10 10]);
try
delete(fullfile(out_dir,[deconvprefix '*']))
delete(fullfile(out_dir,[conprefix,'*']))
end
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.connectivity = cell(1, 0);
for i=[1 3:7]
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.HRFE.hrfm = i;
deconvprefix2 = ['Deconvtest_',num2str(i),'_'];
matlabbatch{1}.spm.tools.rsHRF.sig_rsHRF.prefix = deconvprefix2;
spm_jobman('run', matlabbatch);
expected_output2 = fullfile(out_dir,[deconvprefix2,'combROI_',filename,'_hrf.mat']);
job = load(expected_output2);
testCase.assertEqual(size(job.PARA), [3 10]);
end
try
delete(fullfile(out_dir,[deconvprefix,'*']))
end |
github | compneuro-da/rsHRF-master | test_rsHRF_Voxelwise_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_Voxelwise_cfg_job.m | 4,580 | utf_8 | f87d49d4621efdea5bb8f9a023c5e8f9 | function tests = test_rsHRF_Voxelwise_cfg_job
% Unit Tests for voxelwise rsHRF estimation/deconvolution and FC/GC analysis
tests = functiontests(localfunctions);
function test_voxelwise(testCase)
out_dir = tempdir;
conprefix = 'Conntest_';
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,filename,'_hrf.mat'])
fullfile(out_dir,[conprefix,filename,'_deconv_pwGC.mat'])
fullfile(out_dir,[conprefix,'10_',filename,'_deconv_Olrm_Z_Pearson.nii'])
};
fpath = fileparts(which('rsHRF.m'));
fnii = fullfile(fpath,'unittests','rsHRF_demo.nii,1');
atlas_nii = fullfile(fpath,'unittests','rsHRF_demo_atlas.nii,1');
mask_nii= fullfile(fpath,'unittests','rsHRF_demo_mask.nii,1');
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.images = {fnii};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.which1st = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.num_basis = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.rmoutlier = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{1}.conn.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{1}.conn.Seed_ROI = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{1}.conn.genericROI{1}.atlas = {atlas_nii};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{1}.conn.method = 4;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{1}.conn.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.Seed_ROI = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.genericROI{1}.atlas = {atlas_nii};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.method = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.morder = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.ndinfo = [NaN NaN];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity{2}.connG.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfnii_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
job = load(expected_output{1}); job = job.job;
testCase.assertTrue(isfield(job,'prefix'));
job = load(expected_output{2});
testCase.assertEqual(size(job.PARA_rm), [3 27]);
job = load(expected_output{3});
testCase.assertTrue(isfield(job,'M'));
testCase.assertEqual(size(job.M.GC_Matrix), [10 10]);
testCase.assertTrue(exist(expected_output{4},'file') > 0);
try
delete(fullfile(out_dir,[deconvprefix '*']))
delete(fullfile(out_dir,[conprefix,'*']))
end
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.rmoutlier = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity = cell(1, 0);
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.mask = {mask_nii};
for i=[1 3:7]
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfm = i;
deconvprefix2 = ['Deconvtest_',num2str(i),'_'];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.prefix = deconvprefix2;
spm_jobman('run', matlabbatch);
expected_output2 = fullfile(out_dir,[deconvprefix2,filename,'_hrf.mat']);
job = load(expected_output2);
testCase.assertEqual(size(job.PARA), [3 1]);
end
try
delete(fullfile(out_dir,[deconvprefix,'*']))
end
|
github | compneuro-da/rsHRF-master | test_rsHRF_SurfROI_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_SurfROI_cfg_job.m | 4,263 | utf_8 | 2013a3fc83ac25d8c8a1acc35293762c | function tests = test_rsHRF_SurfROI_cfg_job
% Unit Tests for (surface) ROI rsHRF estimation/deconvolution and FC/GC analysis
tests = functiontests(localfunctions);
function test_SurfROI(testCase)
out_dir = tempdir;
conprefix = 'Conntest_';
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,filename,'_hrf.mat'])
fullfile(out_dir,[conprefix,filename,'_deconv_PCGC.mat'])
fullfile(out_dir,[conprefix,filename,'_deconv_Corr_PartialPearson.mat'])
};
fpath = fileparts(which('rsHRF.m'));
fgii = fullfile(fpath,'unittests','rsHRF_demo.gii');
atlas_gii = fullfile(fpath,'unittests','rsHRF_demo_atlas.gii');
mask_gii= fullfile(fpath,'unittests','rsHRF_demo_mask.gii');
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.images = {fgii};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.which1st = 3;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.genericROI{1}.meshatlas = {atlas_gii};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.num_basis = NaN;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{1}.conn.data4conn = 3;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{1}.conn.method = 5;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{1}.conn.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{2}.connG.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{2}.connG.method = 3;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{2}.connG.morder = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{2}.connG.ndinfo = [2 3];
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity{2}.connG.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
job = load(expected_output{1}); job = job.job;
testCase.assertTrue(isfield(job,'prefix'));
job = load(expected_output{2});
testCase.assertEqual(size(job.PARA), [3 5]);
job = load(expected_output{3});
testCase.assertTrue(isfield(job,'M'));
testCase.assertEqual(size(job.M.GC_Matrix), [5 5]);
testCase.assertTrue(exist(expected_output{4},'file') > 0);
try
delete(fullfile(out_dir,[deconvprefix '*']))
delete(fullfile(out_dir,[conprefix,'*']))
end
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity = cell(1, 0);
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.mask = {mask_gii};
for i=[1 3:7]
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrfm = i;
deconvprefix2 = ['Deconvtest_',num2str(i),'_'];
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.prefix = deconvprefix2;
spm_jobman('run', matlabbatch);
expected_output2 = fullfile(out_dir,[deconvprefix2,filename,'_hrf.mat']);
job = load(expected_output2);
testCase.assertEqual(size(job.PARA), [3 5]);
end
try
delete(fullfile(out_dir,[deconvprefix,'*']))
end
|
github | compneuro-da/rsHRF-master | test_rsHRF_find_event_vector.m | .m | rsHRF-master/unittests/test_rsHRF_find_event_vector.m | 451 | utf_8 | 4edc3607ff94c7875c9bd03d8d332592 | function tests = test_rsHRF_find_event_vector
% Unit Tests for rsHRF_find_event_vector
tests = functiontests(localfunctions);
function test_rsHRF_find_event_vector_1(testCase)
import matlab.unittest.constraints.*
matrix = randn(200,1);
ts = [20,60,100 150];
matrix(ts)=10; % plot(matrix)
event = rsHRF_find_event_vector(matrix,1,1,[]);
testCase.verifyThat(event, IsOfClass('double'));
testCase.assertTrue(all(ismember(ts,find(event))));
|
github | compneuro-da/rsHRF-master | test_rsHRF_Viewer_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_Viewer_cfg_job.m | 2,559 | utf_8 | 63817f367f41761dadd3b7993ce9ac50 | function tests = test_rsHRF_Viewer_cfg_job
% Unit Tests for voxelwise rsHRF display
tests = functiontests(localfunctions);
function test_Viewer(testCase)
out_dir = tempdir;
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,filename,'_hrf.mat'])
};
fpath = fileparts(which('rsHRF.m'));
fnii = fullfile(fpath,'unittests','rsHRF_demo.nii,1');
atlas_nii = fullfile(fpath,'unittests','rsHRF_demo_atlas.nii,1');
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.images = {fnii};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.which1st = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.num_basis = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.rmoutlier = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.deconv_save = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfnii_save = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
matlabbatch={};
matlabbatch{1}.spm.tools.rsHRF.display_HRF.underlay_nii = {atlas_nii};
matlabbatch{1}.spm.tools.rsHRF.display_HRF.stat_nii = {atlas_nii};
matlabbatch{1}.spm.tools.rsHRF.display_HRF.HRF_mat = {expected_output([2 2 2])};
spm('defaults', 'FMRI');
spm_jobman('run', matlabbatch);
try
delete(fullfile(out_dir,[deconvprefix '*']))
end
close all |
github | compneuro-da/rsHRF-master | test_rsHRF_Vertexwise_cfg_job.m | .m | rsHRF-master/unittests/test_rsHRF_Vertexwise_cfg_job.m | 4,546 | utf_8 | e9b9a5b0e1b3b62113143415f517edd9 | function tests = test_rsHRF_Vertexwise_cfg_job
% Unit Tests for vertexwise rsHRF estimation/deconvolution and FC/GC analysis
tests = functiontests(localfunctions);
function test_vertexwise(testCase)
out_dir = tempdir;
conprefix = 'Conntest_';
deconvprefix = 'Deconvtest_';
filename = 'rsHRF_demo';
expected_output = {fullfile(out_dir,[deconvprefix,filename,'_job.mat'])
fullfile(out_dir,[deconvprefix,filename,'_hrf.mat'])
fullfile(out_dir,[conprefix,filename,'_deconv_CGC.mat'])
fullfile(out_dir,[conprefix,'5_',filename,'_deconv_Z_Pearson.gii'])
};
fpath = fileparts(which('rsHRF.m'));
fgii = fullfile(fpath,'unittests','rsHRF_demo.gii');
atlas_gii = fullfile(fpath,'unittests','rsHRF_demo_atlas.gii');
mask_gii= fullfile(fpath,'unittests','rsHRF_demo_mask.gii');
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.images = {fgii};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.Denoising.generic = {};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.Denoising.Detrend = 0;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.Denoising.BPF = {};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.Denoising.Despiking = 0;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.Denoising.which1st = 3;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.hrfm = 2;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.TR = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.num_basis = 3;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.cvi = 0;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.fmri_t = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.fmri_t0 = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.tmask = NaN;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.hrfdeconv = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{1}.conn.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{1}.conn.Seed_ROI = 0;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{1}.conn.genericROI{1}.meshatlas = {atlas_gii};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{1}.conn.method = 4;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{1}.conn.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.data4conn = 2;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.Seed_ROI = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.genericROI{1}.meshatlas = {atlas_gii};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.method = 2;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.morder = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.ndinfo = [NaN NaN];
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity{2}.connG.prefix = conprefix;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.outdir = {out_dir};
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.savedata.hrfnii_save = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.prefix = deconvprefix;
spm('defaults', 'FMRI');
% spm_jobman('interactive', matlabbatch);
spm_jobman('run', matlabbatch);
job = load(expected_output{1}); job = job.job;
testCase.assertTrue(isfield(job,'prefix'));
job = load(expected_output{2});
testCase.assertEqual(size(job.PARA), [3 5]);
job = load(expected_output{3});
testCase.assertTrue(isfield(job,'M'));
testCase.assertEqual(size(job.M.GC_Matrix), [5 5]);
testCase.assertTrue(exist(expected_output{4},'file') > 0);
try
delete(fullfile(out_dir,[deconvprefix '*']))
delete(fullfile(out_dir,[conprefix,'*']))
end
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.connectivity = cell(1, 0);
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.mask = {mask_gii};
for i=[1 3:7]
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.HRFE.hrfm = i;
deconvprefix2 = ['Deconvtest_',num2str(i),'_'];
matlabbatch{1}.spm.tools.rsHRF.mesh_rsHRF.prefix = deconvprefix2;
spm_jobman('run', matlabbatch);
expected_output2 = fullfile(out_dir,[deconvprefix2,filename,'_hrf.mat']);
job = load(expected_output2);
testCase.assertEqual(size(job.PARA), [3 1]);
end
try
delete(fullfile(out_dir,[deconvprefix,'*']))
end
|
github | compneuro-da/rsHRF-master | rsHRF_estimation_impulseest_IO.m | .m | rsHRF-master/demo_codes/rsHRF_estimation_impulseest_IO.m | 11,440 | utf_8 | 99bc4a399cc92d67ce2bbff4a3eb25e2 | function [hrf] = rsHRF_estimation_impulseest_IO(input, output, para)
%% detrend
if ~isempty(para.flag_detrend)
input = spm_detrend(input,para.flag_detrend);
output = spm_detrend(output,para.flag_detrend);
end
%% filtering
if ~isempty(para.Band)
output = bandpass_filt(output, 1/para.TR, para.Band, 10, 'fir', 'twopass', 1);
% output = rsHRF_band_filter(output,para.TR,para.Band);
end
if 0
figure
plot(zscore([input output]))
end
%% neural binay stimulus onset
u0 = rsHRF_find_event_vector(input,para.thr,para.localK,para.temporal_mask);
u0 = full(u0(:));
srs0 = iddata(output, u0, para.TR);
srs0.InputName = 'LFP-bin';
srs0.OutputName = 'OIS';
NN=fix(para.len*1/para.TR);
srsiiu_lfp_bin = impulseest(srs0,NN,para.options);
%% LFP HRF
srs = iddata(output, input, para.TR);
srs.InputName = 'LFP';
srs.OutputName = 'OIS';
srsii_lfp = impulseest(srs,NN,para.options);
H_LFP_bin = srsiiu_lfp_bin.Report.Parameters.ParVector;
H_LFP = srsii_lfp.Report.Parameters.ParVector;
[H_Blind] = rsHRF_estimation_impulseest(output,para);
hrf.H_LFP_bin=H_LFP_bin;
hrf.H_LFP=H_LFP;
hrf.H_Blind=H_Blind;
function filt = bandpass_filt(data, Fs, Fbp, N, type, dir, meanback)
%
% BANDPASS_FILT applies a band-pass filter to the data in a specified
% frequency band.
%
%
%USAGE
%-----
% filt = bandpass_filt(data, Fsample, Fbp, N, type, dir, meanback)
%
%
%INPUT
%-----
% - DATA : data matrix (Nsamples x Nchannels)
% - FSAMPLE : sampling frequency in Hz
% - FBP : frequency band, specified as [Fhp Flp]
% Fhp = 0 => low-pass filter
% Flp = inf => high-pass filter
% - N : filter order (positive integer). If N=[], the default value
% will be used: 4 ('but') or dependent upon frequency band and
% data length ('fir', 'firls')
% - TYPE : filter type. If TYPE='', the default value will be used.
% 'but' Butterworth IIR filter (default)
% 'fir' FIR filter using Matlab fir1 function
% 'firls' FIR filter using Matlab firls function (requires
% Matlab Signal Processing Toolbox)
% - DIR : filter direction. If DIR='', the default value will be used.
% 'onepass' forward filter only
% 'onepass-reverse' reverse filter only, i.e. backward in time
% 'twopass' zero-phase forward and reverse filter (default)
% 'twopass-reverse' zero-phase reverse and forward filter
% 'twopass-average' average of the twopass and the twopass-reverse
% - MEANBACK: 1 (add the mean back after filtering [default]) or 0 (do not add)
%
% Note that a one- or two-pass filter has consequences for the strength of
% the filter, i.e. a two-pass filter with the same filter order will
% attenuate the signal twice as strong.
%
%
%EXAMPLE
%-------
% T = .5; % [s] => sampling freq. = 1/T => Nyquist freq. = 1/(2T)
% t = (0:T:2*pi*10)';
% f1 = (1/2/T)*.030;
% f2 = (1/2/T)*.050;
% f3 = (1/2/T)*.075;
% x1 = 10*sin(2*pi*f1*t);
% x2 = 4*sin(2*pi*f2*t);
% x3 = 15*cos(2*pi*f3*t);
% x = x1 + x2 + x3;
%
% type = {'but' 'fir' 'firls'};
% dir = {'onepass' 'onepass-reverse' 'twopass' 'twopass-reverse' 'twopass-average'};
% addmean = 0; N=10; tt=1; dd=3;
%
% xLP = bandpass_filt(x, 1/T, [0 (f2+f3)/2], N, type{tt}, dir{dd}, addmean);
% figure, plot(t,x,t,xLP,t,x1+x2)
% title(sprintf('Low-pass filter (%s - %s)', type{tt}, dir{dd}))
% legend('Original', 'Filtered', 'f1 & f2')
% xHP = bandpass_filt(x, 1/T, [(f1+f2)/2 inf], N, type{tt}, dir{dd}, addmean);
% figure, plot(t,x,t,xHP,t,x2+x3)
% title(sprintf('High-pass filter (%s - %s)', type{tt}, dir{dd}))
% legend('Original', 'Filtered', 'f2 & f3')
% xBP = bandpass_filt(x, 1/T, [(f1+f2)/2 (f2+f3)/2], 6, type{tt}, dir{dd}, addmean);
% figure, plot(t,x,t,xBP,t,x2)
% title(sprintf('Band-pass filter (%s - %s)', type{tt}, dir{dd}))
% legend('Original', 'Filtered', 'f2')
% Copyright (c) 2003-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_preproc_lowpassfilter.m 7123 2012-12-06 21:21:38Z roboos $
% $Id: ft_preproc_bandpassfilter.m 7123 2012-12-06 21:21:38Z roboos $
% $Id: ft_preproc_highpassfilter.m 7123 2012-12-06 21:21:38Z roboos $
% $Id: filter_with_correction.m 7123 2012-12-06 21:21:38Z roboos $
% Default values
%==========================================================================
if nargin<4 || isempty(N)
N = []; % set the default filter order later
end
if nargin<5 || isempty(type)
type = 'but'; % set the default filter type
end
if nargin<6 || isempty(dir)
dir = 'twopass'; % set the default filter direction
end
if nargin<7 || isempty(meanback)
meanback = 1; % set the default option for the mean
end
% Initialize
%==========================================================================
Fbp = sort(Fbp);
if Fbp(1)==0 && isinf(Fbp(2)) % full spectrum => nothing should be done
filt = data;
return
end
if Fbp(1)==0 % low-pass filter
Fbp = Fbp(2);
ftype = -1; % filter type
elseif isinf(Fbp(2)) % high-pass filter
Fbp = Fbp(1);
ftype = 1; % filter type
else % band-pass filter
ftype = 0; % filter type
end
Fn = Fs/2; % Nyquist frequency
Nsamples = size(data, 1);
data = data.'; % Nchannels x Nsamples
% Compute filter coefficients
%==========================================================================
switch type
case 'but'
if isempty(N)
if ftype==-1 || ftype==1 % low- and high-pass filters
N = 6;
elseif ftype==0 % band-pass filter
N = 4;
end
end
if ftype==-1 % low-pass filter
[B, A] = butter(N, Fbp/Fn);
elseif ftype==1 % high-pass filter
[B, A] = butter(N, Fbp/Fn, 'high');
elseif ftype==0 % band-pass filter
[B, A] = butter(N, [Fbp(1)/Fn Fbp(2)/Fn]);
end
case 'fir'
if isempty(N)
if ftype==-1 || ftype==1 % low- and high-pass filters
N = 3*fix(Fs / Fbp);
if ftype==1 && rem(N, 2)==1
N = N + 1;
end
elseif ftype==0 % band-pass filter
N = 3*fix(Fs / Fbp(1)); % old: 25
end
end
if N > floor( (Nsamples - 1) / 3)
if ftype==1
N = floor(Nsamples/3) - 2;
if rem(N, 2)==1
N = N + 1; % "fir1" always uses an even filter order for the highpass configuration
end
else
N = floor(Nsamples/3) - 1;
end
end
if ftype==-1 % low-pass filter
[B, A] = fir1(N, Fbp/Fn);
elseif ftype==1 % high-pass filter
[B, A] = fir1(N, Fbp/Fn, 'high');
elseif ftype==0 % band-pass filter
[B, A] = fir1(N, [Fbp(1)/Fn Fbp(2)/Fn]);
end
case 'firls' % from NUTMEG's implementation
if isempty(N)
if ftype==-1 || ftype==1 % low- and high-pass filters
N = 3*fix(Fs / Fbp);
if ftype==1 && rem(N, 2)==1
N = N + 1;
end
elseif ftype==0 % band-pass filter
N = 3*fix(Fs / Fbp(1));
end
end
if N > floor( (Nsamples - 1) / 3)
if ftype==1
N = floor(Nsamples/3) - 2;
if rem(N, 2)==1
N = N + 1;
end
else
N = floor(Nsamples/3) - 1;
end
end
f = 0:0.001:1;
if rem(length(f), 2)~=0
f(end) = [];
end
z = zeros(1, length(f));
if ftype==-1 % low-pass filter
[val, pos1] = min(abs(Fs*f/2 - 0));
if isfinite(Fbp)
[val, pos2] = min(abs(Fs*f/2 - Fbp));
else
pos2 = length(f);
end
elseif ftype==1 % high-pass filter
[val,pos1] = min(abs(Fs*f/2 - Fbp));
pos2 = length(f);
elseif ftype==0 % band-pass filter
if isfinite(Fbp(1))
[val, pos1] = min(abs(Fs*f/2 - Fbp(1)));
else
[val, pos2] = min(abs(Fs*f/2 - Fbp(2)));
pos1 = pos2;
end
if isfinite(Fbp(2))
[val, pos2] = min(abs(Fs*f/2 - Fbp(2)));
else
pos2 = length(f);
end
end
z(pos1:pos2) = 1;
A = 1;
B = firls(N, f, z); % requires Matlab signal processing toolbox
otherwise
error('Unsupported filter type "%s"', type);
end
% Apply A to the data and correct edge-artifacts for one-pass filtering
%==========================================================================
poles = roots(A);
if any(abs(poles) >= 1)
%poles
fprintf(['Calculated filter coefficients have poles on or outside\n' ...
'the unit circle and will not be stable. Try a higher cutoff\n' ...
'frequency or a different type/order of filter.\n'])
filt = [];
return
end
dcGain = sum(B)/sum(A);
mu = sum(data, 2)/Nsamples; % data mean
data = bsxfun(@minus, data, mu); % zero-mean
switch dir
case 'onepass'
offset = data(:,1);
data = data - repmat(offset, 1, Nsamples);
filt = filter(B, A, data.').' + repmat(dcGain*offset, 1, Nsamples);
% old: filt = filter(B, A, data.');
case 'onepass-reverse'
offset = data(:, end);
data = fliplr(data) - repmat(offset, 1, Nsamples);
filt = filter(B, A, data.').';
filt = fliplr(filt) + repmat(dcGain*offset, 1, Nsamples);
% old: data=fliplr(data); filt=filter(B, A, data.'); filt fliplr(filt);
case 'twopass'
% filtfilt does the correction for us
filt = filtfilt(B, A, data.').';
case 'twopass-reverse'
% filtfilt does the correction for us
filt = fliplr(filtfilt(B, A, fliplr(data).').');
case 'twopass-average'
% take the average from the twopass and the twopass-reverse
filt1 = filtfilt(B, A, data.').';
filt2 = fliplr(filtfilt(B, A, fliplr(data).').');
filt = (filt1 + filt2)/2;
otherwise
error('Unsupported filter direction "%s"', dir);
end
if meanback
filt = bsxfun(@plus, filt, mu); % add mean back to the filtered data
end
filt = filt.'; % restore data shape |
github | compneuro-da/rsHRF-master | rsHRF_demo_UCLA_sub_gamma3_wm.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/rsHRF_demo_UCLA_sub_gamma3_wm.m | 2,409 | utf_8 | 1647fe41b830244fd71da5d19fd54003 | function rsHRF_demo_UCLA_sub_gamma3_wm(fl,fnii,niimask,mainoutdir,csf_mat)
[fpath,name,~] = fileparts(fl);
id = strfind(name,'_task');
subid = name(1:id(1)-1);
gunzip([fnii,'.gz'])
a= spm_load(fl);
b = load(csf_mat);
acomp = [b.csf_acompcor];
Q1 = [a.X, a.Y, a.Z, a.RotX, a.RotY, a.RotZ];
HM = [Q1, [zeros(1,size(Q1,2));diff(Q1)]];
FD = a.FramewiseDisplacement; FD(1)=0;
tmask = double(FD<0.3);
if mean(FD)>0.2
return
end
nui = [acomp HM];
txtfile = fullfile(fpath,[name,'_csf.txt']);
save(txtfile,'nui','-ascii')
outdir = fullfile(mainoutdir,subid);
rsHRF_gamma3HRF_batch_job([fnii,',1'],txtfile,tmask,niimask,outdir)
delete(fnii)
function rsHRF_gamma3HRF_batch_job(fnii,txtfile,tmask,nii_mask,outdir)
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.images = {fnii};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.generic{1}.multi_reg = {txtfile};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Detrend = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.BPF{1}.bands = [0.01 0.1];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.Denoising.Despiking = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrfm = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.TR = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.hrflen = 32;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.cvi = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.num_basis = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t = 5;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.fmri_t0 = 3;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.HRFE.tmask = tmask;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.rmoutlier = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.mask = {nii_mask};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.connectivity = {};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.outdir = {outdir};
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.deconv_save = 0;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.hrfnii_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.vox_rsHRF.prefix = 'T5to3AR1_';
spm('defaults', 'FMRI');
spm_jobman('interactive',matlabbatch);
spm_jobman('run',matlabbatch); |
github | compneuro-da/rsHRF-master | rsHRF_demo_UCLA_sub_Fourier_surf_ROI.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/rsHRF_demo_UCLA_sub_Fourier_surf_ROI.m | 2,687 | utf_8 | bd72bb48f9957960369ac13f17f771ba | %-----------------------------------------------------------------------
% Job saved on 01-Oct-2020 17:30:46 by cfg_util (rev $Rev: 7345 $)
% spm SPM - SPM12 (7771)
% cfg_basicio BasicIO - Unknown
%-----------------------------------------------------------------------
function rsHRF_demo_UCLA_sub_Fourier_surf_ROI(fl,gnii,mainoutdir,atlasgii)
[fpath,name,~] = fileparts(fl);
id = strfind(name,'_task');
subid = name(1:id(1)-1);
a= spm_load(fl);
acomp = [a.aCompCor00, a.aCompCor01, a.aCompCor02, a.aCompCor03, a.aCompCor04, a.aCompCor05];
Q1 = [a.X, a.Y, a.Z, a.RotX, a.RotY, a.RotZ];
HM = [Q1, [zeros(1,size(Q1,2));diff(Q1)]];
FD = a.FramewiseDisplacement; FD(1)=0;
if mean(FD)>0.2
return
end
tmask = double(FD<0.3);
nui = [acomp HM];
txtfile = fullfile(fpath,[name,'.txt']);
save(txtfile,'nui','-ascii')
outdir = fullfile(mainoutdir,subid);
matlabbatch={};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.images = {gnii};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.generic{1}.multi_reg = {txtfile};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.Detrend = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.BPF{1}.bands = [0.01 0.1];
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.Despiking = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.Denoising.which1st = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.genericROI{1}.meshatlas = {atlasgii};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrfm = 5;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.TR = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.hrflen = 20;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.num_basis = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.mdelay = [4 8];
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.cvi = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.fmri_t = 5;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.fmri_t0 = 3;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.thr = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.localK = 2;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.HRFE.tmask = tmask;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.mask = {''};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.connectivity = {};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.outdir = {outdir};
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.deconv_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.hrfmat_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.savedata.job_save = 1;
matlabbatch{1}.spm.tools.rsHRF.SurfROI_rsHRF.prefix = 'T5to3AR1_';
spm('defaults', 'FMRI');
% spm_jobman('interactive', matlabbatch);
spm_jobman('run', matlabbatch); |
github | compneuro-da/rsHRF-master | W_Calculate_RVR.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/W_Calculate_RVR.m | 2,383 | utf_8 | 1c9ded04ddc186db35091bbb267ac855 |
function [w_Brain, model_All] = W_Calculate_RVR(Subjects_Data, Subjects_Scores, Covariates, Pre_Method, ResultantFolder)
%
% Subject_Data:
% m*n matrix
% m is the number of subjects
% n is the number of features
%
% Subject_Scores:
% the continuous variable to be predicted,[1*m]
%
% Covariates:
% m*n matrix
% m is the number of subjects
% n is the number of covariates
%
% Pre_Method:
% 'Normalize', 'Scale', 'None'
%
% ResultantFolder:
% the path of folder storing resultant files
%
if nargin >= 5
if ~exist(ResultantFolder, 'dir')
mkdir(ResultantFolder);
end
end
[Subjects_Quantity, Features_Quantity] = size(Subjects_Data);
if ~isempty(Covariates)
[~, Covariates_quantity] = size(Covariates);
M = 1;
for j = 1:Covariates_quantity
M = M + term(Covariates(:, j));
end
slm = SurfStatLinMod(Subjects_Data, M);
Subjects_Data = Subjects_Data - repmat(slm.coef(1, :), Subjects_Quantity, 1);
for j = 1:Covariates_quantity
Subjects_Data = Subjects_Data - ...
repmat(Covariates(:, j), 1, Features_Quantity) .* repmat(slm.coef(j + 1, :), Subjects_Quantity, 1);
end
end
if strcmp(Pre_Method, 'Normalize')
%Normalizing
MeanValue = mean(Subjects_Data);
StandardDeviation = std(Subjects_Data);
[~, columns_quantity] = size(Subjects_Data);
for j = 1:columns_quantity
Subjects_Data(:, j) = (Subjects_Data(:, j) - MeanValue(j)) / StandardDeviation(j);
end
elseif strcmp(Pre_Method, 'Scale')
% Scaling to [0 1]
MinValue = min(Subjects_Data);
MaxValue = max(Subjects_Data);
[~, columns_quantity] = size(Subjects_Data);
for j = 1:columns_quantity
Subjects_Data(:, j) = (Subjects_Data(:, j) - MinValue(j)) / (MaxValue(j) - MinValue(j));
end
end
% SVR
Subjects_Data = double(Subjects_Data);
d.train{1} = Subjects_Data * Subjects_Data';
d.test{1} = Subjects_Data * Subjects_Data';
d.tr_targets = Subjects_Scores';
d.use_kernel = 1;
d.pred_type = 'regression';
model_All = prt_machine_rvr(d, []);
w_Brain = zeros(1, Features_Quantity);
for i = 1:length(model_All.alpha)
w_Brain = w_Brain + model_All.alpha(i) * Subjects_Data(i, :);
end
w_Brain = w_Brain / norm(w_Brain);
if nargin >= 5
save([ResultantFolder filesep 'w_Brain.mat'], 'w_Brain');
end
|
github | compneuro-da/rsHRF-master | W_Calculate_RVR_SGE.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/W_Calculate_RVR_SGE.m | 389 | utf_8 | ed548906c32e0c3951f1c7fc894f7392 |
function W_Calculate_RVR_SGE(Subjects_Data_Path, Rand_Scores, ID, Covariates, Pre_Method, ResultantFolder)
tmp = load(Subjects_Data_Path);
FieldName = fieldnames(tmp);
for i = 1:length(ID)
disp(ID(i));
[w_Brain, ~] = W_Calculate_RVR(tmp.(FieldName{1}), Rand_Scores{i}, Covariates, Pre_Method);
save([ResultantFolder filesep 'w_Brain_' num2str(ID(i)) '.mat'], 'w_Brain');
end |
github | compneuro-da/rsHRF-master | SurfStatWriteVol1.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/SurfStatWriteVol1.m | 19,785 | utf_8 | bad41c0fa1d7c525f5619d09cbf3db77 | function SurfStatWriteVol( d, Z, T );
%Writes volumetric image data in MINC, ANALYZE, NIFTI or AFNI format.
%
% Usage: fmris_write_image( d [, Z, T] ).
%
% d.file_name = file name with extension .mnc, .img, .nii or .brik as above
% Z = vector of slices.
% T = vector of times.
% If Z and T are omitted, writes the entire volume.
file = deblank(d.file_name);
[base,ext]=fileparts2(file);
d.file_name=[base ext];
switch lower(ext)
case '.mnc'
if nargin == 3
if length(T)<=160
fmris_write_minc(d,Z,T);
else
fn=deblank(d.file_name);
d.file_name=[fn(1:(length(fn)-3)) 'nii'];
fmris_write_nifti(d,Z,T);
end
else
if d.dim(4)<=160
fmris_write_minc(d);
else
fn=deblank(d.file_name);
d.file_name=[fn(1:(length(fn)-3)) 'nii'];
fmris_write_nifti(d);
end
end
case '.img'
if nargin == 3
fmris_write_analyze(d,Z,T);
else
fmris_write_analyze(d);
end
case '.brik'
if nargin == 3
fmris_write_afni(d,Z,T);
else
fmris_write_afni(d);
end
case '.nii'
if nargin == 3
fmris_write_nifti(d,Z,T);
else
fmris_write_nifti(d);
end
otherwise
['Unknown file extension']
end
return
end
%%
function [base,ext]=fileparts2(string)
if isstr(string)
[path,name,ext]=fileparts(deblank(string));
else
[path,name,ext]=fileparts(deblank(string.file_name));
end
if strcmp(ext,'.gz')
[path2,name,ext]=fileparts(name);
end
if isempty(path)
base=name;
else
base=[path '/' name];
end
return
end
%%
function [d]=fmris_write_afni(d,Z,T);
existinfo=0;
if ~isfield(d,'dim') & isfield(d,'parent_file')
[path,name,ext]=fileparts(deblank(d.parent_file));
[err, Infoparent] = BrikInfo([path '/' name '.HEAD']);
d.dim=[Infoparent.DATASET_DIMENSIONS(1:3) Infoparent.DATASET_RANK(2)];
existinfo=1;
end
if nargin==1
Z=1:d.dim(3);
T=1:d.dim(4);
end
Opt.Prefix=d.file_name(1:(length(d.file_name)-5));
Opt.Slices=Z;
Opt.Frames=T;
Opt.NoCheck=1;
if Z(1)==1 & T(1)==1
if ~existinfo
[path,name,ext]=fileparts(deblank(d.parent_file));
[err, Infoparent] = BrikInfo([path '/' name '.HEAD']);
end
[path,name,ext]=fileparts(deblank(d.file_name));
Info.LABEL_1=name;
Info.DATASET_NAME=['./' name];
if isfield(d,'origin')
Info.ORIGIN=d.origin;
else
Info.ORIGIN=Infoparent.ORIGIN;
end
if isfield(d,'vox')
Info.DELTA=d.vox;
else
Info.DELTA=Infoparent.DELTA;
end
Info.SCENE_DATA=Infoparent.SCENE_DATA;
Info.ORIENT_SPECIFIC=Infoparent.ORIENT_SPECIFIC;
Info.TYPESTRING=Infoparent.TYPESTRING;
Opt.NoCheck=0;
end
Info.DATASET_DIMENSIONS=[d.dim(1:3) 0 0];
Info.DATASET_RANK=[3 d.dim(4) 0 0 0 0 0 0];
Info.BRICK_TYPES=repmat(3,1,d.dim(4));
Info.TypeName='float';
Info.TypeBytes=4;
Info.BYTEORDER_STRING='MSB_FIRST';
Info.MachineFormat='ieee-be';
if isfield(d,'df')
if ~isempty(d.df)
Info.WORSLEY_DF=d.df;
end
end
if isfield(d,'nconj')
if ~isempty(d.nconj)
Info.WORSLEY_NCONJ=d.nconj;
end
end
if isfield(d,'fwhm')
if ~isempty(d.fwhm)
Info.WORSLEY_FWHM=d.fwhm;
end
end
[err, ErrMessage, Info] = WriteBrik(d.data, Info, Opt);
return
end
%%
function [d]=fmris_write_analyze(d,Z,T);
% Write Analyze format Image Volumes
%
% Usage
%
% rpm_write_analyze(d,Z,T);
%
% Writes image data and attributes from the structure d.
% The following fields are required from d.
%
% d.file_path: '/kop1/data/fdg/'
% d.file_name: 'n03309_3d_dy2_CS-Cal_K1'
% d.data: [128x128x31 double]
% d.vox: [2.0900 2.0900 3.4200]
% d.vox_units: 'mm'
% d.vox_offset: 0
% d.calib_units: 'min^-1'
% d.origin: [0 0 0];
% d.descrip: 'Parametric Image - K1 (1)'
%
% All other information is generated automatically.
%
% (c) Roger Gunn & John Aston
if isfield(d,'parent_file')
d2=SurfStatReadVol(d.parent_file,0,0);
d.vox=d2.vox;
d.vox_units=d2.vox_units;
d.calib_units='';
d.origin=d2.origin;
d.vox_offset=d2.vox_offset;
end
if ~isfield(d,'descrip')
d.descrip='';
end
file=d.file_name;
d.origin=-d.origin./d.vox(1:3);
if length(size(d.data))<5&size(d.data,1)>1&size(d.data,2)>1&length(d.origin)<4
d.calib = [1 1];
d.precision='float';
% Write Header
if nargin==1
[d]=Write_Analyze_Hdr(d);
elseif nargin==3
if (T(1)==1&Z(1)==1)
[d]=Write_Analyze_Hdr(d);
else
d3 = fmris_read_image(file,0,0);
d.hdr = d3.hdr;
end
end
if ~isstruct(d);
return
end
% Write Image
if nargin==1
if ~isempty(d)
fid = fopen(file,'w','n');
if fid > -1
for t=1:d.hdr.dim(5)
for z=1:d.hdr.dim(4)
fwrite(fid,d.data(:,:,z,t)/d.hdr.funused1,d.precision);
end
end
fclose (fid);
else
errordlg('Cannot open file for writing ','Write Error');d=[];return;
end
end
elseif nargin==3
if T(1)~=1|Z(1)~=1
if ~exist(file,'file')
errordlg('Please write Plane 1 Frame 1 first','Write Error');return;
end
else
fid=fopen(file,'w','n');fclose(fid);
end
fid = fopen(file,'r+','n');
if fid > -1
if T(1)==1&Z(1)==1
plane=zeros(d.dim(1:2));
for t=1:d.hdr.dim(5)
for z=1:d.hdr.dim(4)
fwrite(fid,plane,d.precision);
end
end
end
for t=1:length(T)
for z=1:length(Z)
fseek(fid,4*d.dim(1)*d.dim(2)*((T(t)-1)*d.dim(3)+Z(z)-1),'bof');
if length(Z)~=1;
fwrite(fid,d.data(:,:,z,t),'float');
else
fwrite(fid,d.data(:,:,t),'float');
end
end
end
fclose (fid);
else
errordlg('Cannot open file for writing ','Write Error');d=[];return;
end
end
else
errordlg('Incompatible data structure: Check dimension and Origin ','Write Error');
end
return;
end
%%
function [d]=Write_Analyze_Hdr(d);
% Write Analyze Header from the structure d
% Adapted from John Ashburners spm_hwrite.m
d.file_name_hdr=[d.file_name(1:(length(d.file_name)-3)) 'hdr'];
file=d.file_name_hdr;
fid = fopen(file,'w','n');
if fid > -1
d.hdr.data_type = ['dsr ' 0];
d.hdr.db_name = [' ' 0];
if isfield(d,'dim')
d.hdr.dim = [4 1 1 1 1 0 0 0];
d.hdr.dim(2:(1+length(d.dim(find(d.dim)))))= d.dim(find(d.dim));
else
d.hdr.dim = [4 1 1 1 1 0 0 0];
d.hdr.dim(2:(1+length(size(d.data)))) = size(d.data);
end
d.hdr.pixdim = [4 0 0 0 0 0 0 0];
d.hdr.pixdim(2:(1+length(d.vox))) = d.vox;
d.hdr.vox_units = [0 0 0 0];
d.hdr.vox_units(1:min([3 length(d.vox_units)])) = d.vox_units(1:min([3 length(d.vox_units)]));
d.hdr.vox_offset = d.vox_offset;
d.hdr.calmin = d.calib(1);
d.hdr.calmax = d.calib(2);
switch d.precision
case 'uint1' % 1 bit
d.hdr.datatype = 1;
d.hdr.bitpix = 1;
d.hdr.glmin = 0;
d.hdr.glmax = 1;
d.hdr.funused1 = 1;
case 'uint8' % 8 bit
% d.hdr.datatype = 2;
% d.hdr.bitpix = 8;
% d.hdr.glmin = 0;
% d.hdr.glmax = 255;
% d.hdr.funused1 = abs(d.hdr.calmin)/255;
errordlg('You should write a float image','8 Bit Write Error');d=[];return;
case 'int16' % 16 bit
d.hdr.datatype = 4;
d.hdr.bitpix = 16;
if abs(d.hdr.calmin)>abs(d.hdr.calmax)
d.hdr.funused1 = abs(d.hdr.calmin)/(2^15-1);
else
d.hdr.funused1 = abs(d.hdr.calmax)/(2^15-1);
end
d.hdr.glmin = round(d.hdr.funused1*d.hdr.calmin);
d.hdr.glmax = round(d.hdr.funused1*d.hdr.calmin);
case 'int32' % 32 bit
d.hdr.datatype = 8;
d.hdr.bitpix = 32;
if abs(d.hdr.calmin)>abs(d.hdr.calmax)
d.hdr.funused1 = abs(d.hdr.calmin)/(2^31-1);
else
d.hdr.funused1 = abs(d.hdr.calmax)/(2^31-1);
end
d.hdr.glmin = round(d.hdr.funused1*d.hdr.calmin);
d.hdr.glmax = round(d.hdr.funused1*d.hdr.calmin);
case 'float' % float (32 bit)
d.hdr.datatype = 16;
d.hdr.bitpix = 32;
d.hdr.glmin = 0;
d.hdr.glmax = 0;
d.hdr.funused1 = 1;
case 'double' % double (64 bit)
d.hdr.datatype = 64;
d.hdr.bitpix = 64;
d.hdr.glmin = 0;
d.hdr.glmax = 0;
d.hdr.funused1 = 1;
otherwise
errordlg('Unrecognised precision (d.type)','Write Error');d=[];return;
end
d.hdr.descrip = zeros(1,80);d.hdr.descrip(1:min([length(d.descrip) 79]))=d.descrip(1:min([length(d.descrip) 79]));
d.hdr.aux_file = ['none ' 0];
d.hdr.origin = [0 0 0 0 0];d.hdr.origin(1:length(d.origin))=d.origin;
% write (struct) header_key
%---------------------------------------------------------------------------
fseek(fid,0,'bof');
fwrite(fid,348, 'int32');
fwrite(fid,d.hdr.data_type, 'char' );
fwrite(fid,d.hdr.db_name, 'char' );
fwrite(fid,0, 'int32');
fwrite(fid,0, 'int16');
fwrite(fid,'r', 'char' );
fwrite(fid,'0', 'char' );
% write (struct) image_dimension
%---------------------------------------------------------------------------
fseek(fid,40,'bof');
fwrite(fid,d.hdr.dim, 'int16');
fwrite(fid,d.hdr.vox_units, 'char' );
fwrite(fid,zeros(1,8), 'char' );
fwrite(fid,0, 'int16');
fwrite(fid,d.hdr.datatype, 'int16');
fwrite(fid,d.hdr.bitpix, 'int16');
fwrite(fid,0, 'int16');
fwrite(fid,d.hdr.pixdim, 'float');
fwrite(fid,d.hdr.vox_offset, 'float');
fwrite(fid,d.hdr.funused1, 'float');
fwrite(fid,0, 'float');
fwrite(fid,0, 'float');
fwrite(fid,d.hdr.calmax, 'float');
fwrite(fid,d.hdr.calmin, 'float');
fwrite(fid,0, 'int32');
fwrite(fid,0, 'int32');
fwrite(fid,d.hdr.glmax, 'int32');
fwrite(fid,d.hdr.glmin, 'int32');
% write (struct) data_history
%---------------------------------------------------------------------------
fwrite(fid,d.hdr.descrip, 'char');
fwrite(fid,d.hdr.aux_file, 'char');
fwrite(fid,0, 'char');
fwrite(fid,d.hdr.origin, 'uint16');
fwrite(fid,zeros(1,10), 'char');
if isfield(d,'df')
fwrite(fid,sprintf('%10g',d.df(1)),'char');
if length(d.df)>1
fwrite(fid,sprintf('%10g',d.df(2)),'char');
else
fwrite(fid,zeros(1,10),'char');
end
else
fwrite(fid,zeros(1,20),'char');
end
if isfield(d,'fwhm')
fwrite(fid,sprintf('%10g',d.fwhm(1)),'char');
if length(d.fwhm)>1
fwrite(fid,sprintf('%10g',d.fwhm(2)),'char');
else
fwrite(fid,zeros(1,10),'char');
end
else
fwrite(fid,zeros(1,20),'char');
end
if isfield(d,'nconj')
fwrite(fid,sprintf('%3g',d.nconj),'char');
else
fwrite(fid,zeros(1,3),'char');
end
fwrite(fid,zeros(1,32),'char');
s = ftell(fid);
fclose(fid);
else
errordlg('Cannot open file for writing ','Write Error');d=[];return;
end
return;
end
%%
function [d]=fmris_write_minc(d,Z,T);
if ~(d.file_name(1)=='/' | d.file_name(2)==':')
if d.file_name(1:2)=='./'
d.file_name=[pwd d.file_name(3:length(file))];
else
d.file_name=[pwd '/' d.file_name];
end
end
fid=fopen(d.parent_file);
d.parent_file=fopen(fid);
fclose(fid);
if ~isfield(d,'dim')
d.dim = fliplr(miinquire(d.parent_file,'imagesize')');
d.dim = d.dim + (d.dim == 0);
end
if nargin==1
Z=1:d.dim(3);
T=1:d.dim(4);
end
if isfield(d,'precision')
precision=d.precision;
if isempty(precision)
precision='float';
end
else
precision='float';
end
if T(1)==1 & Z(1)==1
dim=d.dim;
if dim(4)==1
dim(4)=0;
end
if exist(d.file_name,'file')
delete(d.file_name);
end
newh=newimage(d.file_name,fliplr(dim),d.parent_file,precision);
if isfield(d,'df')
miwriteatt(d.file_name,'df','df',d.df);
end
if isfield(d,'nconj')
miwriteatt(d.file_name,'nconj','nconj',d.nconj);
end
if isfield(d,'fwhm')
miwriteatt(d.file_name,'fwhm','fwhm',d.fwhm);
end
else
newh=openimage(d.file_name,'w');
end
d.data=squeeze(reshape(d.data,d.dim(1)*d.dim(2),length(Z),length(T)));
if d.dim(4)<=1
putimages(newh,d.data,Z);
elseif length(T)==1|length(Z)==1
putimages(newh,d.data,Z,T);
else
for i=1:length(T)
putimages(newh,squeeze(d.data(:,:,i)),Z,T(i));
end
end
closeimage(newh);
return
end
%%
function [d]=fmris_write_nifti(d,Z,T)
if nargin<2
Z=1;
T=1;
end
if Z(1)==1 & T(1)==1
fidout=fopen(d.file_name,'w');
isniftiparent=0;
if isfield(d,'parent_file')
if exist(d.parent_file)
pf=deblank(d.parent_file);
ext=pf((length(pf)-2):length(pf));
isniftiparent=(ext=='nii');
end
end
if isniftiparent
machineformats='nlbdgcas';
for i=1:length(machineformats)
fid=fopen(d.parent_file,'r',machineformats(i));
sizeof_hdr=fread(fid,1,'int');
if sizeof_hdr==348;
%Must have found a formt that works, so break and continue using this format
break
else
%Need to close if file is not native format
%else if the file format is 's', then 7 stranded files are left orphaned and never closed.
fclose(fid);
end
end
data_type=fread(fid,10,'char');
db_name=fread(fid,18,'char');
extents=fread(fid,1,'int');
session_error=fread(fid,1,'short');
regular=char(fread(fid,1,'char')');
dim_info=char(fread(fid,1,'char')');
dim=fread(fid,8,'short');
intent_p =fread(fid,3,'float');
intent_code =fread(fid,1,'short');
datatype=fread(fid,1,'short');
bitpix=fread(fid,1,'short');
slice_start=fread(fid,1,'short');
pixdim=fread(fid,8,'float');
vox_offset=fread(fid,1,'float');
scl_slope=fread(fid,1,'float');
scl_inter=fread(fid,1,'float');
slice_end=fread(fid,1,'short');
slice_code =char(fread(fid,1,'char')');
xyzt_units =char(fread(fid,1,'char')');
cal_max=fread(fid,1,'float');
cal_min=fread(fid,1,'float');
slice_duration=fread(fid,1,'float');
toffset=fread(fid,1,'float');
glmax=fread(fid,1,'int');
glmin=fread(fid,1,'int');
descrip=char(fread(fid,80,'char')');
aux_file=char(fread(fid,24,'char')');
qform_code =fread(fid,1,'short');
sform_code =fread(fid,1,'short');
quatern_b =fread(fid,1,'float');
quatern_c =fread(fid,1,'float');
quatern_d =fread(fid,1,'float');
qoffset_x =fread(fid,1,'float');
qoffset_y =fread(fid,1,'float');
qoffset_z =fread(fid,1,'float');
srow_x =fread(fid,4,'float');
srow_y =fread(fid,4,'float');
srow_z =fread(fid,4,'float');
intent_name=char(fread(fid,16,'char')');
magic =fread(fid,4,'char');
fclose(fid);
else
data_type=' ';
db_name=' ';
extents=0;
session_error=0;
regular='r';
dim_info=' ';
slice_start=0;
pixdim=ones(1,8);
slice_code =' ';
xyzt_units =' ';
cal_max=25500;
cal_min=3;
slice_duration=0;
toffset=0;
aux_file=' ';
qform_code =1;
sform_code =0;
quatern_b =0;
quatern_c =1;
quatern_d =0;
qoffset_x =d.origin(1);
qoffset_y =d.origin(2);
qoffset_z =d.origin(3);
srow_x =[0 0 0 0];
srow_y =[0 0 0 0];
srow_z =[0 0 0 0];
intent_name=' ';
end
sizeof_hdr=348;
datatype=16;
bitpix=32;
vox_offset=352;
scl_slope =0;
scl_inter =0;
slice_end=0;
glmax=0;
glmin=0;
descrip=['FMRISTAT' repmat(' ',1,72)];
magic =[double('n+1') 0]';
dim=ones(1,8);
dim(1)=max(find(d.dim>1));
dim((1:dim(1))+1)=d.dim(1:dim(1));
if isfield(d,'vox')
pixdim=ones(1,8);
pixdim(1)=-1;
pixdim((1:dim(1))+1)=d.vox(1:dim(1));
end
intent_p=zeros(1,2);
if isfield(d,'df')
intent_p(1:length(d.df))=d.df;
intent_code=length(d.df)+2;
else
intent_code=0;
end
intent_q=zeros(1,2);
if isfield(d,'fwhm');
intent_q(1:length(d.fwhm))=d.fwhm;
end;
intent_q=round(intent_q/100*2^16);
intent_q=(intent_q.*(intent_q>=0)-2^16).*(intent_q<2^16)+2^16;
descrip=['FMRISTAT' repmat(' ',1,72)];
fwrite(fidout,sizeof_hdr,'int');
fwrite(fidout,data_type,'char');
fwrite(fidout,db_name,'char');
fwrite(fidout,extents,'int');
fwrite(fidout,session_error,'short');
fwrite(fidout,regular,'char');
fwrite(fidout,dim_info,'char');
fwrite(fidout,dim,'short');
fwrite(fidout,intent_p,'float');
fwrite(fidout,intent_q,'short');
fwrite(fidout,intent_code,'short');
fwrite(fidout,datatype,'short');
fwrite(fidout,bitpix,'short');
fwrite(fidout,slice_start,'short');
fwrite(fidout,pixdim,'float');
fwrite(fidout,vox_offset,'float');
fwrite(fidout,scl_slope ,'float');
fwrite(fidout,scl_inter ,'float');
fwrite(fidout,slice_end,'short');
fwrite(fidout,slice_code,'char');
fwrite(fidout,xyzt_units,'char');
fwrite(fidout,cal_max,'float');
fwrite(fidout,cal_min,'float');
fwrite(fidout,slice_duration,'float');
fwrite(fidout,toffset,'float');
fwrite(fidout,glmax,'int');
fwrite(fidout,glmin,'int');
fwrite(fidout,descrip,'char');
fwrite(fidout,aux_file,'char');
fwrite(fidout,qform_code,'short');
fwrite(fidout,sform_code,'short');
fwrite(fidout,quatern_b,'float');
fwrite(fidout,quatern_c,'float');
fwrite(fidout,quatern_d,'float');
fwrite(fidout,qoffset_x,'float');
fwrite(fidout,qoffset_y,'float');
fwrite(fidout,qoffset_z,'float');
fwrite(fidout,srow_x,'float');
fwrite(fidout,srow_y,'float');
fwrite(fidout,srow_z,'float');
fwrite(fidout,intent_name,'char');
fwrite(fidout,magic,'char');
fwrite(fidout,0,'float');
else
fidout=fopen(d.file_name,'r+');
end
if nargin<2
Z=1:d.dim(3);
T=1:d.dim(4);
end
vox_offset=352;
if ~isfield(d,'precision') | isempty(d.precision); d.precision='float32'; end;
if ~isfield(d,'byte') | isempty(d.byte); d.byte=4; end;
if Z(1)==1 & T(1)==1 & ~(all(Z==1:d.dim(3)) & all(T==1:d.dim(4)))
for t=1:d.dim(4)
fwrite(fidout,zeros(1,prod(d.dim(1:3))),d.precision);
end
end
if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))
for t=1:length(T)
for z=1:length(Z)
position=d.byte*((T(t)-1)*prod(d.dim(1:3))+(Z(z)-1)*prod(d.dim(1:2)))+vox_offset;
status=fseek(fidout,position,'bof');
if length(size(d.data))==4
fwrite(fidout,d.data(:,:,z,t),d.precision);
elseif length(T)==1
fwrite(fidout,d.data(:,:,z),d.precision);
elseif length(Z)==1
fwrite(fidout,d.data(:,:,t),d.precision);
else
'Slices and/or frames do not match data'
end
end
end
else
'Slices and/or frames out of range:'
Z
T
end
fclose(fidout);
return;
end
|
github | compneuro-da/rsHRF-master | SurfStatReadVol1.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/SurfStatReadVol1.m | 17,058 | utf_8 | a06b1de60d4f9453d2516675335e9cad | function d = SurfStatReadVol1( file, Z, T );
%Reads a single volumetric file in MINC, ANALYZE, NIFTI or AFNI format.
%
% Usage: d = SurfStatReadVol1( file [, Z, T] ).
%
% file = file name with extension .mnc, .img, .nii or .brik as above.
% Z = vector of slices.
% T = vector of times.
% If Z and T are both 0, then just the header is read into d.
% If Z and T are omitted, reads the entire volume.
if ~isstr(file)
d = file;
if isfield(d,'data') & nargin==3
if length(size(d.data))==4 & Z~=0 & T~=0
d.data=file.data(:,:,Z,T);
end
if length(size(d.data))==3 & length(Z)>1 & length(T)==1
d.data=file.data(:,:,Z);
end
if length(size(d.data))==3 & length(Z)==1 & length(T)>1
d.data=file.data(:,:,T);
end
if length(size(d.data))==3 & length(Z)==1 & length(T)==1 & Z>0 & T>0
d.data=file.data(:,:,Z);
end
end
return
end
file = deblank(file);
[path,name,ext]=fileparts(file);
if strcmp(ext,'.gz')
if isunix
unix(['gunzip ' file]);
else
['Can''t gunzip on non-unix system']
return
end
[path,name,ext]=fileparts(name)
end
switch lower(ext)
case '.mnc'
if nargin == 3
d = fmris_read_minc(file,Z,T);
else
d = fmris_read_minc(file);
end
case '.img'
if nargin == 3
d = fmris_read_analyze(file,Z,T);
else
d = fmris_read_analyze(file);
end
if isfield(d,'data') d.data(isnan(d.data))=0; end;
d.origin=-d.origin.*d.vox(1:3);
case '.brik'
if nargin == 3
d = fmris_read_afni(file,Z,T);
else
d = fmris_read_afni(file);
end
case '.nii'
if nargin == 3
d = fmris_read_nifti(file,Z,T);
else
d = fmris_read_nifti(file);
end
otherwise
['Unknown file extension']
end
d.parent_file=file;
return
end
%%
function [d]=fmris_read_afni(file,Z,T)
[err, Info]=BrikInfo(file);
d.dim = [Info.DATASET_DIMENSIONS(1:3) Info.DATASET_RANK(2)];
if nargin == 1
Z = 1:d.dim(3);
T = 1:d.dim(4);
end
if (T(1)~=0)&(Z(1)~=0)
Opt.Slices=Z;
Opt.Frames=T;
[err, d.data, Info, ErrMessage] = BrikLoad(file, Opt);
d.calib = [min(min(min(min(d.data)))) max(max(max(max(d.data))))];
end
d.vox = Info.DELTA;
d.vox_units = '';
d.vox_offset = 0;
d.precision = '';
d.calib_units = '';
d.origin = Info.ORIGIN;
d.descrip = '';
if isfield(Info,'WORSLEY_DF')
df=Info.WORSLEY_DF;
else
df=[];
end
if ~isempty(df)
d.df=df;
end
if isfield(Info,'WORSLEY_NCONJ')
nconj=Info.WORSLEY_NCONJ;
else
nconj=[];
end
if ~isempty(nconj)
d.nconj=nconj;
end
if isfield(Info,'WORSLEY_FWHM')
fwhm=Info.WORSLEY_FWHM;
else
fwhm=[];
end
if ~isempty(fwhm)
d.fwhm=fwhm;
end
return;
end
%%
function d=fmris_read_analyze(file,Z,T);
% Read in 1 4D or >1 3D Analyze format Image Volumes
%
% Usage
%
% d=Read_Analyze(file);
% Reads in all image data and attributes into the structure d.
%
% d=Read_Analyze(file,Z,T);
% Reads in chosen planes and frames and attributes into the structure d.
% Z and T are vectors e.g. Z=1:31;T=1:12; or Z=[24 26];T=[1 3 5];
%
% (c) Roger Gunn & John Aston
% Get machine format on which the file was written:
machineformat=getmachineformat(file);
if ~isempty(machineformat)
% Read Header Information
d=Read_Analyze_Hdr(file,machineformat);
d.file_name=file;
% try to get file precision if it is unknown:
if strcmp(d.precision,'Unknown')
d.precision=getprecision(deblank(file),machineformat,d.dim,d.global);
end
% Read Image Data
if ~isempty(d) & ~strcmp(d.precision,'Unknown')
if nargin==1 | strcmp(d.precision,'uint1')
% Read in Whole Analyze Volume
fid = fopen(d.file_name,'r',machineformat);
if fid > -1
d.data=d.scale*reshape(fread(fid,prod(d.dim),d.precision),d.dim(1),d.dim(2),d.dim(3),d.dim(4));
fclose(fid);
else
errordlg('Check Image File: Existence, Permissions ?','Read Error');
end;
if nargin==3
if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))
d.data=d.data(:,:,Z,T);
d.Z=Z;
d.T=T;
else
errordlg('Incompatible Matrix Identifiers !','Read Error');
end
end
elseif nargin==3
% Read in Chosen Planes and Frames
if (T(1)~=0)|(Z(1)~=0)
if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))
fid = fopen(d.file_name,'r',machineformat);
if fid > -1
d.data=zeros(d.dim(1),d.dim(2),length(Z),length(T));
for t=1:length(T)
for z=1:length(Z)
status=fseek(fid,d.hdr.byte*((T(t)-1)*prod(d.dim(1:3))+(Z(z)-1)*prod(d.dim(1:2))),'bof');
d.data(:,:,z,t)=d.scale*fread(fid,[d.dim(1) d.dim(2)],d.precision);
end
end
d.Z=Z;
d.T=T;
fclose(fid);
else
errordlg('Check Image File: Existence, Permissions ?','Read Error');
end;
else
errordlg('Incompatible Matrix Identifiers !','Read Error');
end;
end;
else
errordlg('Unusual Number of Arguments','Read Error');
end;
else
if strcmp(d.precision,'Unknown');
errordlg('Unknown Data Type (Precision?)','Read Error');
end
end;
else
errordlg('Unknown Machine Format','Read Error');
end
% if there is no slice thickness, set it to 6mm:
if d.vox(3)==0
d.vox(3)=6;
end
return;
end
%%
function machineformat=getmachineformat(file);
% Get machine format by reading the d.hdr.dim(1) attribute and
% making sure it is 1, 2, 3 or 4.
machineformat=[];
for mf='nlbdgcas'
fid = fopen([file(1:(length(file)-3)) 'hdr'],'r',mf);
if fid > -1
fseek(fid,40,'bof');
if any(fread(fid,1,'int16')==1:4)
machineformat=mf;
fclose(fid);
break
else
fclose(fid);
end
else
errordlg('Check Header File: Existence, Permissions ?','Read Error');
break
end
end
return
end
%%
function precision=getprecision(file,machineformat,dim,range);
% Get precision by reading a value from the middle of the .img file and
% making sure it is within the global attribute
precisions=['int8 '
'int16 '
'int32 '
'int64 '
'uint8 '
'uint16 '
'uint32 '
'uint64 '
'single '
'float32'
'double '
'float64' ];
nbytes=[1 2 4 8 1 2 4 8 4 4 8 8];
middle_vol=dim(1)*dim(2)*floor(dim(3)/2)+dim(1)*round(dim(2)/2)+round(dim(1)/2);
h=dir(file);
n=ceil(h.bytes/prod(dim));
fid = fopen(file,'r',machineformat);
if fid > -1
for i=1:size(precisions,1)
if nbytes(i)==n
status=fseek(fid,middle_vol*n,'bof');
if status==0
precision=deblank(precisions(i,:));
x=fread(fid,10,precision);
if all(range(1)<=x) & all(x<=range(2))
return
end
end
end
end
end
errordlg('Check Header File: Existence, Permissions ?','Read Error');
precision='Unknown';
return
end
%%
function d=Read_Analyze_Hdr(file,machineformat);
% Read Analyze Header information into the structure d
% Adapted from John Ashburners spm_hread.m
fid = fopen([file(1:(length(file)-3)) 'hdr'],'r',machineformat);
if fid > -1
% read (struct) header_key
%---------------------------------------------------------------------------
fseek(fid,0,'bof');
d.hdr.sizeof_hdr = fread(fid,1,'int32');
d.hdr.data_type = deblank(setstr(fread(fid,10,'char'))');
d.hdr.db_name = deblank(setstr(fread(fid,18,'char'))');
d.hdr.extents = fread(fid,1,'int32');
d.hdr.session_error = fread(fid,1,'int16');
d.hdr.regular = deblank(setstr(fread(fid,1,'char'))');
d.hdr.hkey_un0 = deblank(setstr(fread(fid,1,'char'))');
% read (struct) image_dimension
%---------------------------------------------------------------------------
fseek(fid,40,'bof');
d.hdr.dim = fread(fid,8,'int16');
d.hdr.vox_units = deblank(setstr(fread(fid,4,'char'))');
d.hdr.cal_units = deblank(setstr(fread(fid,8,'char'))');
d.hdr.unused1 = fread(fid,1,'int16');
d.hdr.datatype = fread(fid,1,'int16');
d.hdr.bitpix = fread(fid,1,'int16');
d.hdr.dim_un0 = fread(fid,1,'int16');
d.hdr.pixdim = fread(fid,8,'float');
d.hdr.vox_offset = fread(fid,1,'float');
d.hdr.funused1 = fread(fid,1,'float');
d.hdr.funused2 = fread(fid,1,'float');
d.hdr.funused3 = fread(fid,1,'float');
d.hdr.cal_max = fread(fid,1,'float');
d.hdr.cal_min = fread(fid,1,'float');
d.hdr.compressed = fread(fid,1,'int32');
d.hdr.verified = fread(fid,1,'int32');
d.hdr.glmax = fread(fid,1,'int32');
d.hdr.glmin = fread(fid,1,'int32');
% read (struct) data_history
%---------------------------------------------------------------------------
fseek(fid,148,'bof');
d.hdr.descrip = deblank(setstr(fread(fid,80,'char'))');
d.hdr.aux_file = deblank(setstr(fread(fid,24,'char'))');
d.hdr.orient = fread(fid,1,'char');
d.hdr.origin = fread(fid,5,'uint16');
d.hdr.generated = deblank(setstr(fread(fid,10,'char'))');
d.hdr.scannum = deblank(setstr(fread(fid,10,'char'))');
d.hdr.patient_id = deblank(setstr(fread(fid,10,'char'))');
d.hdr.exp_date = deblank(setstr(fread(fid,10,'char'))');
d.hdr.exp_time = deblank(setstr(fread(fid,10,'char'))');
d.hdr.hist_un0 = deblank(setstr(fread(fid,3,'char'))');
d.hdr.views = fread(fid,1,'int32');
d.hdr.vols_added = fread(fid,1,'int32');
d.hdr.start_field = fread(fid,1,'int32');
d.hdr.field_skip = fread(fid,1,'int32');
d.hdr.omax = fread(fid,1,'int32');
d.hdr.omin = fread(fid,1,'int32');
d.hdr.smax = fread(fid,1,'int32');
d.hdr.smin = fread(fid,1,'int32');
fclose(fid);
% Put important information in main structure
%---------------------------------------------------------------------------
d.dim = d.hdr.dim(2:5)';
vox = d.hdr.pixdim(2:5)';
if vox(4)==0
vox(4)=[];
end
d.vox = vox;
d.vox_units = d.hdr.vox_units;
d.vox_offset = d.hdr.vox_offset;
scale = d.hdr.funused1;
d.scale = ~scale + scale;
d.global = [d.hdr.glmin d.hdr.glmax];
d.calib = [d.hdr.cal_min d.hdr.cal_max];
d.calib_units = d.hdr.cal_units;
d.origin = d.hdr.origin(1:3)';
d.descrip = d.hdr.descrip(1:max(find(d.hdr.descrip)));
if ~isnan(str2double(d.hdr.scannum)); d.df(1) =str2double(d.hdr.scannum); end
if ~isnan(str2double(d.hdr.patient_id)); d.df(2) =str2double(d.hdr.patient_id); end
if ~isnan(str2double(d.hdr.exp_date)); d.fwhm(1)=str2double(d.hdr.exp_date); end
if ~isnan(str2double(d.hdr.exp_time)); d.fwhm(2)=str2double(d.hdr.exp_time); end
if ~isnan(str2double(d.hdr.hist_un0)); d.nconj =str2double(d.hdr.hist_un0); end
switch d.hdr.datatype
case 1
d.precision = 'uint1';
d.hdr.byte = 0;
case 2
d.precision = 'uint8';
d.hdr.byte = 1;
case 4
d.precision = 'int16';
d.hdr.byte = 2;
case 8
d.precision = 'int32';
d.hdr.byte = 4;
case 16
d.precision = 'float';
d.hdr.byte = 4;
case 64
d.precision = 'double';
d.hdr.byte = 8;
otherwise
d.precision = 'Unknown';
d.hdr.byte = 0;
end
else
d=[];
errordlg('Check Header File: Existence, Permissions ?','Read Error');
end
return
end
%%
function [d]=fmris_read_minc(file,Z,T)
fid=fopen(file);
file=fopen(fid);
fclose(fid);
d.file_name = file;
d.dim = fliplr(miinquire(file,'imagesize')');
d.dim = d.dim + (d.dim == 0);
if nargin == 1
Z = 1:d.dim(3);
T = 1:d.dim(4);
end
if (T~=0)&(Z~=0)
if d.dim(4)==1
images = mireadimages(file,Z-1);
else
n=length(T);
images=[];
for i=0:floor((n-1)/256)
frames=T((i*256+1):min((i+1)*256,n));
images = [images mireadimages(file,Z-1,frames-1)];
end
end
d.data = reshape(images,[d.dim(1:2) length(Z) length(T)]);
d.calib = [min(min(min(min(d.data)))) max(max(max(max(d.data))))];
end
[x_vox, y_vox, z_vox] = miinquire(file,'attvalue','xspace','step','attvalue','yspace','step','attvalue','zspace','step');
d.vox = [x_vox y_vox z_vox];
d.vox_units = '';
d.vox_offset = 0;
d.precision = '';
d.calib_units = '';
[x_origin, y_origin, z_origin] = miinquire(file,'attvalue','xspace','start','attvalue','yspace','start','attvalue','zspace','start');
d.origin = [x_origin y_origin z_origin];
d.descrip = '';
df=miinquire(file, 'attvalue', 'df', 'df');
if ~isempty(df)
d.df=df;
end
nconj=miinquire(file, 'attvalue', 'nconj', 'nconj');
if ~isempty(nconj)
d.nconj=nconj;
end
fwhm=miinquire(file, 'attvalue', 'fwhm', 'fwhm');
if ~isempty(fwhm)
d.fwhm=fwhm;
end
return;
end
%%
function [d]=fmris_read_nifti(file,Z,T)
d.file_name=file;
machineformats='nlbdgcas';
for i=1:length(machineformats)
fid=fopen(file,'r',machineformats(i));
if fid == -1;
fprintf('Invalid file %s',file)
end
sizeof_hdr=fread(fid,1,'int');
if sizeof_hdr==348;
%Must have found a formt that works, so break and continue using this format
break;
else
%Need to close if file is not native format
%else if the file format is 's', then 7 stranded files are left orphaned and never closed.
fclose(fid);
end
end
data_type=fread(fid,10,'char');
db_name=fread(fid,18,'char');
extents=fread(fid,1,'int');
session_error=fread(fid,1,'short');
regular=char(fread(fid,1,'char')');
dim_info=char(fread(fid,1,'char')');
dim=fread(fid,8,'short');
intent_p =fread(fid,2,'float');
intent_q =fread(fid,2,'uint16');
intent_code =fread(fid,1,'short');
datatype=fread(fid,1,'short');
bitpix=fread(fid,1,'short');
slice_start=fread(fid,1,'short');
pixdim=fread(fid,8,'float');
vox_offset=fread(fid,1,'float');
scl_slope =fread(fid,1,'float');
scl_inter =fread(fid,1,'float');
slice_end=fread(fid,1,'short');
slice_code =char(fread(fid,1,'char')');
xyzt_units =char(fread(fid,1,'char')');
cal_max=fread(fid,1,'float');
cal_min=fread(fid,1,'float');
slice_duration=fread(fid,1,'float');
toffset=fread(fid,1,'float');
glmax=fread(fid,1,'int');
glmin=fread(fid,1,'int');
descrip=char(fread(fid,80,'char')');
aux_file=char(fread(fid,24,'char')');
qform_code =fread(fid,1,'short');
sform_code =fread(fid,1,'short');
quatern_b =fread(fid,1,'float');
quatern_c =fread(fid,1,'float');
quatern_d =fread(fid,1,'float');
qoffset_x =fread(fid,1,'float');
qoffset_y =fread(fid,1,'float');
qoffset_z =fread(fid,1,'float');
srow_x =fread(fid,4,'float');
srow_y =fread(fid,4,'float');
srow_z =fread(fid,4,'float');
intent_name=char(fread(fid,16,'char')');
magic =char(fread(fid,4,'char')');
d.machineformat=machineformats(i);
d.dim=ones(1,4);
if dim(1)==5
if dim(5)==1
dim=[4; dim(2:4); dim(6); zeros(3,1)]
else
dim
fclose(fid);
return
end
end
d.dim(1:dim(1))=dim((1:dim(1))+1);
d.vox=zeros(1,3);
d.vox(1:dim(1))=pixdim((1:dim(1))+1);
%Attempt to fill out more information for a complete nifti description
d.vox_offset = vox_offset;
d.scale = scl_slope;
d.intercept = scl_inter;
d.global = [glmin glmax];
d.calib = [cal_min cal_max];
if qform_code>0;
d.origin = [qoffset_x qoffset_y qoffset_z];
else
d.origin = [srow_x(4) srow_y(4) srow_z(4)];
end
d.descrip = descrip;
d.parent_file=file;
if intent_p(1)>0; d.df(1)=intent_p(1); end;
if intent_p(2)>0; d.df(2)=intent_p(2); end;
intent_q=intent_q/2^16*100;
if intent_q(1)>0; d.fwhm(1)=intent_q(1); end;
if intent_q(2)>0; d.fwhm(2)=intent_q(2); end;
if nargin<2
Z=1:d.dim(3);
T=1:d.dim(4);
end
if Z(1)==0 & T(1)==0
fclose(fid);
return
end
types=lower(['UINT8 ';'INT16 ';'INT32 ';'FLOAT32';'FLOAT64']);
codes=[2; 4; 8; 16; 64];
d.precision=[];
for i=1:5
if datatype==codes(i)
d.precision=deblank(types(i,:));
end
end
if isempty(d.precision)
unknown_datatype=datatype
fclose(fid);
return
end
%d.byte=bitpix/8
d.byte=4;
if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))
d.data=zeros(d.dim(1),d.dim(2),length(Z),length(T));
for t=1:length(T)
for z=1:length(Z)
position=d.byte*((T(t)-1)*prod(d.dim(1:3))+(Z(z)-1)*prod(d.dim(1:2)))+vox_offset;
status=fseek(fid,position,'bof');
d.data(:,:,z,t)=fread(fid,[d.dim(1) d.dim(2)],d.precision);
end
end
fclose(fid);
else
Z
T
fclose(fid);
return
end
if scl_slope~=0
d.data=d.data*scl_slope+scl_inter;
end
return;
end
|
github | compneuro-da/rsHRF-master | stat_threshold.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/stat_threshold.m | 27,286 | utf_8 | 75dcc644078e278b556f0acc871d984d | function [ peak_threshold, extent_threshold, ...
peak_threshold_1, extent_threshold_1, t, rho ] = ...
stat_threshold( search_volume, num_voxels, fwhm, df, p_val_peak, ...
cluster_threshold, p_val_extent, nconj, nvar, EC_file, expr, nprint );
%Thresholds and P-values of peaks and clusters of random fields in any D.
%
% [PEAK_THRESHOLD, EXTENT_THRESHOLD, PEAK_THRESHOLD_1 EXTENT_THRESHOLD_1] =
% STAT_THRESHOLD([ SEARCH_VOLUME [, NUM_VOXELS [, FWHM [, DF [, P_VAL_PEAK
% [, CLUSTER_THRESHOLD [, P_VAL_EXTENT [, NCONJ [, NVAR [, EC_FILE
% [, TRANSFORM [, NPRINT ]]]]]]]]]]]] );
%
% If P-values are supplied, returns the thresholds for local maxima
% or peaks (PEAK_THRESHOLD) (if thresholds are supplied then it
% returns P-values) for the following SPMs:
% - Z, chi^2, t, F, Hotelling's T^2, Roy's maximum root, maximum
% canonical correlation, cross- and auto-correlation;
% - scale space Z and chi^2;
% - conjunctions of NCONJ of these (except cross- and auto-correlation);
% and spatial extent of contiguous voxels above CLUSTER_THRESHOLD
% (EXTENT_THRESHOLD) except conjunctions. Note that for the multivariate
% statistics spatial extent is measured in resels for the higher
% dimensional space formed by adding sphere(s) to the search region.
%
% For peaks (local maxima), two methods are used:
% random field theory (Worsley et al. 1996, Human Brain Mapping, 4:58-73),
% and a simple Bonferroni correction based on the number of voxels
% in the search region. The final threshold is the minimum of the two.
%
% For clusters, the method of Cao, 1999, Advances in Applied Probability,
% 31:577-593 is used. The cluster size is only accurate for large
% CLUSTER_THRESHOLD (say >3) and large resels = SEARCH_VOLUME / FWHM^D.
%
% PEAK_THRESHOLD_1 is the height of a single peak chosen in advance, and
% EXTENT_THRESHOLD_1 is the extent of a single cluster chosen in advance
% of looking at the data, e.g. the nearest peak or cluster to a pre-chosen
% voxel or ROI - see Friston KJ. Testing for anatomically specified
% regional effects. Human Brain Mapping. 5(2):133-6, 1997.
%
% SEARCH_VOLUME is the volume of the search region in mm^3. The method for
% finding PEAK_THRESHOLD works well for any value of SEARCH_VOLUME, even
% SEARCH_VOLUME = 0 (default), which gives the threshold for the image at
% a single voxel. The random field theory threshold is based on the
% assumption that the search region is a sphere in 3D, which is a very
% tight lower bound for any non-spherical region.
% For a non-spherical D-dimensional region, set SEARCH_VOLUME to a vector
% of the D+1 intrinsic volumes of the search region. In D=3 these are
% [Euler characteristic, 2 * caliper diameter, 1/2 surface area, volume].
% E.g. for a sphere of radius r in 3D, use [1, 4*r, 2*pi*r^2, 4/3*pi*r^3],
% which is equivalent to just SEARCH_VOLUME = 4/3*pi*r^3.
% For a 2D search region, use [1, 1/2 perimeter length, area].
% For cross- and auto-correlations, where correlation is maximized over all
% pairs of voxels from two search regions, SEARCH_VOLUME has two rows
% interpreted as above - see Cao, J. & Worsley, K.J. (1999). The geometry
% of correlation fields, with an application to functional connectivity of
% the brain. Annals of Applied Probability, 9:1021-1057.
%
% NUM_VOXELS is the number of voxels (3D) or pixels (2D) in the search
% volume. For cross- and auto-correlations, use two rows. Default is 1.
%
% FWHM is the fwhm in mm of a smoothing kernel applied to the data. Default
% is 0.0, i.e. no smoothing, which is roughly the case for raw fMRI data.
% For motion corrected fMRI data, use at least 6mm; for PET data, this would
% be the scanner fwhm of about 6mm. Using the geometric mean of the three
% x,y,z FWHM's is a very good approximation if they are different.
% If you have already calculated resels, then set SEARCH_VOLUME=resels
% and FWHM=1. Cluster extents will then be in resels, rather than mm^3.
% For cross- and auto-correlations, use two rows. For scale space, use two
% columns for the min and max fwhm (only for Z and chi^2 SPMs).
%
% DF=[DF1 DF2; DFW1 DFW2 0] is a 2 x 2 matrix of degrees of freedom.
% If DF2 is 0, then DF1 is the df of the T statistic image.
% If DF1=Inf then it calculates thresholds for the Gaussian image.
% If DF2>0 then DF1 and DF2 are the df's of the F statistic image.
% DFW1 and DFW2 are the numerator and denominator df of the FWHM image.
% They are only used for calculating cluster resel p-values and thresholds
% (ignored if NVAR>1 or NCONJ>1 since there are no theoretical results).
% The random estimate of the local resels adds variability to the summed
% resels of the cluster. The distribution of the local resels summed over a
% region depends on the unknown spatial correlation structure of the resels,
% so we assume that the resels are constant over the cluster, reasonable if the
% clusters are small. The cluster resels are then multiplied by the random resel
% distribution at a point. This gives an upper bound to p-values and thresholds.
% If DF=[DF1 DF2] (row) then DFW1=DFW2=Inf, i.e. FWHM is fixed.
% If DF=[DF1; DFW1] (column) then DF2=0 and DFW2=DFW1, i.e. t statistic.
% If DF=DF1 (scalar) then DF2=0 and DFW1=DFW2=Inf, i.e. t stat, fixed FWHM.
% If any component of DF >= 1000 then it is set to Inf. Default is Inf.
%
% P_VAL_PEAK is the row vector of desired P-values for peaks.
% If the first element is greater than 1, then they are
% treated as peak values and P-values are returned. Default is 0.05.
% To get P-values for peak values < 1, set the first element > 1,
% set the second to the deisired peak value, then discard the first result.
%
% CLUSTER_THRESHOLD is the scalar threshold of the image for clusters.
% If it is <= 1, it is taken as a probability p, and the
% cluter_thresh is chosen so that P( T > cluster_thresh ) = p.
% Default is 0.001, i.e. P( T > cluster_thresh ) = 0.001.
%
% P_VAL_EXTENT is the row vector of desired P-values for spatial extents
% of clusters of contiguous voxels above CLUSTER_THRESHOLD.
% If the first element is greater than 1, then they are treated as
% extent values and P-values are returned. Default is 0.05.
%
% NCONJ is the number of conjunctions. If NCONJ > 1, calculates P-values and
% thresholds for peaks (but not clusters) of the minimum of NCONJ independent
% SPM's - see Friston, K.J., Holmes, A.P., Price, C.J., Buchel, C.,
% Worsley, K.J. (1999). Multi-subject fMRI studies and conjunction analyses.
% NeuroImage, 10:385-396. Default is NCONJ = 1 (no conjunctions).
%
% NVAR is the number of variables for multivariate equivalents of T and F
% statistics, found by maximizing T^2 or F over all linear combinations of
% variables, i.e. Hotelling's T^2 for DF1=1, Roy's maximum root for DF1>1.
% For maximum canonical cross- and auto-correlations, use two rows.
% See Worsley, K.J., Taylor, J.E., Tomaiuolo, F. & Lerch, J. (2004). Unified
% univariate and multivariate random field theory. Neuroimage, 23:S189-195.
% Default is 1, i.e. univariate statistics.
%
% EC_FILE: file for EC densities in IRIS Explorer latin module format.
% Ignored if empty (default).
%
% EXPR: matlab expression applied to threshold in t, e.g. 't=sqrt(t);'.
%
% NPRINT: maximum number of P-values or thresholds to print. Default 5.
%
% Examples:
%
% T statistic, 1000000mm^3 search volume, 1000000 voxels (1mm voxel volume),
% 20mm smoothing, 30 degrees of freedom, P=0.05 and 0.01 for peaks, cluster
% threshold chosen so that P=0.001 at a single voxel, P=0.05 and 0.01 for extent:
%
% stat_threshold(1000000,1000000,20,30,[0.05 0.01],0.001,[0.05 0.01]);
%
% peak_threshold = 5.0826 5.7853
% Cluster_threshold = 3.3852
% peak_threshold_1 = 4.8782 5.5955
% extent_threshold = 3340.3 6315.5
% extent_threshold_1 = 2911.5 5719.6
%
% Check: Suppose we are given peak values of 5.0826, 5.7853 and
% spatial extents of 3340.3, 6315.5 above a threshold of 3.3852,
% then we should get back our original P-values:
%
% stat_threshold(1000000,1000000,20,30,[5.0826 5.7853],3.3852,[3340.3 6315.5]);
%
% P_val_peak = 0.0500 0.0100
% P_val_peak_1 = 0.0318 0.0065
% P_val_extent = 0.0500 0.0100
% P_val_extent_1 = 0.0379 0.0074
%
% Another way of doing this is to use the fact that T^2 has an F
% distribution with 1 and 30 degrees of freedom, and double the P values:
%
% stat_threshold(1000000,1000000,20,[1 30],[0.1 0.02],0.002,[0.1 0.02]);
%
% peak_threshold = 25.8330 33.4702
% Cluster_threshold = 11.4596
% peak_threshold_1 = 20.7886 27.9741
% extent_threshold = 3297.8 6305.2
% extent_threshold_1 = 1936.4 4420.3
%
% Note that sqrt([25.8330 33.4702 11.4596])=[5.0826 5.7853 3.3852]
% in agreement with the T statistic thresholds, but the spatial extent
% thresholds are very close but not exactly the same.
%
% If the shape of the search region is known, then the 'intrinisic
% volume' must be supplied. E.g. for a spherical search region with
% a volume of 1000000 mm^3, radius r:
%
% r=(1000000/(4/3*pi))^(1/3);
% stat_threshold([1 4*r 2*pi*r^2 4/3*pi*r^3], ...
% 1000000,20,30,[0.05 0.01],0.001,[0.05 0.01]);
%
% gives the same results as our first example. A 100 x 100 x 100 cube
%
% stat_threshold([1 300 30000 1000000], ...
% 1000000,20,30,[0.05 0.01],0.001,[0.05 0.01]);
%
% gives slightly higher thresholds (5.0969, 5.7976) for peaks, but the cluster
% thresholds are the same since they depend (so far) only on the volume and
% not the shape. For a 2D circular search region of the same radius r, use
%
% stat_threshold([1 pi*r pi*r^2],1000000,20,30,[0.05 0.01],0.001,[0.05 0.01]);
%
% A volume of 0 returns the usual uncorrected threshold for peaks,
% which can also be found by setting NUM_VOXELS=1, FWHM = 0:
%
% stat_threshold(0,1,20,30,[0.05 0.01])
% stat_threshold(1,1, 0,30,[0.05 0.01]);
%
% For non-isotropic fields, replace the SEARCH_VOLUME by the vector of resels
% (see Worsley et al. 1996, Human Brain Mapping, 4:58-73), and set FWHM=1,
% so that EXTENT_THRESHOLD's are measured in resels, not mm^3. If the
% resels are estimated from residuals, add an extra row to DF (see above).
%
% For the conjunction of 2 and 3 T fields as above:
%
% stat_threshold(1000000,1000000,20,30,[0.05 0.01],[],[],2)
% stat_threshold(1000000,1000000,20,30,[0.05 0.01],[],[],3)
%
% returns lower thresholds of [3.0251 3.3984] and [2.2336 2.5141] resp. Note
% that there are as yet no theoretical results for extents so they are NaN.
%
% For Hotelling's T^2 e.g. for linear models of deformations (NVAR=3):
%
% stat_threshold(1000000,1000000,20,[1 30],[0.05 0.01],[],[],1,3)
%
% For Roy's max root, e.g. for effective connectivity using deformations,
%
% stat_threshold(1000000,1000000,20,[3 30],[0.05 0.01],[],[],1,3)
%
% There are no theoretical results for mulitvariate extents so they are NaN.
% Check: A Hotelling's T^2 with Inf df is the same as a chi^2 with NVAR df
%
% stat_threshold(1000000,1000000,20,[1 Inf],[],[],[],[],NVAR)
% stat_threshold(1000000,1000000,20,[NVAR Inf])*NVAR
%
% should give the same answer!
%
% Cross- and auto-correlations: to threshold the auto-correlation of fmrilm
% residuals (100 df) over all pairs of 1000000 voxels in a 1000000mm^3
% region with 20mm FWHM smoothing, use df=99 (one less for the correlation):
%
% stat_threshold([1000000; 1000000], [1000000; 1000000], 20, 99, 0.05)
%
% which gives a T statistic threshold of 6.7923 with 99 df. To convert to
% a correlation, use 6.7923/sqrt(99+6.7923^2)=0.5638. Note that auto-
% correlations are symmetric, so the P-value is in fact 0.05/2=0.025; on the
% other hand, we usually want a two sided test of both positive and negative
% correlations, so the P-value should be doubled back to 0.05. For cross-
% correlations, e.g. between n=321 GM density volumes (1000000mm^3 ball,
% FWHM=13mm) and cortical thickness on the average surface (250000mm^2,
% FWHM=18mm), use 321-2=319 df for removing the constant and the correlation.
% Note that we use P=0.025 to threshold both +ve and -ve correlations.
%
% r=(1000000/(4/3*pi))^(1/3);
% stat_threshold([1 4*r 2*pi*r^2 4/3*pi*r^3; 1 0 250000 0], ...
% [1000000; 40962], [13; 18], 319, 0.025)
%
% This gives a T statistic threshold of 6.7158 with 319 df. To convert to
% a correlation, use 6.7158/sqrt(319+6.7158^2)=0.3520. Note that NVAR can be
% greater than one for maximum canonical cross- and auto-correlations
% between all pairs of multivariate imaging data. Finally, the spatial
% extent for 5D clusters of connected correlations is 5.9228e+006 mm^5.
%
% Scale space: suppose we smooth 1000000 voxels in a 1000000mm^3 region
% from 6mm to 30mm in 10 steps ( e.g. fwhm=6*(30/6).^((0:9)/9) ):
%
% stat_threshold(1000000, 1000000*10, [6 30])
%
% gives a scale space threshold of 5.0663, only slightly higher than the
% 5.0038 you get from using the highest resolution data only, i.e.
%
% stat_threshold(1000000, 1000000, 6)
%############################################################################
% COPYRIGHT: Copyright 2003 K.J. Worsley
% Department of Mathematics and Statistics,
% McConnell Brain Imaging Center,
% Montreal Neurological Institute,
% McGill University, Montreal, Quebec, Canada.
% [email protected] , www.math.mcgill.ca/keith
%
% Permission to use, copy, modify, and distribute this
% software and its documentation for any purpose and without
% fee is hereby granted, provided that this copyright
% notice appears in all copies. The author and McGill University
% make no representations about the suitability of this
% software for any purpose. It is provided "as is" without
% express or implied warranty.
%############################################################################
% Defaults:
if nargin<1; search_volume=[]; end
if nargin<2; num_voxels=[]; end
if nargin<3; fwhm=[]; end
if nargin<4; df=[]; end
if nargin<5; p_val_peak=[]; end
if nargin<6; cluster_threshold=[]; end
if nargin<7; p_val_extent=[]; end
if nargin<8; nconj=[]; end
if nargin<9; nvar=[]; end
if nargin<10; EC_file=[]; end
if nargin<11; expr=[]; end
if nargin<12; nprint=[]; end
if isempty(search_volume); search_volume=0; end
if isempty(num_voxels); num_voxels=1; end
if isempty(fwhm); fwhm=0.0; end
if isempty(df); df=Inf; end
if isempty(p_val_peak); p_val_peak=0.05; end
if isempty(cluster_threshold); cluster_threshold=0.001; end
if isempty(p_val_extent); p_val_extent=0.05; end
if isempty(nconj); nconj=1; end
if isempty(nvar); nvar=1; end
if isempty(nprint); nprint=5; end
if size(fwhm,1)==1; fwhm(2,:)=fwhm; end
if size(fwhm,2)==1; scale=1; else scale=fwhm(1,2)/fwhm(1,1); fwhm=fwhm(:,1); end;
isscale=(scale>1);
if length(num_voxels)==1; num_voxels(2,1)=1; end
if size(search_volume,2)==1
radius=(search_volume/(4/3*pi)).^(1/3);
search_volume=[ones(length(radius),1) 4*radius 2*pi*radius.^2 search_volume];
end
if size(search_volume,1)==1
search_volume=[search_volume; [1 zeros(1,size(search_volume,2)-1)]];
end
lsv=size(search_volume,2);
fwhm_inv=all(fwhm>0)./(fwhm+any(fwhm<=0));
resels=search_volume.*repmat(fwhm_inv,1,lsv).^repmat(0:lsv-1,2,1);
invol=resels.*(4*log(2)).^(repmat(0:lsv-1,2,1)/2);
for k=1:2
D(k,1)=max(find(invol(k,:)))-1;
end
% determines which method was used to estimate fwhm (see fmrilm or multistat):
df_limit=4;
if length(df)==1; df=[df 0]; end
if size(df,1)==1; df=[df; Inf Inf; Inf Inf]; end
if size(df,2)==1; df=[df df]; df(1,2)=0; end
if size(df,1)==2; df=[df; df(2,:)]; end
% is_tstat=1 if it is a t statistic
is_tstat=(df(1,2)==0);
if is_tstat
df1=1;
df2=df(1,1);
else
df1=df(1,1);
df2=df(1,2);
end
if df2 >= 1000; df2=Inf; end
df0=df1+df2;
dfw1=df(2:3,1);
dfw2=df(2:3,2);
for k=1:2
if dfw1(k) >= 1000; dfw1(k)=Inf; end
if dfw2(k) >= 1000; dfw2(k)=Inf; end
end
if length(nvar)==1; nvar(2,1)=df1; end
if isscale & (D(2)>1 | nvar(1,1)>1 | df2<Inf)
D
nvar
df2
fprintf('Cannot do scale space.');
return
end
Dlim=D+[scale>1; 0];
DD=Dlim+nvar-1;
% Values of the F statistic:
t=((1000:-1:1)'/100).^4;
% Find the upper tail probs cumulating the F density using Simpson's rule:
if df2==Inf
u=df1*t;
b=exp(-u/2-log(2*pi)/2+log(u)/4)*df1^(1/4)*4/100;
else
u=df1*t/df2;
b=exp(-df0/2*log(1+u)+log(u)/4-betaln(1/2,(df0-1)/2))*(df1/df2)^(1/4)*4/100;
end
t=[t; 0];
b=[b; 0];
n=length(t);
sb=cumsum(b);
sb1=cumsum(b.*(-1).^(1:n)');
pt1=sb+sb1/3-b/3;
pt2=sb-sb1/3-b/3;
tau=zeros(n,DD(1)+1,DD(2)+1);
tau(1:2:n,1,1)=pt1(1:2:n);
tau(2:2:n,1,1)=pt2(2:2:n);
tau(n,1,1)=1;
tau(:,1,1)=min(tau(:,1,1),1);
% Find the EC densities:
u=df1*t;
for d=1:max(DD)
for e=0:min(min(DD),d)
s1=0;
cons=-((d+e)/2+1)*log(pi)+gammaln(d)+gammaln(e+1);
for k=0:(d-1+e)/2
[i,j]=ndgrid(0:k,0:k);
if df2==Inf
q1=log(pi)/2-((d+e-1)/2+i+j)*log(2);
else
q1=(df0-1-d-e)*log(2)+gammaln((df0-d)/2+i)+gammaln((df0-e)/2+j) ...
-gammalni(df0-d-e+i+j+k)-((d+e-1)/2-k)*log(df2);
end
q2=cons-gammalni(i+1)-gammalni(j+1)-gammalni(k-i-j+1) ...
-gammalni(d-k-i+j)-gammalni(e-k-j+i+1);
s2=sum(sum(exp(q1+q2)));
if s2>0
s1=s1+(-1)^k*u.^((d+e-1)/2-k)*s2;
end
end
if df2==Inf
s1=s1.*exp(-u/2);
else
s1=s1.*exp(-(df0-2)/2*log(1+u/df2));
end
if DD(1)>=DD(2)
tau(:,d+1,e+1)=s1;
if d<=min(DD)
tau(:,e+1,d+1)=s1;
end
else
tau(:,e+1,d+1)=s1;
if d<=min(DD)
tau(:,d+1,e+1)=s1;
end
end
end
end
% For multivariate statistics, add a sphere to the search region:
a=zeros(2,max(nvar));
for k=1:2
j=(nvar(k)-1):-2:0;
a(k,j+1)=exp(j*log(2)+j/2*log(pi) ...
+gammaln((nvar(k)+1)/2)-gammaln((nvar(k)+1-j)/2)-gammaln(j+1));
end
rho=zeros(n,Dlim(1)+1,Dlim(2)+1);
for k=1:nvar(1)
for l=1:nvar(2)
rho=rho+a(1,k)*a(2,l)*tau(:,(0:Dlim(1))+k,(0:Dlim(2))+l);
end
end
if is_tstat
if nvar==1
t=[sqrt(t(1:(n-1))); -flipdim(sqrt(t),1)];
rho=[rho(1:(n-1),:,:); flipdim(rho,1)]/2;
for i=0:D(1)
for j=0:D(2)
rho(n-1+(1:n),i+1,j+1)=-(-1)^(i+j)*rho(n-1+(1:n),i+1,j+1);
end
end
rho(n-1+(1:n),1,1)=rho(n-1+(1:n),1,1)+1;
n=2*n-1;
else
t=sqrt(t);
end
end
% For scale space:
if scale>1
kappa=D(1)/2;
tau=zeros(n,D(1)+1);
for d=0:D(1)
s1=0;
for k=0:d/2
s1=s1+(-1)^k/(1-2*k)*exp(gammaln(d+1)-gammaln(k+1)-gammaln(d-2*k+1) ...
+(1/2-k)*log(kappa)-k*log(4*pi))*rho(:,d+2-2*k,1);
end
if d==0
cons=log(scale);
else
cons=(1-1/scale^d)/d;
end
tau(:,d+1)=rho(:,d+1,1)*(1+1/scale^d)/2+s1*cons;
end
rho(:,1:(D(1)+1),1)=tau;
end
if D(2)==0
d=D(1);
if nconj>1
% Conjunctions:
b=gamma(((0:d)+1)/2)/gamma(1/2);
for i=1:d+1
rho(:,i,1)=rho(:,i,1)/b(i);
end
m1=zeros(n,d+1,d+1);
for i=1:d+1
j=i:d+1;
m1(:,i,j)=rho(:,j-i+1,1);
end
for k=2:nconj
for i=1:d+1
for j=1:d+1
m2(:,i,j)=sum(rho(:,1:d+2-i,1).*m1(:,i:d+1,j),2);
end
end
m1=m2;
end
for i=1:d+1
rho(:,i,1)=m1(:,1,i)*b(i);
end
end
if ~isempty(EC_file)
if d<3
rho(:,(d+2):4,1)=zeros(n,4-d-2+1);
end
fid=fopen(EC_file,'w');
% first 3 are dimension sizes as 4-byte integers:
fwrite(fid,[n max(d+2,5) 1],'int');
% next 6 are bounding box as 4-byte floats:
fwrite(fid,[0 0 0; 1 1 1],'float');
% rest are the data as 4-byte floats:
if ~isempty(expr)
eval(expr);
end
fwrite(fid,t,'float');
fwrite(fid,rho,'float');
fclose(fid);
end
end
if all(fwhm>0)
pval_rf=zeros(n,1);
for i=1:D(1)+1
for j=1:D(2)+1
pval_rf=pval_rf+invol(1,i)*invol(2,j)*rho(:,i,j);
end
end
else
pval_rf=Inf;
end
% Bonferroni
pt=rho(:,1,1);
pval_bon=abs(prod(num_voxels))*pt;
% Minimum of the two:
pval=min(pval_rf,pval_bon);
tlim=1;
if p_val_peak(1) <= tlim
peak_threshold=minterp1(pval,t,p_val_peak);
if length(p_val_peak)<=nprint
peak_threshold
end
else
% p_val_peak is treated as a peak value:
P_val_peak=interp1(t,pval,p_val_peak);
i=isnan(P_val_peak);
P_val_peak(i)=(is_tstat & (p_val_peak(i)<0));
peak_threshold=P_val_peak;
if length(p_val_peak)<=nprint
P_val_peak
end
end
if all(fwhm<=0) | any(num_voxels<0)
peak_threshold_1=p_val_peak+NaN;
extent_threshold=p_val_extent+NaN;
extent_threshold_1=extent_threshold;
return
end
% Cluster_threshold:
if cluster_threshold > tlim
tt=cluster_threshold;
else
% cluster_threshold is treated as a probability:
tt=minterp1(pt,t,cluster_threshold);
if nprint>0
Cluster_threshold=tt
end
end
d=sum(D);
rhoD=interp1(t,rho(:,D(1)+1,D(2)+1),tt);
p=interp1(t,pt,tt);
% Pre-selected peak:
pval=rho(:,D(1)+1,D(2)+1)./rhoD;
if p_val_peak(1) <= tlim
peak_threshold_1=minterp1(pval,t, p_val_peak);
if length(p_val_peak)<=nprint
peak_threshold_1
end
else
% p_val_peak is treated as a peak value:
P_val_peak_1=interp1(t,pval,p_val_peak);
i=isnan(P_val_peak_1);
P_val_peak_1(i)=(is_tstat & (p_val_peak(i)<0));
peak_threshold_1=P_val_peak_1;
if length(p_val_peak)<=nprint
P_val_peak_1
end
end
if d==0 | nconj>1 | nvar(1)>1 | scale>1
extent_threshold=p_val_extent+NaN;
extent_threshold_1=extent_threshold;
if length(p_val_extent)<=nprint
extent_threshold
extent_threshold_1
end
return
end
% Expected number of clusters:
EL=invol(1,D(1)+1)*invol(2,D(2)+1)*rhoD;
cons=gamma(d/2+1)*(4*log(2))^(d/2)/fwhm(1)^D(1)/fwhm(2)^D(2)*rhoD/p;
if df2==Inf & dfw1(1)==Inf & dfw1(2)==Inf
if p_val_extent(1) <= tlim
pS=-log(1-p_val_extent)/EL;
extent_threshold=(-log(pS)).^(d/2)/cons;
pS=-log(1-p_val_extent);
extent_threshold_1=(-log(pS)).^(d/2)/cons;
if length(p_val_extent)<=nprint
extent_threshold
extent_threshold_1
end
else
% p_val_extent is now treated as a spatial extent:
pS=exp(-(p_val_extent*cons).^(2/d));
P_val_extent=1-exp(-pS*EL);
extent_threshold=P_val_extent;
P_val_extent_1=1-exp(-pS);
extent_threshold_1=P_val_extent_1;
if length(p_val_extent)<=nprint
P_val_extent
P_val_extent_1
end
end
else
% Find dbn of S by taking logs then using fft for convolution:
ny=2^12;
a=d/2;
b2=a*10*max(sqrt(2/(min(df1+df2,min(dfw1)))),1);
if df2<Inf
b1=a*log((1-(1-0.000001)^(2/(df2-d)))*df2/2);
else
b1=a*log(-log(1-0.000001));
end
dy=(b2-b1)/ny;
b1=round(b1/dy)*dy;
y=((1:ny)'-1)*dy+b1;
numrv=1+(d+(D(1)>0)+(D(2)>0))*(df2<Inf)+...
(D(1)*(dfw1(1)<Inf)+(dfw2(1)<Inf))*(D(1)>0)+...;
(D(2)*(dfw1(2)<Inf)+(dfw2(2)<Inf))*(D(2)>0);
f=zeros(ny,numrv);
mu=zeros(1,numrv);
if df2<Inf
% Density of log(Beta(1,(df2-d)/2)^(d/2)):
yy=exp(y./a)/df2*2;
yy=yy.*(yy<1);
f(:,1)=(1-yy).^((df2-d)/2-1).*((df2-d)/2).*yy/a;
mu(1)=exp(gammaln(a+1)+gammaln((df2-d+2)/2)-gammaln((df2+2)/2)+a*log(df2/2));
else
% Density of log(exp(1)^(d/2)):
yy=exp(y./a);
f(:,1)=exp(-yy).*yy/a;
mu(1)=exp(gammaln(a+1));
end
nuv=[];
aav=[];
if df2<Inf
nuv=df2+2-(1:d);
aav=[repmat(-1/2,1,d)];
for k=1:2
if D(k)>0;
nuv=[df1+df2-D(k) nuv];
aav=[D(k)/2 aav];
end;
end;
end
for k=1:2
if dfw1(k)<Inf & D(k)>0
if dfw1(k)>df_limit
nuv=[nuv dfw1(k)-dfw1(k)/dfw2(k)-(0:(D(k)-1))];
else
nuv=[nuv repmat(dfw1(k)-dfw1(k)/dfw2(k),1,D(k))];
end
aav=[aav repmat(1/2,1,D(k))];
end
if dfw2(k)<Inf
nuv=[nuv dfw2(k)];
aav=[aav -D(k)/2];
end
end
for i=1:(numrv-1)
nu=nuv(i);
aa=aav(i);
yy=y/aa+log(nu);
% Density of log((chi^2_nu/nu)^aa):
f(:,i+1)=exp(nu/2*yy-exp(yy)/2-(nu/2)*log(2)-gammaln(nu/2))/abs(aa);
mu(i+1)=exp(gammaln(nu/2+aa)-gammaln(nu/2)-aa*log(nu/2));
end
% Check: plot(y,f); sum(f*dy,1) should be 1
omega=2*pi*((1:ny)'-1)/ny/dy;
shift=complex(cos(-b1*omega),sin(-b1*omega))*dy;
prodfft=prod(fft(f),2).*shift.^(numrv-1);
% Density of Y=log(B^(d/2)*U^(d/2)/sqrt(det(Q))):
ff=real(ifft(prodfft));
% Check: plot(y,ff); sum(ff*dy) should be 1
mu0=prod(mu);
% Check: plot(y,ff.*exp(y)); sum(ff.*exp(y)*dy.*(y<10)) should equal mu0
alpha=p/rhoD/mu0*fwhm(1)^D(1)*fwhm(2)^D(2)/(4*log(2))^(d/2);
% Integrate the density to get the p-value for one cluster:
pS=cumsum(ff(ny:-1:1))*dy;
pS=pS(ny:-1:1);
% The number of clusters is Poisson with mean EL:
pSmax=1-exp(-pS*EL);
if p_val_extent(1) <= tlim
yval=minterp1(-pSmax,y,-p_val_extent);
% Spatial extent is alpha*exp(Y) -dy/2 correction for mid-point rule:
extent_threshold=alpha*exp(yval-dy/2);
% For a single cluster:
yval=minterp1(-pS,y,-p_val_extent);
extent_threshold_1=alpha*exp(yval-dy/2);
if length(p_val_extent)<=nprint
extent_threshold
extent_threshold_1
end
else
% p_val_extent is now treated as a spatial extent:
logpval=log(p_val_extent/alpha+(p_val_extent<=0))+dy/2;
P_val_extent=interp1(y,pSmax,logpval);
extent_threshold=P_val_extent.*(p_val_extent>0)+(p_val_extent<=0);
% For a single cluster:
P_val_extent_1=interp1(y,pS,logpval);
extent_threshold_1=P_val_extent_1.*(p_val_extent>0)+(p_val_extent<=0);
if length(p_val_extent)<=nprint
P_val_extent
P_val_extent_1
end
end
end
return
function x=gammalni(n);
i=find(n>=0);
x=Inf+n;
if ~isempty(i)
x(i)=gammaln(n(i));
end
return
function iy=minterp1(x,y,ix);
% interpolates only the monotonically increasing values of x at ix
n=length(x);
mx=x(1);
my=y(1);
xx=x(1);
for i=2:n
if x(i)>xx
xx=x(i);
mx=[mx xx];
my=[my y(i)];
end
end
iy=interp1(mx,my,ix);
return
|
github | compneuro-da/rsHRF-master | SurfStatResels.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/SurfStatResels.m | 17,594 | utf_8 | 7a46dc3835272228e7108dd7cfc676d2 | function [resels, reselspvert, edg] = SurfStatResels( slm, mask );
%Resels of surface or volume data inside a mask.
%
% Usage: [resels, reselspvert, edg] = SurfStatResels( slm [, mask] )
%
% slm.resl = e x k matrix of sum over observations of squares of
% differences of normalized residuals along each edge.
% slm.tri = t x 3 matrix of triangle indices, 1-based, t=#triangles.
% or
% slm.lat = 3D logical array, 1=in, 0=out.
% mask = 1 x v, 1=inside, 0=outside, v=#vertices,
% = ones(1,v), i.e. the whole surface, by default.
%
% resels = 1 x (D+1) vector of 0,...,D dimensional resels of the mask,
% = EC of the mask if slm.resl is not given.
% reselspvert = 1 x v vector of D-dimensional resels per mask vertex.
% edg = e x 2 matrix of edge indices, 1-based, e=#edges.
% The first version of this function (below) was much more elegant.
% There were two reasons why I had to abandon it:
% 1) for volumetric data, the edg, tri and tet matrices become huge, often
% exceeding the memory capacity - they require 62 integers per voxel, as
% opposed to 12 integers per vertex for surface data.
% 2) even if memory is not exceeded, the "unique" and "ismember" functions
% take a huge amount of time; the original version is ~7 times slower.
% To overcome 1), I had to resort to a slice-wise implementation for
% volumetric data. To cut down storage, the edg, tri and tet matrices are
% formed only for two adjacent slices in the volume. The slm.lat data is
% then copied into one slice, then the other, in an alternating fashion.
% Since the tetrahedral filling is also alternating, there is no need to
% recompute the edg, tri and tet matrices. However the ordering of the edg
% matrix is crucial - it must match the SurfStatEdg function so that
% slm.resl is synchronised. The ordering of the tri and tet matrices is not
% important.
% To avoid the "unique" function in 2), the edg and tri matrices were
% created by hand, rather than derived from the tet matrix. To avoid the
% "ismember" function, edge look-up was implemented by a sparse matrix.
% This reduces execution time to ~18%. However it will not work for large
% dimensions, since the largest index of a sparse matrix is 2^31. If this
% is exceeded, then "interp1" is used which is slower but still reduces the
% time to ~45% that of "ismember". Traingle area look-up was avoided by
% simply re-computing trangle areas from the edges.
%
% Here is the original SurfStatResels function:
%
% if isfield(surf,'tri')
% tri=sort(surf.tri,2);
% edg=unique([tri(:,[1 2]); tri(:,[1 3]); tri(:,[2 3])],'rows');
% tet=[];
% end
% if isfield(surf,'lat')
% % Fill lattice with 5 tetrahedra per cube
% [I,J,K]=size(surf.lat);
% [i,j,k]=ndgrid(1:int32(I),1:int32(J),1:int32(K));
% i=i(:);
% j=j(:);
% k=k(:);
% c1=find(rem(i+j+k,2)==0 & i<I & j<J & k<K);
% c2=find(rem(i+j+k,2)==0 & i>1 & j<J & k<K);
% clear i j k
% IJ=I*J;
% tet=[c1 c1+1 c1+1+I c1+1+IJ;
% c1 c1+I c1+1+I c1+I+IJ;
% c1 c1+1+I c1+1+IJ c1+I+IJ;
% c1 c1+IJ c1+1+IJ c1+I+IJ;
% c1+1+I c1+1+IJ c1+I+IJ c1+1+I+IJ;
% c2-1 c2 c2-1+I c2-1+IJ;
% c2 c2-1+I c2+I c2+I+IJ;
% c2 c2-1+I c2-1+IJ c2+I+IJ;
% c2 c2-1+IJ c2+IJ c2+I+IJ;
% c2-1+I c2-1+IJ c2-1+I+IJ c2+I+IJ];
% clear c1 c2
% % Find triangles and edges
% tri=unique([tet(:,[1 2 3]); tet(:,[1 2 4]); ...
% tet(:,[1 3 4]); tet(:,[2 3 4])],'rows');
% edg=unique([tri(:,[1 2]); tri(:,[1 3]); tri(:,[2 3])],'rows');
% % index by voxels in the lat
% vid=cumsum(surf.lat(:)).*surf.lat(:);
% % only inside the lat
% edg=vid(edg(all(surf.lat(edg),2),:));
% tri=vid(tri(all(surf.lat(tri),2),:));
% tet=vid(tet(all(surf.lat(tet),2),:));
% end
%
% m=sum(mask(:));
% lkc(1,1)=m;
% %% LKC of edges
% maskedg=all(mask(edg),2);
% lkc(1,2)=sum(maskedg);
% if isfield(slm,'resl')
% r1=mean(sqrt(slm.resl(maskedg,:)),2);
% lkc(2,2)=sum(r1);
% end
%
% %% LKC of triangles
% masktri=all(mask(tri),2);
% lkc(1,3)=sum(masktri);
% if isfield(slm,'resl')
% [tf,loc]=ismember(tri(masktri,[1 2]),edg,'rows'); l12=slm.resl(loc,:);
% [tf,loc]=ismember(tri(masktri,[1 3]),edg,'rows'); l13=slm.resl(loc,:);
% [tf,loc]=ismember(tri(masktri,[2 3]),edg,'rows'); l23=slm.resl(loc,:);
% a=max(4*l12.*l13-(l12+l13-l23).^2,0);
% r2=mean(sqrt(a),2)/4;
% lkc(2,3)=sum(mean(sqrt(l12)+sqrt(l13)+sqrt(l23),2))/2;
% lkc(3,3)=sum(r2);
% end
%
% if isfield(slm,'lat')
% %% LKC of tetrahedra
% masktet=all(mask(tet),2);
% trimasktri=tri(masktri,:);
% lkc(1,4)=sum(masktet);
% if isfield(slm,'resl')
% [tf,loc]=ismember(tet(masktet,[1 2 3]),trimasktri,'rows'); a4=a(loc,:);
% [tf,loc]=ismember(tet(masktet,[1 2 4]),trimasktri,'rows'); a3=a(loc,:);
% [tf,loc]=ismember(tet(masktet,[1 3 4]),trimasktri,'rows'); a2=a(loc,:);
% [tf,loc]=ismember(tet(masktet,[2 3 4]),trimasktri,'rows'); a1=a(loc,:);
%
% [tf,loc]=ismember(tet(masktet,[1 2]),edg,'rows'); l12=slm.resl(loc,:);
% [tf,loc]=ismember(tet(masktet,[1 3]),edg,'rows'); l13=slm.resl(loc,:);
% [tf,loc]=ismember(tet(masktet,[2 3]),edg,'rows'); l23=slm.resl(loc,:);
% [tf,loc]=ismember(tet(masktet,[1 4]),edg,'rows'); l14=slm.resl(loc,:);
% [tf,loc]=ismember(tet(masktet,[2 4]),edg,'rows'); l24=slm.resl(loc,:);
% [tf,loc]=ismember(tet(masktet,[3 4]),edg,'rows'); l34=slm.resl(loc,:);
%
% d12=4*l12.*l34-(l13+l24-l23-l14).^2;
% d13=4*l13.*l24-(l12+l34-l23-l14).^2;
% d14=4*l14.*l23-(l12+l34-l24-l13).^2;
%
% h=(a1<=0)|(a2<=0);
% delta12=sum(mean(sqrt(l34).*pacos((d12-a1-a2)./sqrt(a1.*a2+h)/2.*(1-h)+h),2));
% h=(a1<=0)|(a3<=0);
% delta13=sum(mean(sqrt(l24).*pacos((d13-a1-a3)./sqrt(a1.*a3+h)/2.*(1-h)+h),2));
% h=(a1<=0)|(a4<=0);
% delta14=sum(mean(sqrt(l23).*pacos((d14-a1-a4)./sqrt(a1.*a4+h)/2.*(1-h)+h),2));
% h=(a2<=0)|(a3<=0);
% delta23=sum(mean(sqrt(l14).*pacos((d14-a2-a3)./sqrt(a2.*a3+h)/2.*(1-h)+h),2));
% h=(a2<=0)|(a4<=0);
% delta24=sum(mean(sqrt(l13).*pacos((d13-a2-a4)./sqrt(a2.*a4+h)/2.*(1-h)+h),2));
% h=(a3<=0)|(a4<=0);
% delta34=sum(mean(sqrt(l12).*pacos((d12-a3-a4)./sqrt(a3.*a4+h)/2.*(1-h)+h),2));
%
% r3=mean(sqrt(max((4*a1.*a2-(a1+a2-d12).^2)./(l34+(l34<=0)).*(l34>0),0)),2)/48;
%
% lkc(2,4)=(delta12+delta13+delta14+delta23+delta24+delta34)/(2*pi);
% lkc(3,4)=sum(mean(sqrt(a1)+sqrt(a2)+sqrt(a3)+sqrt(a4),2))/8;
% lkc(4,4)=sum(r3);
% end
% end
if isfield(slm,'tri')
tri=sort(slm.tri,2);
edg=unique([tri(:,[1 2]); tri(:,[1 3]); tri(:,[2 3])],'rows');
if nargin<2
v=max(edg(:));
mask=logical(zeros(1,v));
mask(edg)=1;
else
if size(mask,1)>1
mask=mask';
end
v=size(mask,2);
end
m=sum(mask(:));
lkc(1,1)=m;
%% LKC of edges
maskedg=all(mask(edg),2);
lkc(1,2)=sum(maskedg);
if isfield(slm,'resl')
r1=mean(sqrt(slm.resl(maskedg,:)),2);
lkc(2,2)=sum(r1);
end
%% LKC of triangles
masktri=all(mask(tri),2);
lkc(1,3)=sum(masktri);
if isfield(slm,'resl')
[tf,loc]=ismember(tri(masktri,[1 2]),edg,'rows'); l12=slm.resl(loc,:);
[tf,loc]=ismember(tri(masktri,[1 3]),edg,'rows'); l13=slm.resl(loc,:);
[tf,loc]=ismember(tri(masktri,[2 3]),edg,'rows'); l23=slm.resl(loc,:);
a=max(4*l12.*l13-(l12+l13-l23).^2,0);
r2=mean(sqrt(a),2)/4;
lkc(2,3)=sum(mean(sqrt(l12)+sqrt(l13)+sqrt(l23),2))/2;
lkc(3,3)=sum(r2);
end
if nargout>=2
reselspvert=zeros(v,1);
for j=1:3
reselspvert=reselspvert+accumarray(tri(masktri,j),r2,[v 1]);
end
D=2;
reselspvert=reselspvert'/(D+1)/sqrt(4*log(2))^D;
end
end
%%
if isfield(slm,'lat')
edg=SurfStatEdg(slm);
% The lattice is filled with 5 alternating tetrahedra per cube
[I,J,K]=size(slm.lat);
IJ=I*J;
[i,j]=ndgrid(1:int32(I),1:int32(J));
i=i(:);
j=j(:);
c1=int32(find(rem(i+j,2)==0 & i<I & j<J));
c2=int32(find(rem(i+j,2)==0 & i>1 & j<J));
c11=int32(find(rem(i+j,2)==0 & i==I & j<J));
c21=int32(find(rem(i+j,2)==0 & i==I & j>1));
c12=int32(find(rem(i+j,2)==0 & i<I & j==J));
c22=int32(find(rem(i+j,2)==0 & i>1 & j==J));
d1=find(rem(i+j,2)==1 & i<I & j<J)+IJ;
d2=find(rem(i+j,2)==1 & i>1 & j<J)+IJ;
tri1=[c1 c1+1 c1+1+I; % bottom slice
c1 c1+I c1+1+I;
c2-1 c2 c2-1+I;
c2 c2-1+I c2+I];
tri2=[c1 c1+1 c1+1+IJ; % between slices
c1 c1+IJ c1+1+IJ;
c1 c1+I c1+I+IJ;
c1 c1+IJ c1+I+IJ;
c1 c1+1+I c1+1+IJ;
c1 c1+1+I c1+I+IJ;
c1 c1+1+IJ c1+I+IJ;
c1+1+I c1+1+IJ c1+I+IJ;
c2-1 c2 c2-1+IJ;
c2 c2-1+IJ c2+IJ;
c2-1 c2-1+I c2-1+IJ;
c2-1+I c2-1+IJ c2-1+I+IJ;
c2 c2-1+I c2+I+IJ;
c2 c2-1+IJ c2+I+IJ;
c2 c2-1+I c2-1+IJ;
c2-1+I c2-1+IJ c2+I+IJ;
c11 c11+I c11+I+IJ;
c11 c11+IJ c11+I+IJ;
c21-I c21 c21-I+IJ;
c21 c21-I+IJ c21+IJ;
c12 c12+1 c12+1+IJ;
c12 c12+IJ c12+1+IJ;
c22-1 c22 c22-1+IJ;
c22 c22-1+IJ c22+IJ];
tri3=[d1 d1+1 d1+1+I; % top slice
d1 d1+I d1+1+I;
d2-1 d2 d2-1+I;
d2 d2-1+I d2+I];
tet1=[c1 c1+1 c1+1+I c1+1+IJ; % between slices
c1 c1+I c1+1+I c1+I+IJ;
c1 c1+1+I c1+1+IJ c1+I+IJ;
c1 c1+IJ c1+1+IJ c1+I+IJ;
c1+1+I c1+1+IJ c1+I+IJ c1+1+I+IJ;
c2-1 c2 c2-1+I c2-1+IJ;
c2 c2-1+I c2+I c2+I+IJ;
c2 c2-1+I c2-1+IJ c2+I+IJ;
c2 c2-1+IJ c2+IJ c2+I+IJ;
c2-1+I c2-1+IJ c2-1+I+IJ c2+I+IJ];
v=sum(slm.lat(:));
if nargin<2
mask=logical(ones(1,v));
else
if size(mask,1)>1
mask=mask';
end
end
if nargout>=2
reselspvert=zeros(v,1);
end
vs=cumsum(squeeze(sum(sum(slm.lat))));
vs=int32([0; vs; vs(K)]);
es=0;
lat=logical(zeros(I,J,2));
lat(:,:,1)=slm.lat(:,:,1);
lkc=zeros(4);
fprintf(1,'%s',[num2str(K) ' slices to resel, % remaining: 100 ']);
n10=floor(K/10);
for k=1:K
if rem(k,n10)==0
fprintf(1,'%s',[num2str(round(100*(1-k/K))) ' ']);
end
f=rem(k,2);
if k<K
lat(:,:,f+1)=slm.lat(:,:,k+1);
else
lat(:,:,f+1)=zeros(I,J);
end
vid=int32(cumsum(lat(:)).*lat(:))';
if f
edg1=edg(edg(:,1)>vs(k) & edg(:,1)<=vs(k+1),:)-vs(k);
edg2=edg(edg(:,1)>vs(k) & edg(:,2)<=vs(k+2),:)-vs(k);
tri=[vid(tri1(all(lat(tri1),2),:)); vid(tri2(all(lat(tri2),2),:))];
mask1=mask((vs(k)+1):vs(k+2));
else
edg1=[edg(edg(:,1)>vs(k) & edg(:,2)<=vs(k+1),:)-vs(k)+vs(k+2)-vs(k+1);
edg(edg(:,1)<=vs(k+1) & edg(:,2)>vs(k+1),2)-vs(k+1) ...
edg(edg(:,1)<=vs(k+1) & edg(:,2)>vs(k+1),1)-vs(k)+vs(k+2)-vs(k+1)];
edg2=[edg1; edg(edg(:,1)>vs(k+1) & edg(:,2)<=vs(k+2),:)-vs(k+1)];
tri=[vid(tri3(all(lat(tri3),2),:)); vid(tri2(all(lat(tri2),2),:))];
mask1=[mask((vs(k+1)+1):vs(k+2)) mask((vs(k)+1):vs(k+1))];
end
tet=vid(tet1(all(lat(tet1),2),:));
m1=max(double(edg2(:,1)));
ue=double(edg2(:,1))+m1*(double(edg2(:,2))-1);
e=size(edg2,1);
ae=1:e;
if e<2^31
sparsedg=sparse(ue,1,ae);
end
%%
lkc1=zeros(4);
lkc1(1,1)=sum(mask((vs(k)+1):vs(k+1)));
%% LKC of edges
maskedg=all(mask1(edg1),2);
lkc1(1,2)=sum(maskedg);
if isfield(slm,'resl')
r1=mean(sqrt(slm.resl(find(maskedg)+es,:)),2);
lkc1(2,2)=sum(r1);
end
%% LKC of triangles
masktri=all(mask1(tri),2);
lkc1(1,3)=sum(masktri);
if isfield(slm,'resl')
if e<2^31
l12=slm.resl(sparsedg(tri(masktri,1)+m1*(tri(masktri,2)-1),1)+es,:);
l13=slm.resl(sparsedg(tri(masktri,1)+m1*(tri(masktri,3)-1),1)+es,:);
l23=slm.resl(sparsedg(tri(masktri,2)+m1*(tri(masktri,3)-1),1)+es,:);
else
l12=slm.resl(interp1(ue,ae,tri(masktri,1)+m1*(tri(masktri,2)-1),'nearest')+es,:);
l13=slm.resl(interp1(ue,ae,tri(masktri,1)+m1*(tri(masktri,3)-1),'nearest')+es,:);
l23=slm.resl(interp1(ue,ae,tri(masktri,2)+m1*(tri(masktri,3)-1),'nearest')+es,:);
end
a=max(4*l12.*l13-(l12+l13-l23).^2,0);
r2=mean(sqrt(a),2)/4;
lkc1(2,3)=sum(mean(sqrt(l12)+sqrt(l13)+sqrt(l23),2))/2;
lkc1(3,3)=sum(r2);
if nargout>=2 & K==1
for j=1:3
if f
v1=tri(masktri,j)+vs(k);
else
v1=tri(masktri,j)+vs(k+1);
v1=v1-int32(v1>vs(k+2))*(vs(k+2)-vs(k));
end
reselspvert=reselspvert+accumarray(v1,r2,[v 1]);
end
end
end
%% LKC of tetrahedra
masktet=all(mask1(tet),2);
lkc1(1,4)=sum(masktet);
if isfield(slm,'resl') & k<K
if e<2^31
l12=slm.resl(sparsedg(tet(masktet,1)+m1*(tet(masktet,2)-1),1)+es,:);
l13=slm.resl(sparsedg(tet(masktet,1)+m1*(tet(masktet,3)-1),1)+es,:);
l23=slm.resl(sparsedg(tet(masktet,2)+m1*(tet(masktet,3)-1),1)+es,:);
l14=slm.resl(sparsedg(tet(masktet,1)+m1*(tet(masktet,4)-1),1)+es,:);
l24=slm.resl(sparsedg(tet(masktet,2)+m1*(tet(masktet,4)-1),1)+es,:);
l34=slm.resl(sparsedg(tet(masktet,3)+m1*(tet(masktet,4)-1),1)+es,:);
else
l12=slm.resl(interp1(ue,ae,tet(masktet,1)+m1*(tet(masktet,2)-1),'nearest')+es,:);
l13=slm.resl(interp1(ue,ae,tet(masktet,1)+m1*(tet(masktet,3)-1),'nearest')+es,:);
l23=slm.resl(interp1(ue,ae,tet(masktet,2)+m1*(tet(masktet,3)-1),'nearest')+es,:);
l14=slm.resl(interp1(ue,ae,tet(masktet,1)+m1*(tet(masktet,4)-1),'nearest')+es,:);
l24=slm.resl(interp1(ue,ae,tet(masktet,2)+m1*(tet(masktet,4)-1),'nearest')+es,:);
l34=slm.resl(interp1(ue,ae,tet(masktet,3)+m1*(tet(masktet,4)-1),'nearest')+es,:);
end
a4=max(4*l12.*l13-(l12+l13-l23).^2,0);
a3=max(4*l12.*l14-(l12+l14-l24).^2,0);
a2=max(4*l13.*l14-(l13+l14-l34).^2,0);
a1=max(4*l23.*l24-(l23+l24-l34).^2,0);
d12=4*l12.*l34-(l13+l24-l23-l14).^2;
d13=4*l13.*l24-(l12+l34-l23-l14).^2;
d14=4*l14.*l23-(l12+l34-l24-l13).^2;
h=(a1<=0)|(a2<=0);
delta12=sum(mean(sqrt(l34).*pacos((d12-a1-a2)./sqrt(a1.*a2+h)/2.*(1-h)+h),2));
h=(a1<=0)|(a3<=0);
delta13=sum(mean(sqrt(l24).*pacos((d13-a1-a3)./sqrt(a1.*a3+h)/2.*(1-h)+h),2));
h=(a1<=0)|(a4<=0);
delta14=sum(mean(sqrt(l23).*pacos((d14-a1-a4)./sqrt(a1.*a4+h)/2.*(1-h)+h),2));
h=(a2<=0)|(a3<=0);
delta23=sum(mean(sqrt(l14).*pacos((d14-a2-a3)./sqrt(a2.*a3+h)/2.*(1-h)+h),2));
h=(a2<=0)|(a4<=0);
delta24=sum(mean(sqrt(l13).*pacos((d13-a2-a4)./sqrt(a2.*a4+h)/2.*(1-h)+h),2));
h=(a3<=0)|(a4<=0);
delta34=sum(mean(sqrt(l12).*pacos((d12-a3-a4)./sqrt(a3.*a4+h)/2.*(1-h)+h),2));
r3=mean(sqrt(max((4*a1.*a2-(a1+a2-d12).^2)./(l34+(l34<=0)).*(l34>0),0)),2)/48;
lkc1(2,4)=(delta12+delta13+delta14+delta23+delta24+delta34)/(2*pi);
lkc1(3,4)=sum(mean(sqrt(a1)+sqrt(a2)+sqrt(a3)+sqrt(a4),2))/8;
lkc1(4,4)=sum(r3);
if nargout>=2
for j=1:4
if f
v1=tet(masktet,j)+vs(k);
else
v1=tet(masktet,j)+vs(k+1);
v1=v1-int32(v1>vs(k+2))*(vs(k+2)-vs(k));
end
reselspvert=reselspvert+accumarray(v1,r3,[v 1]);
end
end
end
lkc=lkc+lkc1;
es=es+size(edg1,1);
end
if nargout>=2
D=2+(K>1);
reselspvert=reselspvert'/(D+1)/sqrt(4*log(2))^D;
end
fprintf(1,'%s\n','Done');
end
%% resels
D=size(lkc,1)-1;
D2=size(lkc,2)-1;
tpltz=toeplitz((-1).^(0:D),(-1).^(0:D2));
lkcs=sum(tpltz.*lkc,2)';
lkcs=lkcs(1:max(find(abs(lkcs))));
resels=lkcs./sqrt(4*log(2)).^(0:D);
return
end
%%
function y=pacos(x)
y=acos(min(abs(x),1).*sign(x));
return
end
|
github | compneuro-da/rsHRF-master | RVR_W_Permutation.m | .m | rsHRF-master/demo_codes/rsHRF_demo_UCLA/RVR/RVR_W_Permutation.m | 1,696 | utf_8 | 527f7c4ad4cfdbe7ec572b365bb43319 |
function RVR_W_Permutation(Data_Path, Scores, Perm_times_Range, RandIndex_Folder, Covariates, Pre_Method, ResultantFolder, Queue)
TaskQuantity = 100;
JobsPerTask = fix(length(Perm_times_Range) / TaskQuantity);
JobsRemain = mod(length(Perm_times_Range), TaskQuantity * JobsPerTask);
mkdir([ResultantFolder filesep 'rand_perm']);
for i = 1:100
i
ID = Perm_times_Range([(i - 1) * JobsPerTask + 1 : i * JobsPerTask]);
if i == 100 & JobsRemain
ID = [ID Perm_times_Range(length(Perm_times_Range) - JobsRemain + 1 : end)];
end
for j = 1:length(ID)
% Rand_Index = randperm(length(Scores));
load([RandIndex_Folder filesep 'RandID_' num2str(ID(j)) '.mat']);
Rand_Index = RandID;
Rand_Score{j} = Scores(Rand_Index);
end
save([ResultantFolder filesep 'rand_perm' filesep 'rand_perm_' num2str(i) '.mat'], 'Rand_Score');
Job_Name = ['perm_W_' num2str(i)];
pipeline.(Job_Name).command = 'W_Calculate_RVR_SGE(opt.para1, opt.para2, opt.para3, opt.para4, opt.para5, opt.para6)';
pipeline.(Job_Name).opt.para1 = Data_Path;
pipeline.(Job_Name).opt.para2 = Rand_Score;
pipeline.(Job_Name).opt.para3 = ID;
pipeline.(Job_Name).opt.para4 = Covariates;
pipeline.(Job_Name).opt.para5 = Pre_Method;
pipeline.(Job_Name).opt.para6 = ResultantFolder;
clear Rand_Score;
end
Pipeline_opt.mode = 'qsub';
Pipeline_opt.qsub_options = Queue;
Pipeline_opt.mode_pipeline_manager = 'batch';
Pipeline_opt.max_queued = 200;
Pipeline_opt.flag_verbose = 1;
Pipeline_opt.flag_pause = 0;
Pipeline_opt.flag_update = 1;
Pipeline_opt.path_logs = [ResultantFolder filesep 'logs'];
psom_run_pipeline(pipeline,Pipeline_opt);
|
github | lhmRyan/deep-supervised-hashing-DSH-master | classification_demo.m | .m | deep-supervised-hashing-DSH-master/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 | kpzhang93/MTCNN_face_detection_alignment-master | test.m | .m | MTCNN_face_detection_alignment-master/code/codes/camera_demo/test.m | 8,824 | utf_8 | 484a3e8719f2102fd5aa6c841209b5ed | function varargout = test(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @test_OpeningFcn, ...
'gui_OutputFcn', @test_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
function test_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);
function varargout = test_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function pushbutton1_Callback(hObject, eventdata, handles)
threshold=[0.6 0.7 str2num(get(findobj('tag','edit4'),'string'))]
factor=0.709;
minsize=str2num(get(findobj('tag','edit6'),'string'));
stop=0.03;
mypath=get(findobj('tag','edit1'),'string')
addpath(mypath);
caffe.reset_all();
caffe.set_mode_cpu();
mypath=get(findobj('tag','edit3'),'string')
addpath(mypath);
cameraid=get(findobj('tag','edit2'),'string')
camera=imaqhwinfo;
camera=camera.InstalledAdaptors{str2num(cameraid)}
vid1= videoinput(camera,1,get(findobj('tag','edit5'),'string'));
warning off all
usbVidRes1=get(vid1,'videoResolution');
nBands1=get(vid1,'NumberOfBands');
hImage1=imshow(zeros(usbVidRes1(2),usbVidRes1(1),nBands1));
preview(vid1,hImage1);
prototxt_dir = './model/det1.prototxt';
model_dir = './model/det1.caffemodel';
PNet=caffe.Net(prototxt_dir,model_dir,'test');
prototxt_dir = './model/det2.prototxt';
model_dir = './model/det2.caffemodel';
RNet=caffe.Net(prototxt_dir,model_dir,'test');
prototxt_dir = './model/det3.prototxt';
model_dir = './model/det3.caffemodel';
ONet=caffe.Net(prototxt_dir,model_dir,'test');
prototxt_dir = './model/det4.prototxt';
model_dir = './model/det4.caffemodel';
LNet=caffe.Net(prototxt_dir,model_dir,'test');
rec=rectangle('Position',[1 1 1 1],'Edgecolor','r');
while (1)
img=getsnapshot(vid1);
[total_boxes point]=detect_face(img,minsize,PNet,RNet,ONet,threshold,false,factor);
try
delete(rec);
catch
end
numbox=size(total_boxes,1);
for j=1:numbox;
rec(j)=rectangle('Position',[total_boxes(j,1:2) total_boxes(j,3:4)-total_boxes(j,1:2)],'Edgecolor','g','LineWidth',3);
rec(6*numbox+j)=rectangle('Position',[point(1,j),point(6,j),5,5],'Curvature',[1,1],'FaceColor','g','LineWidth',3);
rec(12*numbox+j)=rectangle('Position',[point(2,j),point(7,j),5,5],'Curvature',[1,1],'FaceColor','g','LineWidth',3);
rec(18*numbox+j)=rectangle('Position',[point(3,j),point(8,j),5,5],'Curvature',[1,1],'FaceColor','g','LineWidth',3);
rec(24*numbox+j)=rectangle('Position',[point(4,j),point(9,j),5,5],'Curvature',[1,1],'FaceColor','g','LineWidth',3);
rec(30*numbox+j)=rectangle('Position',[point(5,j),point(10,j),5,5],'Curvature',[1,1],'FaceColor','g','LineWidth',3);
end
pause(stop)
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit2_Callback(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit2 as text
% str2double(get(hObject,'String')) returns contents of edit2 as a double
% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit3_Callback(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit3 as text
% str2double(get(hObject,'String')) returns contents of edit3 as a double
% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit4_Callback(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit4 as text
% str2double(get(hObject,'String')) returns contents of edit4 as a double
% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit5_Callback(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit5 as text
% str2double(get(hObject,'String')) returns contents of edit5 as a double
% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit6_Callback(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit6 as text
% str2double(get(hObject,'String')) returns contents of edit6 as a double
% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github | dailymoyuan/Compressed-Air-Energy-Storage-for-wind-energy-storage-master | air_tank.m | .m | Compressed-Air-Energy-Storage-for-wind-energy-storage-master/air_tank.m | 713 | utf_8 | e066bd0364ff84d95ed16714340c9d7e | %---------------air storage tank-----------------%
function [Cp_nrm,Turbine_trq] = fcn(v_wind,wp)
Cpmax=0.4825;
rated_trb=36;
Pw_rated=600;
w=wp*pi/30;
air_rho=1.225;
r_blade=30;
swept_area=pi*r_blade^2;
lambda=(r_blade*w)/v_wind;
beta=0;
c1=0.51760*0.15;
c2=116*1.512;
c3=0.4;
c4=5;
c5=21*1.36;
c6=0.0068;
Cp=c1*(c2.*(1./(lambda+0.08*beta)-0.035./(beta.^3+1))-c3*beta-c4)...
.*exp(-c5.*(1*0.47./(lambda+0.08*beta)-0.035./(beta.^3+1)))+c6*lambda;
Cp_nrm=Cp*100/Cpmax;
Power=0.5*Cp*air_rho*swept_area*v_wind^3;
Turbine_trq=1e-3*0.5*Cp*air_rho*swept_area*v_wind^3/w;
loss_per_stg=0.01;
gr_stg=2;
loss_gr=(loss_per_stg*gr_stg*wp/rated_trb)*Pw_rated;
if w==0
w=1;
end
|
github | dailymoyuan/Compressed-Air-Energy-Storage-for-wind-energy-storage-master | expension_stage.m | .m | Compressed-Air-Energy-Storage-for-wind-energy-storage-master/expension_stage.m | 1,022 | utf_8 | 989a4e95cfda9e8f92cdc3e960ee60fa | %-----------expansion stage--------------%
function [Pout_caes,Tout_LP, Tin_LP,Tout_HP,pout_HP,pout_LP, P_HP, P_LP] = fcn(P_need_left, dm, pin_HP, Tin_HP)
B1 = 3; % compression ratio for high turbines
B2 = 15; % compression ratio for low turbines
n_t = 0.85; % efficiency of both turbines
nHX = 0.7; % efficiency of heat exchanger HX
Thx_f = 283; % temperature of HX fluid [K]
R = 0.287; % air cte [KJ/Kg.K] --> Pout_caes is in [KW]
% initialize value
Pout_caes=0;
Tout_LP=0;
Tout_HP=0;
Tin_LP=0;
pout_HP=0;
pout_LP=0;
P_HP = 0;
P_LP = 0;
if P_need_left > 0
% pressure of turbines
pout_HP = pin_HP/B1;
pin_LP = pout_HP;
pout_LP = pin_LP/B2;
Tout_HP = Tin_HP/(B1^0.2857);
Tout_hx = Tout_HP+nHX*(Thx_f-Tout_HP);
Tin_LP = Tout_hx;
Tout_LP = Tin_LP/(B2^0.2857);
P_HP = n_t*abs(dm)*R*3.5*(Tin_HP - Tout_HP);
P_LP = n_t*abs(dm)*R*3.5*(Tin_LP - Tout_LP);
Pout_caes = P_need_left;
end
end
|
github | dailymoyuan/Compressed-Air-Energy-Storage-for-wind-energy-storage-master | charge_mode_supervisor_control_logic.m | .m | Compressed-Air-Energy-Storage-for-wind-energy-storage-master/charge_mode_supervisor_control_logic.m | 1,933 | utf_8 | 6f936eba5c79806e40c79bfeff7e47e8 | %--------battery charging/discharging mode transtion login definition with time step count-----------\\
function [P_excess,P_need,P_real,P_without_supplu] = fcn(P_auto,real_Tload,auto_Tload,wm,P_aero)
P_real = real_Tload * (wm *pi/30);
if P_auto > P_real
P_without_supplu = 0;
else
P_without_supplu = P_auto;
end
act_t= 20; % Time constant to determine if excess power is available or power needed to maintain minimum power delivary
time_stp=0.001; % simulation time step
persistent counter1 counter2
if isempty(counter1)
counter1=0; % initialize couter1
end
if isempty(counter2)
counter2=0; % initialize couter2
end
%--------charging number count definition-----------\\
if P_auto >= P_real
P_need = 0;
counter1=counter1+1;
if counter1 > act_t/time_stp % number of counter1
P_excess = P_auto - P_real;
else % counter1<act_t/time_stp
P_excess = 0;
end
else
P_excess=0;
counter1=0;
end
%-------discharging number count definition-----------\\
if P_auto <= P_real
P_excess=0;
counter2=counter2+1;
if counter2>act_t/time_stp % number of counter1
P_need = P_real - P_auto;
else % counter2 < act_t/time_stp
P_need = 0;
end
else
P_need=0;
counter2=0;
end
end
|
github | dailymoyuan/Compressed-Air-Energy-Storage-for-wind-energy-storage-master | compression_stage.m | .m | Compressed-Air-Energy-Storage-for-wind-energy-storage-master/compression_stage.m | 560 | utf_8 | 22222521bd8765bab9448af0f63d4045 | %------setting Pelec as the power input from P_exceed of wind farm-----%
%------used to compress air and store it in the air tank---------------%
function dm_c = fcn(Tout, P_ex, p)
dm_c = 0;
n_c = 0.877; %efficiency of each compressor
Tin = 293; %environment temperature [k]
R = 0.287; %air-gas constant kj/kg.k
Pideal = P_ex/(n_c);
p_max = 40; % maximum pressure in air tank
if P_ex > 0
dm_c = Pideal/(R*3.5*(Tout-Tin));
if p >= p_max
dm_c = 0;
end
end
end
|
github | dailymoyuan/Compressed-Air-Energy-Storage-for-wind-energy-storage-master | storage_size_def.m | .m | Compressed-Air-Energy-Storage-for-wind-energy-storage-master/storage_size_def.m | 400 | utf_8 | 5d699f45672b6e9e824e1d3b655d4972 | %turbine output is messured in Kwh - energy
% n is the efficiency of the turbine
% a is the number of turbines used
% pm is the maximum pressure of the tank in [Pa]
function [sc,m,V] = fcn(turbine_out,Tin_ct,Tout_ct,Ts)
n = 0.85;
a = 2;
pm = 4e+6;
cp = 1.005;
R = 287.06;
sc = turbine_out/(n^a);
m = sc*3600/(cp*(Tout_ct-Tin_ct));
V = m*R*Ts/pm;
|
github | kunzhan/Pulse-coupled_neural_networks_PCNN-master | GrayStretch.m | .m | Pulse-coupled_neural_networks_PCNN-master/functions/GrayStretch.m | 1,449 | utf_8 | 59810661bc80ef21e7702aeaf24fe2b3 | function GS = GrayStretch(I,Per)
% The code was written by Jicai Teng, Jinhui Shi, Kun Zhan
% $Revision: 1.0.0.0 $ $Date: 2014/12/06 $ 17:58:47 $
% Reference:
% [1] K Zhan, J Shi, Q Li, J Teng, M Wang,
% "Image segmentation using fast linking SCM,"
% in Proc. of IJCNN, IEEE, vol. 25, pp. 2093-2100, 2015.
% [2] K Zhan, J Teng, J Shi, Q Li, M Wang,
% "Feature-linking model for image enhancement,"
% Neural Computation, 28(5), 1072-1100, 2016.
[m,M] = FindingMm(I,Per);
GS = uint8((double(I)-m)./(M-m)*255);
end
function [minI,MaxI] = FindingMm(I,Per)
h = imhist(I);
All = sum(h);
ph = h ./ All;
mth_ceiling = BoundFinding(ph,Per);
Mph=fliplr(ph')';
Mth_floor = BoundFinding(Mph,Per);
Mth_floor = 256 - Mth_floor + 1;
ConstraintJudge = @(x,y) sum(h(x:y))/All >= Per;
Difference = zeros(256,256) + inf;
for m = mth_ceiling:-1:1
for M = Mth_floor:256
if (h(m) > 0 )&&(h(M) > 0)
if ConstraintJudge(m,M)
Difference(m,M) = M - m;
end
end
end
end
minD = min(Difference(:));
[m, M] = find(Difference==minD);
minI = m(1) - 1;
MaxI = M(1) - 1;
end
function m_ceiling = BoundFinding(ph,Per)
cumP = cumsum(ph);
n = 1;
residualP = 1-Per;
while cumP(n) < residualP
n = n + 1;
end
m_ceiling = n;
end |
github | herenvarno/caffe-master | classification_demo.m | .m | caffe-master/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 | zongwave/IPASS-master | BM3DDEB.m | .m | IPASS-master/BM3D/BM3D/BM3DDEB.m | 17,170 | utf_8 | 1ca4e4613bf8a4a204335f69e5b9a1ca | function [ISNR, y_hat_RWI] = BM3DDEB(experiment_number, test_image_name)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2008-2014 Tampere University of Technology. All rights reserved.
% This work should only be used for nonprofit purposes.
%
% AUTHORS:
% Kostadin Dabov
% Alessandro Foi email: alessandro.foi _at_ tut.fi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This function implements the image deblurring method proposed in:
%
% [1] K. Dabov, A. Foi, V. Katkovnik, and K. Egiazarian, "Image
% restoration by sparse 3D transform-domain collaborative filtering,"
% Proc SPIE Electronic Imaging, January 2008.
%
% FUNCTION INTERFACE:
%
% [PSNR, y_hat_RWI] = BM3DDEB(experiment_number, test_image_name)
%
% INPUT:
% 1) experiment_number: 1 -> PSF 1, sigma^2 = 2
% 2 -> PSF 1, sigma^2 = 8
% 3 -> PSF 2, sigma^2 = 0.308
% 4 -> PSF 3, sigma^2 = 49
% 5 -> PSF 4, sigma^2 = 4
% 6 -> PSF 5, sigma^2 = 64
%
% 2) test_image_name: a valid filename of a grayscale test image
%
% OUTPUT:
% 1) ISNR: the output improvement in SNR, dB
% 2) y_hat_RWI: the restored image
%
% ! The function can work without any of the input arguments,
% in which case, the internal default ones are used !
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Fixed regularization parameters (obtained empirically after a rough optimization)
Regularization_alpha_RI = 4e-4;
Regularization_alpha_RWI = 5e-3;
%%%% Experiment number (see below for details, e.g. how the blur is generated, etc.)
if (exist('experiment_number') ~= 1)
experiment_number = 3; % 1 -- 6
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Select a single image filename (might contain path)
%%%%
if (exist('test_image_name') ~= 1)
test_image_name = [
% 'Lena512.png'
'Cameraman256.png'
% 'barbara.png'
% 'house.png'
];
end
%%%% Select 2D transforms ('dct', 'dst', 'hadamard', or anything that is listed by 'help wfilters'):
transform_2D_HT_name = 'dst'; %% 2D transform (of size N1 x N1) used in Step 1
transform_2D_Wiener_name = 'dct'; %% 2D transform (of size N1_wiener x N1_wiener) used in Step 2
transform_3rd_dimage_name = 'haar'; %% 1D tranform used in the 3-rd dim, the same for both steps
%%%% Step 1 (BM3D with collaborative hard-thresholding) parameters:
N1 = 8; %% N1 x N1 is the block size
Nstep = 3; %% sliding step to process every next refernece block
N2 = 16; %% maximum number of similar blocks (maximum size of the 3rd dimensiona of a 3D array)
Ns = 39; %% length of the side of the search neighborhood for full-search block-matching (BM)
tau_match = 6000;%% threshold for the block distance (d-distance)
lambda_thr2D = 0; %% threshold for the coarse initial denoising used in the d-distance measure
lambda_thr3D = 2.9; %% threshold for the hard-thresholding
beta = 0; %% the beta parameter of the 2D Kaiser window used in the reconstruction
%%%% Step 2 (BM3D with collaborative Wiener filtering) parameters:
N1_wiener = 8;
Nstep_wiener = 2;
N2_wiener = 16;
Ns_wiener = 39;
tau_match_wiener = 800;
beta_wiener = 0;
%%%% Specify whether to print results and display images
print_to_screen = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Note: touch below this point only if you know what you are doing!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Make parameters compatible with the interface of the mex-functions
%%%%
[Tfor, Tinv] = getTransfMatrix(N1, transform_2D_HT_name, 0); %% get (normalized) forward and inverse transform matrices
[TforW, TinvW] = getTransfMatrix(N1_wiener, transform_2D_Wiener_name, 0); %% get (normalized) forward and inverse transform matrices
if (strcmp(transform_3rd_dimage_name, 'haar') == 1),
%%% Fast internal transform is used, no need to generate transform
%%% matrices.
hadper_trans_single_den = {};
inverse_hadper_trans_single_den = {};
else
%%% Create transform matrices. The transforms are later applied by
%%% vector-matrix multiplications
for hpow = 0:ceil(log2(max(N2,N2_wiener))),
h = 2^hpow;
[Tfor3rd, Tinv3rd] = getTransfMatrix(h, transform_3rd_dimage_name, 0);
hadper_trans_single_den{h} = single(Tfor3rd);
inverse_hadper_trans_single_den{h} = single(Tinv3rd');
end
end
if beta == 0 & beta_wiener == 0
Wwin2D = ones(N1,N1);
Wwin2D_wiener = ones(N1_wiener,N1_wiener);
else
Wwin2D = kaiser(N1, beta) * kaiser(N1, beta)'; % Kaiser window used in the hard-thresholding part
Wwin2D_wiener = kaiser(N1_wiener, beta_wiener) * kaiser(N1_wiener, beta_wiener)'; % Kaiser window used in the Wiener filtering part
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Read an image and generate a blurred and noisy image
%%%%
y = im2double(imread(test_image_name));
if experiment_number==1
sigma=sqrt(2)/255;
for x1=-7:7; for x2=-7:7; v(x1+8,x2+8)=1/(x1^2+x2^2+1); end, end; v=v./sum(v(:));
end
if experiment_number==2
sigma=sqrt(8)/255;
s1=0; for a1=-7:7; s1=s1+1; s2=0; for a2=-7:7; s2=s2+1; v(s1,s2)=1/(a1^2+a2^2+1); end, end; v=v./sum(v(:));
end
if experiment_number==3
BSNR=40; sigma=-1; % if "sigma=-1", then the value of sigma depends on the BSNR
v=ones(9); v=v./sum(v(:));
end
if experiment_number==4
sigma=7/255;
v=[1 4 6 4 1]'*[1 4 6 4 1]; v=v./sum(v(:)); % PSF
end
if experiment_number==5
sigma=2/255;
v=fspecial('gaussian', 25, 1.6);
end
if experiment_number==6
sigma=8/255;
v=fspecial('gaussian', 25, .4);
end
[Xv, Xh] = size(y);
[ghy,ghx] = size(v);
big_v = zeros(Xv,Xh); big_v(1:ghy,1:ghx)=v; big_v=circshift(big_v,-round([(ghy-1)/2 (ghx-1)/2])); % pad PSF with zeros to whole image domain, and center it
V = fft2(big_v); % frequency response of the PSF
y_blur = imfilter(y, v(end:-1:1,end:-1:1), 'circular'); % performs blurring (by circular convolution)
randn('seed',0); %%% fix seed for the random number generator
if sigma == -1; %% check whether to use BSNR in order to define value of sigma
sigma=sqrt(norm(y_blur(:)-mean(y_blur(:)),2)^2 /(Xh*Xv*10^(BSNR/10))); % compute sigma from the desired BSNR
end
%%%% Create a blurred and noisy observation
z = y_blur + sigma*randn(Xv,Xh);
tic;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 1: Final estimate by Regularized Inversion (RI) followed by
%%%% BM3D with collaborative hard-thresholding
%%%%
%%%% Step 1.1. Regularized Inversion
RI= conj(V)./( (abs(V).^2) + Regularization_alpha_RI * Xv*Xh*sigma^2); % Transfer Matrix for RI %% Standard Tikhonov Regularization
zRI=real(ifft2( fft2(z).* RI )); % Regularized Inverse Estimate (RI OBSERVATION)
stdRI = zeros(N1, N1);
for ii = 1:N1,
for jj = 1:N1,
UnitMatrix = zeros(N1,N1); UnitMatrix(ii,jj)=1;
BasisElementPadded = zeros(Xv, Xh); BasisElementPadded(1:N1,1:N1) = Tinv*UnitMatrix*Tinv';
TransfBasisElementPadded = fft2(BasisElementPadded);
stdRI(ii,jj) = sqrt( (1/(Xv*Xh)) * sum(sum(abs(TransfBasisElementPadded.*RI).^2)) )*sigma;
end,
end
%%%% Step 1.2. Colored noise suppression by BM3D with collaborative hard-
%%%% thresholding
y_hat_RI = bm3d_thr_colored_noise(zRI, hadper_trans_single_den, Nstep, N1, N2, lambda_thr2D,...
lambda_thr3D, tau_match*N1*N1/(255*255), (Ns-1)/2, sigma, 0, single(Tfor), single(Tinv)',...
inverse_hadper_trans_single_den, single(stdRI'), Wwin2D, 0, 1 );
PSNR_INITIAL_ESTIMATE = 10*log10(1/mean((y(:)-y_hat_RI(:)).^2));
ISNR_INITIAL_ESTIMATE = PSNR_INITIAL_ESTIMATE - 10*log10(1/mean((y(:)-z(:)).^2));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 2: Final estimate by Regularized Wiener Inversion (RWI) followed
%%%% by BM3D with collaborative Wiener filtering
%%%%
%%%% Step 2.1. Regularized Wiener Inversion
Wiener_Pilot = abs(fft2(double(y_hat_RI))); %%% Wiener reference estimate
RWI = conj(V).*Wiener_Pilot.^2./(Wiener_Pilot.^2.*(abs(V).^2) + Regularization_alpha_RWI*Xv*Xh*sigma^2); % Transfer Matrix for RWI (uses standard regularization 'a-la-Tikhonov')
zRWI = real(ifft2(fft2(z).*RWI)); % RWI OBSERVATION
stdRWI = zeros(N1_wiener, N1_wiener);
for ii = 1:N1_wiener,
for jj = 1:N1_wiener,
UnitMatrix = zeros(N1_wiener,N1_wiener); UnitMatrix(ii,jj)=1;
BasisElementPadded = zeros(Xv, Xh); BasisElementPadded(1:N1_wiener,1:N1_wiener) = TinvW*UnitMatrix*TinvW';
TransfBasisElementPadded = fft2(BasisElementPadded);
stdRWI(ii,jj) = sqrt( (1/(Xv*Xh)) * sum(sum(abs(TransfBasisElementPadded.*RWI).^2)) )*sigma;
end,
end
%%%% Step 2.2. Colored noise suppression by BM3D with collaborative Wiener
%%%% filtering
y_hat_RWI = bm3d_wiener_colored_noise(zRWI, y_hat_RI, hadper_trans_single_den, Nstep_wiener, N1_wiener, N2_wiener, ...
0, tau_match_wiener*N1_wiener*N1_wiener/(255*255), (Ns_wiener-1)/2, 0, single(stdRWI'), single(TforW), single(TinvW)',...
inverse_hadper_trans_single_den, Wwin2D_wiener, 0, 1, single(ones(N1_wiener)) );
elapsed_time = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Calculate the final estimate's PSNR and ISNR, print them, and show the
%%%% restored image
%%%%
PSNR = 10*log10(1/mean((y(:)-y_hat_RWI(:)).^2));
ISNR = PSNR - 10*log10(1/mean((y(:)-z(:)).^2));
if print_to_screen == 1
fprintf('Image: %s, Exp %d, Time: %.1f sec, PSNR-RI: %.2f dB, PSNR-RWI: %.2f, ISNR-RWI: %.2f dB\n', ...
test_image_name, experiment_number, elapsed_time, PSNR_INITIAL_ESTIMATE, PSNR, ISNR);
figure,imshow(z);
figure,imshow(double(y_hat_RWI));
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some auxiliary functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% Create forward and inverse transform matrices, which allow for perfect
% reconstruction. The forward transform matrix is normalized so that the
% l2-norm of each basis element is 1.
%
% [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% INPUTS:
%
% N --> Size of the transform (for wavelets, must be 2^K)
%
% transform_type --> 'dct', 'dst', 'hadamard', or anything that is
% listed by 'help wfilters' (bi-orthogonal wavelets)
% 'DCrand' -- an orthonormal transform with a DC and all
% the other basis elements of random nature
%
% dec_levels --> If a wavelet transform is generated, this is the
% desired decomposition level. Must be in the
% range [0, log2(N)-1], where "0" implies
% full decomposition.
%
% OUTPUTS:
%
% Tforward --> (N x N) Forward transform matrix
%
% Tinverse --> (N x N) Inverse transform matrix
%
if exist('dec_levels') ~= 1,
dec_levels = 0;
end
if N == 1,
Tforward = 1;
elseif strcmp(transform_type, 'hadamard') == 1,
Tforward = hadamard(N);
elseif (N == 8) & strcmp(transform_type, 'bior1.5')==1 % hardcoded transform so that the wavelet toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.219417649252501 0.449283757993216 0.449283757993216 0.219417649252501 -0.219417649252501 -0.449283757993216 -0.449283757993216 -0.219417649252501;
0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846 -0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284;
-0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284 0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846;
0.707106781186547 -0.707106781186547 0 0 0 0 0 0;
0 0 0.707106781186547 -0.707106781186547 0 0 0 0;
0 0 0 0 0.707106781186547 -0.707106781186547 0 0;
0 0 0 0 0 0 0.707106781186547 -0.707106781186547];
elseif (N == 8) & strcmp(transform_type, 'dct')==1 % hardcoded transform so that the signal processing toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.490392640201615 0.415734806151273 0.277785116509801 0.097545161008064 -0.097545161008064 -0.277785116509801 -0.415734806151273 -0.490392640201615;
0.461939766255643 0.191341716182545 -0.191341716182545 -0.461939766255643 -0.461939766255643 -0.191341716182545 0.191341716182545 0.461939766255643;
0.415734806151273 -0.097545161008064 -0.490392640201615 -0.277785116509801 0.277785116509801 0.490392640201615 0.097545161008064 -0.415734806151273;
0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274 0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274;
0.277785116509801 -0.490392640201615 0.097545161008064 0.415734806151273 -0.415734806151273 -0.097545161008064 0.490392640201615 -0.277785116509801;
0.191341716182545 -0.461939766255643 0.461939766255643 -0.191341716182545 -0.191341716182545 0.461939766255643 -0.461939766255643 0.191341716182545;
0.097545161008064 -0.277785116509801 0.415734806151273 -0.490392640201615 0.490392640201615 -0.415734806151273 0.277785116509801 -0.097545161008064];
elseif (N == 8) & strcmp(transform_type, 'dst')==1 % hardcoded transform so that the PDE toolbox is not needed to generate it
Tforward = [ 0.161229841765317 0.303012985114696 0.408248290463863 0.464242826880013 0.464242826880013 0.408248290463863 0.303012985114696 0.161229841765317;
0.303012985114696 0.464242826880013 0.408248290463863 0.161229841765317 -0.161229841765317 -0.408248290463863 -0.464242826880013 -0.303012985114696;
0.408248290463863 0.408248290463863 0 -0.408248290463863 -0.408248290463863 0 0.408248290463863 0.408248290463863;
0.464242826880013 0.161229841765317 -0.408248290463863 -0.303012985114696 0.303012985114696 0.408248290463863 -0.161229841765317 -0.464242826880013;
0.464242826880013 -0.161229841765317 -0.408248290463863 0.303012985114696 0.303012985114696 -0.408248290463863 -0.161229841765317 0.464242826880013;
0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863;
0.303012985114696 -0.464242826880013 0.408248290463863 -0.161229841765317 -0.161229841765317 0.408248290463863 -0.464242826880013 0.303012985114696;
0.161229841765317 -0.303012985114696 0.408248290463863 -0.464242826880013 0.464242826880013 -0.408248290463863 0.303012985114696 -0.161229841765317];
elseif strcmp(transform_type, 'dct') == 1,
Tforward = dct(eye(N));
elseif strcmp(transform_type, 'dst') == 1,
Tforward = dst(eye(N));
elseif strcmp(transform_type, 'DCrand') == 1,
x = randn(N); x(1:end,1) = 1; [Q,R] = qr(x);
if (Q(1) < 0),
Q = -Q;
end;
Tforward = Q';
else %% a wavelet decomposition supported by 'wavedec'
%%% Set periodic boundary conditions, to preserve bi-orthogonality
dwtmode('per','nodisp');
Tforward = zeros(N,N);
for i = 1:N
Tforward(:,i)=wavedec(circshift([1 zeros(1,N-1)],[dec_levels i-1]), log2(N), transform_type); %% construct transform matrix
end
end
%%% Normalize the basis elements
Tforward = (Tforward' * diag(sqrt(1./sum(Tforward.^2,2))))';
%%% Compute the inverse transform matrix
Tinverse = inv(Tforward);
return; |
github | zongwave/IPASS-master | CBM3D.m | .m | IPASS-master/BM3D/BM3D/CBM3D.m | 28,530 | utf_8 | 9a3e40b8b0f177169d223c8676892b13 | function [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma, profile, print_to_screen, colorspace)
%
% CBM3D is algorithm for attenuation of additive white Gaussian noise from
% color RGB images. This algorithm reproduces the results from the article:
%
% [1] K. Dabov, A. Foi, V. Katkovnik, and K. Egiazarian, "Color image
% denoising via sparse 3D collaborative filtering with grouping constraint in
% luminance-chrominance space," submitted to IEEE Int. Conf. Image Process.,
% January 2007, in review, preprint at http://www.cs.tut.fi/~foi/GCF-BM3D.
%
% FUNCTION INTERFACE:
%
% [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma, profile, print_to_screen, colorspace)
%
% ! The function can work without any of the input arguments,
% in which case, the internal default ones are used !
%
% BASIC USAGE EXAMPLES:
%
% Case 1) Using the default parameters (i.e., image name, sigma, etc.)
%
% [PSNR, yRGB_est] = CBM3D;
%
% Case 2) Using an external noisy image:
%
% % Read an RGB image and scale its intensities in range [0,1]
% yRGB = im2double(imread('image_House256rgb.png'));
% % Generate the same seed used in the experimental results of [1]
% randn('seed', 0);
% % Standard deviation of the noise --- corresponding to intensity
% % range [0,255], despite that the input was scaled in [0,1]
% sigma = 25;
% % Add the AWGN with zero mean and standard deviation 'sigma'
% zRGB = yRGB + (sigma/255)*randn(size(yRGB));
% % Denoise 'zRGB'. The denoised image is 'yRGB_est', and 'NA = 1'
% % because the true image was not provided
% [NA, yRGB_est] = CBM3D(1, zRGB, sigma);
% % Compute the putput PSNR
% PSNR = 10*log10(1/mean((yRGB(:)-yRGB_est(:)).^2))
% % show the noisy image 'zRGB' and the denoised 'yRGB_est'
% figure; imshow(min(max(zRGB,0),1));
% figure; imshow(min(max(yRGB_est,0),1));
%
% Case 3) If the original image yRGB is provided as the first input
% argument, then some additional information is printed (PSNRs,
% figures, etc.). That is, "[NA, yRGB_est] = BM3D(1, zRGB, sigma);" in the
% above code should be replaced with:
%
% [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma);
%
%
% INPUT ARGUMENTS (OPTIONAL):
% 1) yRGB (M x N x 3): Noise-free RGB image (needed for computing PSNR),
% replace with the scalar 1 if not available.
% 2) zRGB (M x N x 3): Noisy RGBimage (intensities in range [0,1] or [0,255])
% 3) sigma (double) : Std. dev. of the noise (corresponding to intensities
% in range [0,255] even if the range of zRGB is [0,1])
% 4) profile (char) : 'np' --> Normal Profile
% 'lc' --> Fast Profile
% 5) print_to_screen : 0 --> do not print output information (and do
% not plot figures)
% 1 --> print information and plot figures
% 6) colorspace (char): 'opp' --> use opponent colorspace
% 'yCbCr' --> use yCbCr colorspace
%
% OUTPUTS:
% 1) PSNR (double) : Output PSNR (dB), only if the original
% image is available, otherwise PSNR = 0
% 2) yRGB_est (M x N x 3): Final RGB estimate (in the range [0,1])
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2007-2011 Tampere University of Technology.
% All rights reserved.
% This work should only be used for nonprofit purposes.
%
% AUTHORS:
% Kostadin Dabov, email: dabov _at_ cs.tut.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% In case, there is no input image (zRGB or yRGB), then use the filename
%%%% below to read an original image (might contain path also). Later,
%%%% artificial AWGN noise is added and this noisy image is processed
%%%% by the CBM3D.
%%%%
image_name = [
% 'kodim12.png'
'image_Lena512rgb.png'
% 'image_House256rgb.png'
% 'image_Peppers512rgb.png'
% 'image_Baboon512rgb.png'
% 'image_F16_512rgb.png'
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Quality/complexity trade-off
%%%%
%%%% 'np' --> Normal Profile (balanced quality)
%%%% 'lc' --> Low Complexity Profile (fast, lower quality)
%%%%
%%%% 'high' --> High Profile (high quality, not documented in [1])
%%%%
%%%% 'vn' --> This profile is automatically enabled for high noise
%%%% when sigma > 40
%%%%
%%%% 'vn_old' --> This is the old 'vn' profile that was used in [1].
%%%% It gives inferior results than 'vn' in most cases.
%%%%
if (exist('profile') ~= 1)
profile = 'np'; %% default profile
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Specify the std. dev. of the corrupting noise
%%%%
if (exist('sigma') ~= 1),
sigma = 50; %% default standard deviation of the AWGN
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Colorspace in which we perform denoising. BM is applied to the first
%%%% component and the matching information is re-used for the other two.
%%%%
if (exist('colorspace') ~= 1),
colorspace = 'opp'; %%% (valid colorspaces are: 'yCbCr' and 'opp')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Following are the parameters for the Normal Profile.
%%%%
%%%% Select transforms ('dct', 'dst', 'hadamard', or anything that is listed by 'help wfilters'):
transform_2D_HT_name = 'bior1.5'; %% transform used for the HT filt. of size N1 x N1
transform_2D_Wiener_name = 'dct'; %% transform used for the Wiener filt. of size N1_wiener x N1_wiener
transform_3rd_dim_name = 'haar'; %% transform used in the 3-rd dim, the same for HT and Wiener filt.
%%%% Hard-thresholding (HT) parameters:
N1 = 8; %% N1 x N1 is the block size used for the hard-thresholding (HT) filtering
Nstep = 3; %% sliding step to process every next reference block
N2 = 16; %% maximum number of similar blocks (maximum size of the 3rd dimension of a 3D array)
Ns = 39; %% length of the side of the search neighborhood for full-search block-matching (BM), must be odd
tau_match = 3000;%% threshold for the block-distance (d-distance)
lambda_thr2D = 0; %% threshold parameter for the coarse initial denoising used in the d-distance measure
lambda_thr3D = 2.7; %% threshold parameter for the hard-thresholding in 3D transform domain
beta = 2.0; %% parameter of the 2D Kaiser window used in the reconstruction
%%%% Wiener filtering parameters:
N1_wiener = 8;
Nstep_wiener = 3;
N2_wiener = 32;
Ns_wiener = 39;
tau_match_wiener = 400;
beta_wiener = 2.0;
%%%% Block-matching parameters:
stepFS = 1; %% step that forces to switch to full-search BM, "1" implies always full-search
smallLN = 'not used in np'; %% if stepFS > 1, then this specifies the size of the small local search neighb.
stepFSW = 1;
smallLNW = 'not used in np';
thrToIncStep = 8; %% used in the HT filtering to increase the sliding step in uniform regions
if strcmp(profile, 'lc') == 1,
Nstep = 6;
Ns = 25;
Nstep_wiener = 5;
N2_wiener = 16;
Ns_wiener = 25;
thrToIncStep = 3;
smallLN = 3;
stepFS = 6*Nstep;
smallLNW = 2;
stepFSW = 5*Nstep_wiener;
end
% Profile 'vn' was proposed in
% Y. Hou, C. Zhao, D. Yang, and Y. Cheng, 'Comment on "Image Denoising by Sparse 3D Transform-Domain
% Collaborative Filtering"', accepted for publication, IEEE Trans. on Image Processing, July, 2010.
% as a better alternative to that initially proposed in [1] (which is currently in profile 'vn_old')
if (strcmp(profile, 'vn') == 1) | (sigma > 40),
N2 = 32;
Nstep = 4;
N1_wiener = 11;
Nstep_wiener = 6;
lambda_thr3D = 2.8;
thrToIncStep = 3;
tau_match_wiener = 3500;
tau_match = 25000;
Ns_wiener = 39;
end
% The 'vn_old' profile corresponds to the original parameters for strong noise proposed in [1].
if (strcmp(profile, 'vn_old') == 1) & (sigma > 40),
transform_2D_HT_name = 'dct';
N1 = 12;
Nstep = 4;
N1_wiener = 11;
Nstep_wiener = 6;
lambda_thr3D = 2.8;
lambda_thr2D = 2.0;
thrToIncStep = 3;
tau_match_wiener = 3500;
tau_match = 5000;
Ns_wiener = 39;
end
decLevel = 0; %% dec. levels of the dyadic wavelet 2D transform for blocks (0 means full decomposition, higher values decrease the dec. number)
thr_mask = ones(N1); %% N1xN1 mask of threshold scaling coeff. --- by default there is no scaling, however the use of different thresholds for different wavelet decompoistion subbands can be done with this matrix
if strcmp(profile, 'high') == 1,
decLevel = 1;
Nstep = 2;
Nstep_wiener = 2;
lambda_thr3D = 2.5;
vMask = ones(N1,1); vMask((end/4+1):end/2)= 1.01; vMask((end/2+1):end) = 1.07; %% this allows to have different threhsolds for the finest and next-to-the-finest subbands
thr_mask = vMask * vMask';
beta = 2.5;
beta_wiener = 1.5;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Note: touch below this point only if you know what you are doing!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check whether to dump information to the screen or reamin silent
dump_output_information = 1;
if (exist('print_to_screen') == 1) & (print_to_screen == 0),
dump_output_information = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Create transform matrices, etc.
%%%%
[Tfor, Tinv] = getTransfMatrix(N1, transform_2D_HT_name, decLevel); %% get (normalized) forward and inverse transform matrices
[TforW, TinvW] = getTransfMatrix(N1_wiener, transform_2D_Wiener_name); %% get (normalized) forward and inverse transform matrices
if (strcmp(transform_3rd_dim_name, 'haar') == 1) | (strcmp(transform_3rd_dim_name(end-2:end), '1.1') == 1),
%%% If Haar is used in the 3-rd dimension, then a fast internal transform is used, thus no need to generate transform
%%% matrices.
hadper_trans_single_den = {};
inverse_hadper_trans_single_den = {};
else
%%% Create transform matrices. The transforms are later applied by
%%% matrix-vector multiplication for the 1D case.
for hpow = 0:ceil(log2(max(N2,N2_wiener))),
h = 2^hpow;
[Tfor3rd, Tinv3rd] = getTransfMatrix(h, transform_3rd_dim_name, 0);
hadper_trans_single_den{h} = single(Tfor3rd);
inverse_hadper_trans_single_den{h} = single(Tinv3rd');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% 2D Kaiser windows used in the aggregation of block-wise estimates
%%%%
if beta_wiener==2 & beta==2 & N1_wiener==8 & N1==8 % hardcode the window function so that the signal processing toolbox is not needed by default
Wwin2D = [ 0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924;
0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;
0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;
0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;
0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;
0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;
0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;
0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924];
Wwin2D_wiener = Wwin2D;
else
Wwin2D = kaiser(N1, beta) * kaiser(N1, beta)'; % Kaiser window used in the aggregation of the HT part
Wwin2D_wiener = kaiser(N1_wiener, beta_wiener) * kaiser(N1_wiener, beta_wiener)'; % Kaiser window used in the aggregation of the Wiener filt. part
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% If needed, read images, generate noise, or scale the images to the
%%%% [0,1] interval
%%%%
if (exist('yRGB') ~= 1) | (exist('zRGB') ~= 1)
yRGB = im2double(imread(image_name)); %% read a noise-free image
randn('seed', 0); %% generate seed
zRGB = yRGB + (sigma/255)*randn(size(yRGB)); %% create a noisy image
else % external images
image_name = 'External image';
% convert zRGB to double precision
zRGB = double(zRGB);
% convert yRGB to double precision
yRGB = double(yRGB);
% if zRGB's range is [0, 255], then convert to [0, 1]
if (max(zRGB(:)) > 10), % a naive check for intensity range
zRGB = zRGB / 255;
end
% if yRGB's range is [0, 255], then convert to [0, 1]
if (max(yRGB(:)) > 10), % a naive check for intensity range
yRGB = yRGB / 255;
end
end
if (size(zRGB,3) ~= 3) | (size(zRGB,4) ~= 1),
error('CBM3D accepts only input RGB images (i.e. matrices of size M x N x 3).');
end
% Check if the true image yRGB is a valid one; if not, then we cannot compute PSNR, etc.
yRGB_is_invalid_image = (length(size(zRGB)) ~= length(size(yRGB))) | (size(zRGB,1) ~= size(yRGB,1)) | (size(zRGB,2) ~= size(yRGB,2)) | (size(zRGB,3) ~= size(yRGB,3));
if (yRGB_is_invalid_image),
dump_output_information = 0;
end
[Xv, Xh, numSlices] = size(zRGB); %%% obtain image sizes
if numSlices ~= 3
fprintf('Error, an RGB color image is required!\n');
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Change colorspace, compute the l2-norms of the new color channels
%%%%
[zColSpace l2normLumChrom] = function_rgb2LumChrom(zRGB, colorspace);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Print image information to the screen
%%%%
if dump_output_information == 1,
fprintf(sprintf('Image: %s (%dx%dx%d), sigma: %.1f\n', image_name, Xv, Xh, numSlices, sigma));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 1. Basic estimate by collaborative hard-thresholding and using
%%%% the grouping constraint on the chrominances.
%%%%
tic;
y_hat = bm3d_thr_color(zColSpace, hadper_trans_single_den, Nstep, N1, N2, lambda_thr2D,...
lambda_thr3D, tau_match*N1*N1/(255*255), (Ns-1)/2, sigma/255, thrToIncStep, single(Tfor), single(Tinv)', inverse_hadper_trans_single_den, single(thr_mask), 'unused arg', 'unused arg', l2normLumChrom, Wwin2D, smallLN, stepFS );
estimate_elapsed_time = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 2. Final estimate by collaborative Wiener filtering and using
%%%% the grouping constraint on the chrominances.
%%%%
tic;
yRGB_est = bm3d_wiener_color(zColSpace, y_hat, hadper_trans_single_den, Nstep_wiener, N1_wiener, N2_wiener, ...
'unused_arg', tau_match_wiener*N1_wiener*N1_wiener/(255*255), (Ns_wiener-1)/2, sigma/255, 'unused arg', single(TforW), single(TinvW)', inverse_hadper_trans_single_den, 'unused arg', 'unused arg', l2normLumChrom, Wwin2D_wiener, smallLNW, stepFSW );
wiener_elapsed_time = toc;
yRGB_est = double(yRGB_est);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Convert back to RGB colorspace
%%%%
yRGB_est = function_LumChrom2rgb(yRGB_est, colorspace);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Calculate final estimate's PSNR and ISNR, print them, and show the
%%%% denoised image
%%%%
PSNR = 0; %% Remains 0 if the true image yRGB is not available
if (~yRGB_is_invalid_image), % then we assume yRGB is a valid image
PSNR = 10*log10(1/mean((yRGB(:)-yRGB_est(:)).^2));
end
if dump_output_information == 1,
fprintf(sprintf('FINAL ESTIMATE (total time: %.1f sec), PSNR: %.2f dB\n', ...
wiener_elapsed_time + estimate_elapsed_time, PSNR));
figure, imshow(min(max(zRGB,0),1)); title(sprintf('Noisy %s, PSNR: %.3f dB (sigma: %d)', ...
image_name(1:end-4), 10*log10(1/mean((yRGB(:)-zRGB(:)).^2)), sigma));
figure, imshow(min(max(yRGB_est,0),1)); title(sprintf('Denoised %s, PSNR: %.3f dB', ...
image_name(1:end-4), PSNR));
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some auxiliary functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% Create forward and inverse transform matrices, which allow for perfect
% reconstruction. The forward transform matrix is normalized so that the
% l2-norm of each basis element is 1.
%
% [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% INPUTS:
%
% N --> Size of the transform (for wavelets, must be 2^K)
%
% transform_type --> 'dct', 'dst', 'hadamard', or anything that is
% listed by 'help wfilters' (bi-orthogonal wavelets)
% 'DCrand' -- an orthonormal transform with a DC and all
% the other basis elements of random nature
%
% dec_levels --> If a wavelet transform is generated, this is the
% desired decomposition level. Must be in the
% range [0, log2(N)-1], where "0" implies
% full decomposition.
%
% OUTPUTS:
%
% Tforward --> (N x N) Forward transform matrix
%
% Tinverse --> (N x N) Inverse transform matrix
%
if exist('dec_levels') ~= 1,
dec_levels = 0;
end
if N == 1,
Tforward = 1;
elseif strcmp(transform_type, 'hadamard') == 1,
Tforward = hadamard(N);
elseif (N == 8) & strcmp(transform_type, 'bior1.5')==1 % hardcoded transform so that the wavelet toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.219417649252501 0.449283757993216 0.449283757993216 0.219417649252501 -0.219417649252501 -0.449283757993216 -0.449283757993216 -0.219417649252501;
0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846 -0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284;
-0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284 0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846;
0.707106781186547 -0.707106781186547 0 0 0 0 0 0;
0 0 0.707106781186547 -0.707106781186547 0 0 0 0;
0 0 0 0 0.707106781186547 -0.707106781186547 0 0;
0 0 0 0 0 0 0.707106781186547 -0.707106781186547];
elseif (N == 8) & strcmp(transform_type, 'dct')==1 % hardcoded transform so that the signal processing toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.490392640201615 0.415734806151273 0.277785116509801 0.097545161008064 -0.097545161008064 -0.277785116509801 -0.415734806151273 -0.490392640201615;
0.461939766255643 0.191341716182545 -0.191341716182545 -0.461939766255643 -0.461939766255643 -0.191341716182545 0.191341716182545 0.461939766255643;
0.415734806151273 -0.097545161008064 -0.490392640201615 -0.277785116509801 0.277785116509801 0.490392640201615 0.097545161008064 -0.415734806151273;
0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274 0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274;
0.277785116509801 -0.490392640201615 0.097545161008064 0.415734806151273 -0.415734806151273 -0.097545161008064 0.490392640201615 -0.277785116509801;
0.191341716182545 -0.461939766255643 0.461939766255643 -0.191341716182545 -0.191341716182545 0.461939766255643 -0.461939766255643 0.191341716182545;
0.097545161008064 -0.277785116509801 0.415734806151273 -0.490392640201615 0.490392640201615 -0.415734806151273 0.277785116509801 -0.097545161008064];
elseif (N == 8) & strcmp(transform_type, 'dst')==1 % hardcoded transform so that the PDE toolbox is not needed to generate it
Tforward = [ 0.161229841765317 0.303012985114696 0.408248290463863 0.464242826880013 0.464242826880013 0.408248290463863 0.303012985114696 0.161229841765317;
0.303012985114696 0.464242826880013 0.408248290463863 0.161229841765317 -0.161229841765317 -0.408248290463863 -0.464242826880013 -0.303012985114696;
0.408248290463863 0.408248290463863 0 -0.408248290463863 -0.408248290463863 0 0.408248290463863 0.408248290463863;
0.464242826880013 0.161229841765317 -0.408248290463863 -0.303012985114696 0.303012985114696 0.408248290463863 -0.161229841765317 -0.464242826880013;
0.464242826880013 -0.161229841765317 -0.408248290463863 0.303012985114696 0.303012985114696 -0.408248290463863 -0.161229841765317 0.464242826880013;
0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863;
0.303012985114696 -0.464242826880013 0.408248290463863 -0.161229841765317 -0.161229841765317 0.408248290463863 -0.464242826880013 0.303012985114696;
0.161229841765317 -0.303012985114696 0.408248290463863 -0.464242826880013 0.464242826880013 -0.408248290463863 0.303012985114696 -0.161229841765317];
elseif strcmp(transform_type, 'dct') == 1,
Tforward = dct(eye(N));
elseif strcmp(transform_type, 'dst') == 1,
Tforward = dst(eye(N));
elseif strcmp(transform_type, 'DCrand') == 1,
x = randn(N); x(1:end,1) = 1; [Q,R] = qr(x);
if (Q(1) < 0),
Q = -Q;
end;
Tforward = Q';
else %% a wavelet decomposition supported by 'wavedec'
%%% Set periodic boundary conditions, to preserve bi-orthogonality
dwtmode('per','nodisp');
Tforward = zeros(N,N);
for i = 1:N
Tforward(:,i)=wavedec(circshift([1 zeros(1,N-1)],[dec_levels i-1]), log2(N), transform_type); %% construct transform matrix
end
end
%%% Normalize the basis elements
Tforward = (Tforward' * diag(sqrt(1./sum(Tforward.^2,2))))';
%%% Compute the inverse transform matrix
Tinverse = inv(Tforward);
return;
function [y, A, l2normLumChrom]=function_rgb2LumChrom(xRGB, colormode)
% Forward color-space transformation ( inverse transformation is function_LumChrom2rgb.m )
%
% Alessandro Foi - Tampere University of Technology - 2005 - 2006 Public release v1.03 (March 2006)
% -----------------------------------------------------------------------------------------------------------------------------------------------
%
% SYNTAX:
%
% [y A l2normLumChrom] = function_rgb2LumChrom(xRGB, colormode);
%
% INPUTS:
% xRGB is RGB image with range [0 1]^3
%
% colormode = 'opp', 'yCbCr', 'pca', or a custom 3x3 matrix
%
% 'opp' Opponent color space ('opp' is equirange version)
% 'yCbCr' The standard yCbCr (e.g. for JPEG images)
% 'pca' Principal components (note that this transformation is renormalized to be equirange)
%
% OUTPUTS:
% y is color-transformed image (with range typically included in or equal to [0 1]^3, depending on the transformation matrix)
%
% l2normLumChrom (optional) l2-norm of the transformation (useful for noise std calculation)
% A transformation matrix (used necessarily if colormode='pca')
%
% NOTES: - If only two outputs are used, then the second output is l2normLumChrom, unless colormode='pca';
% - 'opp' is used by default if no colormode is specified.
%
%
% USAGE EXAMPLE FOR PCA TRANSFORMATION:
% %%%% -- forward color transformation --
% if colormode=='pca'
% [zLumChrom colormode] = function_rgb2LumChrom(zRGB,colormode); % 'colormode' is assigned a 3x3 transform matrix
% else
% zLumChrom = function_rgb2LumChrom(zRGB,colormode);
% end
%
% %%%% [ ... ] Some processing [ ... ]
%
% %%%% -- inverse color transformation --
% zRGB=function_LumChrom2rgb(zLumChrom,colormode);
%
if nargin==1
colormode='opp';
end
change_output=0;
if size(colormode)==[3 3]
A=colormode;
l2normLumChrom=sqrt(sum(A.^2,2));
else
if strcmp(colormode,'opp')
A=[1/3 1/3 1/3; 0.5 0 -0.5; 0.25 -0.5 0.25];
end
if strcmp(colormode,'yCbCr')
A=[0.299 0.587 0.114; -0.16873660714285 -0.33126339285715 0.5; 0.5 -0.4186875 -0.0813125];
end
if strcmp(colormode,'pca')
A=princomp(reshape(xRGB,[size(xRGB,1)*size(xRGB,2) 3]))';
A=A./repmat(sum(A.*(A>0),2)-sum(A.*(A<0),2),[1 3]); %% ranges are normalized to unitary length;
else
if nargout==2
change_output=1;
end
end
end
%%%% Make sure that each channel's intensity range is [0,1]
maxV = sum(A.*(A>0),2);
minV = sum(A.*(A<0),2);
yNormal = (reshape(xRGB,[size(xRGB,1)*size(xRGB,2) 3]) * A' - repmat(minV, [1 size(xRGB,1)*size(xRGB,2)])') * diag(1./(maxV-minV)); % put in range [0,1]
y = reshape(yNormal, [size(xRGB,1) size(xRGB,2) 3]);
%%%% The l2-norm of each of the 3 transform basis elements
l2normLumChrom = diag(1./(maxV-minV))*sqrt(sum(A.^2,2));
if change_output
A=l2normLumChrom;
end
return;
function yRGB=function_LumChrom2rgb(x,colormode)
% Inverse color-space transformation ( forward transformation is function_rgb2LumChrom.m )
%
% Alessandro Foi - Tampere University of Technology - 2005 - 2006 Public release v1.03 (March 2006)
% -----------------------------------------------------------------------------------------------------------------------------------------------
%
% SYNTAX:
%
% yRGB = function_LumChrom2rgb(x,colormode);
%
% INPUTS:
% x is color-transformed image (with range typically included in or equal to [0 1]^3, depending on the transformation matrix)
%
% colormode = 'opp', 'yCbCr', or a custom 3x3 matrix (e.g. provided by the forward transform when 'pca' is selected)
%
% 'opp' opponent color space ('opp' is equirange version)
% 'yCbCr' standard yCbCr (e.g. for JPEG images)
%
% OUTPUTS:
% x is RGB image (with range [0 1]^3)
%
%
% NOTE: 'opp' is used by default if no colormode is specified
%
if nargin==1
colormode='opp';
end
if size(colormode)==[3 3]
A=colormode;
B=inv(A);
else
if strcmp(colormode,'opp')
A =[1/3 1/3 1/3; 0.5 0 -0.5; 0.25 -0.5 0.25];
B =[1 1 2/3;1 0 -4/3;1 -1 2/3];
end
if strcmp(colormode,'yCbCr')
A=[0.299 0.587 0.114; -0.16873660714285 -0.33126339285715 0.5; 0.5 -0.4186875 -0.0813125];
B=inv(A);
end
end
%%%% Make sure that each channel's intensity range is [0,1]
maxV = sum(A.*(A>0),2);
minV = sum(A.*(A<0),2);
xNormal = reshape(x,[size(x,1)*size(x,2) 3]) * diag(maxV-minV) + repmat(minV, [1 size(x,1)*size(x,2)])'; % put in range [0,1]
yRGB = reshape(xNormal * B', [ size(x,1) size(x,2) 3]);
return;
|
github | zongwave/IPASS-master | BM3D.m | .m | IPASS-master/BM3D/BM3D/BM3D.m | 22,747 | utf_8 | 7e2312aaf69cead1edcfd768d113392d | function [PSNR, y_est] = BM3D(y, z, sigma, profile, print_to_screen)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BM3D is an algorithm for attenuation of additive white Gaussian noise from
% grayscale images. This algorithm reproduces the results from the article:
%
% [1] K. Dabov, A. Foi, V. Katkovnik, and K. Egiazarian, "Image Denoising
% by Sparse 3D Transform-Domain Collaborative Filtering,"
% IEEE Transactions on Image Processing, vol. 16, no. 8, August, 2007.
% preprint at http://www.cs.tut.fi/~foi/GCF-BM3D.
%
%
% FUNCTION INTERFACE:
%
% [PSNR, y_est] = BM3D(y, z, sigma, profile, print_to_screen)
%
% ! The function can work without any of the input arguments,
% in which case, the internal default ones are used !
%
% BASIC USAGE EXAMPLES:
%
% Case 1) Using the default parameters (i.e., image name, sigma, etc.)
%
% [PSNR, y_est] = BM3D;
%
% Case 2) Using an external noisy image:
%
% % Read a grayscale image and scale its intensities in range [0,1]
% y = im2double(imread('Cameraman256.png'));
% % Generate the same seed used in the experimental results of [1]
% randn('seed', 0);
% % Standard deviation of the noise --- corresponding to intensity
% % range [0,255], despite that the input was scaled in [0,1]
% sigma = 25;
% % Add the AWGN with zero mean and standard deviation 'sigma'
% z = y + (sigma/255)*randn(size(y));
% % Denoise 'z'. The denoised image is 'y_est', and 'NA = 1' because
% % the true image was not provided
% [NA, y_est] = BM3D(1, z, sigma);
% % Compute the putput PSNR
% PSNR = 10*log10(1/mean((y(:)-y_est(:)).^2))
% % show the noisy image 'z' and the denoised 'y_est'
% figure; imshow(z);
% figure; imshow(y_est);
%
% Case 3) If the original image y is provided as the first input
% argument, then some additional information is printed (PSNRs,
% figures, etc.). That is, "[NA, y_est] = BM3D(1, z, sigma);" in the
% above code should be replaced with:
%
% [PSNR, y_est] = BM3D(y, z, sigma);
%
%
% INPUT ARGUMENTS (OPTIONAL):
%
% 1) y (matrix M x N): Noise-free image (needed for computing PSNR),
% replace with the scalar 1 if not available.
% 2) z (matrix M x N): Noisy image (intensities in range [0,1] or [0,255])
% 3) sigma (double) : Std. dev. of the noise (corresponding to intensities
% in range [0,255] even if the range of z is [0,1])
% 4) profile (char) : 'np' --> Normal Profile
% 'lc' --> Fast Profile
% 5) print_to_screen : 0 --> do not print output information (and do
% not plot figures)
% 1 --> print information and plot figures
%
% OUTPUTS:
% 1) PSNR (double) : Output PSNR (dB), only if the original
% image is available, otherwise PSNR = 0
% 2) y_est (matrix M x N): Final estimate (in the range [0,1])
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2006-2011 Tampere University of Technology.
% All rights reserved.
% This work should only be used for nonprofit purposes.
%
% AUTHORS:
% Kostadin Dabov, email: dabov _at_ cs.tut.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% In case, a noisy image z is not provided, then use the filename
%%%% below to read an original image (might contain path also). Later,
%%%% artificial AWGN noise is added and this noisy image is processed
%%%% by the BM3D.
%%%%
image_name = [
% 'montage.png'
% 'Cameraman256.png'
% 'boat.png'
'Lena512.png'
% 'house.png'
% 'barbara.png'
% 'peppers256.png'
% 'fingerprint.png'
% 'couple.png'
% 'hill.png'
% 'man.png'
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Quality/complexity trade-off profile selection
%%%%
%%%% 'np' --> Normal Profile (balanced quality)
%%%% 'lc' --> Low Complexity Profile (fast, lower quality)
%%%%
%%%% 'high' --> High Profile (high quality, not documented in [1])
%%%%
%%%% 'vn' --> This profile is automatically enabled for high noise
%%%% when sigma > 40
%%%%
%%%% 'vn_old' --> This is the old 'vn' profile that was used in [1].
%%%% It gives inferior results than 'vn' in most cases.
%%%%
if (exist('profile') ~= 1)
profile = 'np'; %% default profile
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Specify the std. dev. of the corrupting noise
%%%%
if (exist('sigma') ~= 1),
sigma = 100; %% default standard deviation of the AWGN
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Following are the parameters for the Normal Profile.
%%%%
%%%% Select transforms ('dct', 'dst', 'hadamard', or anything that is listed by 'help wfilters'):
transform_2D_HT_name = 'bior1.5'; %% transform used for the HT filt. of size N1 x N1
transform_2D_Wiener_name = 'dct'; %% transform used for the Wiener filt. of size N1_wiener x N1_wiener
transform_3rd_dim_name = 'haar'; %% transform used in the 3-rd dim, the same for HT and Wiener filt.
%%%% Hard-thresholding (HT) parameters:
N1 = 8; %% N1 x N1 is the block size used for the hard-thresholding (HT) filtering
Nstep = 3; %% sliding step to process every next reference block
N2 = 16; %% maximum number of similar blocks (maximum size of the 3rd dimension of a 3D array)
Ns = 39; %% length of the side of the search neighborhood for full-search block-matching (BM), must be odd
tau_match = 3000;%% threshold for the block-distance (d-distance)
lambda_thr2D = 0; %% threshold parameter for the coarse initial denoising used in the d-distance measure
lambda_thr3D = 2.7; %% threshold parameter for the hard-thresholding in 3D transform domain
beta = 2.0; %% parameter of the 2D Kaiser window used in the reconstruction
%%%% Wiener filtering parameters:
N1_wiener = 8;
Nstep_wiener = 3;
N2_wiener = 32;
Ns_wiener = 39;
tau_match_wiener = 400;
beta_wiener = 2.0;
%%%% Block-matching parameters:
stepFS = 1; %% step that forces to switch to full-search BM, "1" implies always full-search
smallLN = 'not used in np'; %% if stepFS > 1, then this specifies the size of the small local search neighb.
stepFSW = 1;
smallLNW = 'not used in np';
thrToIncStep = 8; % if the number of non-zero coefficients after HT is less than thrToIncStep,
% than the sliding step to the next reference block is incresed to (nm1-1)
if strcmp(profile, 'lc') == 1,
Nstep = 6;
Ns = 25;
Nstep_wiener = 5;
N2_wiener = 16;
Ns_wiener = 25;
thrToIncStep = 3;
smallLN = 3;
stepFS = 6*Nstep;
smallLNW = 2;
stepFSW = 5*Nstep_wiener;
end
% Profile 'vn' was proposed in
% Y. Hou, C. Zhao, D. Yang, and Y. Cheng, 'Comment on "Image Denoising by Sparse 3D Transform-Domain
% Collaborative Filtering"', accepted for publication, IEEE Trans. on Image Processing, July, 2010.
% as a better alternative to that initially proposed in [1] (which is currently in profile 'vn_old')
if (strcmp(profile, 'vn') == 1) | (sigma > 40),
N2 = 32;
Nstep = 4;
N1_wiener = 11;
Nstep_wiener = 6;
lambda_thr3D = 2.8;
thrToIncStep = 3;
tau_match_wiener = 3500;
tau_match = 25000;
Ns_wiener = 39;
end
% The 'vn_old' profile corresponds to the original parameters for strong noise proposed in [1].
if (strcmp(profile, 'vn_old') == 1) & (sigma > 40),
transform_2D_HT_name = 'dct';
N1 = 12;
Nstep = 4;
N1_wiener = 11;
Nstep_wiener = 6;
lambda_thr3D = 2.8;
lambda_thr2D = 2.0;
thrToIncStep = 3;
tau_match_wiener = 3500;
tau_match = 5000;
Ns_wiener = 39;
end
decLevel = 0; %% dec. levels of the dyadic wavelet 2D transform for blocks (0 means full decomposition, higher values decrease the dec. number)
thr_mask = ones(N1); %% N1xN1 mask of threshold scaling coeff. --- by default there is no scaling, however the use of different thresholds for different wavelet decompoistion subbands can be done with this matrix
if strcmp(profile, 'high') == 1, %% this profile is not documented in [1]
decLevel = 1;
Nstep = 2;
Nstep_wiener = 2;
lambda_thr3D = 2.5;
vMask = ones(N1,1); vMask((end/4+1):end/2)= 1.01; vMask((end/2+1):end) = 1.07; %% this allows to have different threhsolds for the finest and next-to-the-finest subbands
thr_mask = vMask * vMask';
beta = 2.5;
beta_wiener = 1.5;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Note: touch below this point only if you know what you are doing!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Check whether to dump information to the screen or remain silent
dump_output_information = 1;
if (exist('print_to_screen') == 1) & (print_to_screen == 0),
dump_output_information = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Create transform matrices, etc.
%%%%
[Tfor, Tinv] = getTransfMatrix(N1, transform_2D_HT_name, decLevel); %% get (normalized) forward and inverse transform matrices
[TforW, TinvW] = getTransfMatrix(N1_wiener, transform_2D_Wiener_name, 0); %% get (normalized) forward and inverse transform matrices
if (strcmp(transform_3rd_dim_name, 'haar') == 1) | (strcmp(transform_3rd_dim_name(end-2:end), '1.1') == 1),
%%% If Haar is used in the 3-rd dimension, then a fast internal transform is used, thus no need to generate transform
%%% matrices.
hadper_trans_single_den = {};
inverse_hadper_trans_single_den = {};
else
%%% Create transform matrices. The transforms are later applied by
%%% matrix-vector multiplication for the 1D case.
for hpow = 0:ceil(log2(max(N2,N2_wiener))),
h = 2^hpow;
[Tfor3rd, Tinv3rd] = getTransfMatrix(h, transform_3rd_dim_name, 0);
hadper_trans_single_den{h} = single(Tfor3rd);
inverse_hadper_trans_single_den{h} = single(Tinv3rd');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% 2D Kaiser windows used in the aggregation of block-wise estimates
%%%%
if beta_wiener==2 & beta==2 & N1_wiener==8 & N1==8 % hardcode the window function so that the signal processing toolbox is not needed by default
Wwin2D = [ 0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924;
0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;
0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;
0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;
0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;
0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;
0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;
0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924];
Wwin2D_wiener = Wwin2D;
else
Wwin2D = kaiser(N1, beta) * kaiser(N1, beta)'; % Kaiser window used in the aggregation of the HT part
Wwin2D_wiener = kaiser(N1_wiener, beta_wiener) * kaiser(N1_wiener, beta_wiener)'; % Kaiser window used in the aggregation of the Wiener filt. part
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% If needed, read images, generate noise, or scale the images to the
%%%% [0,1] interval
%%%%
if (exist('y') ~= 1) | (exist('z') ~= 1)
y = im2double(imread(image_name)); %% read a noise-free image and put in intensity range [0,1]
randn('seed', 0); %% generate seed
z = y + (sigma/255)*randn(size(y)); %% create a noisy image
else % external images
image_name = 'External image';
% convert z to double precision if needed
z = double(z);
% convert y to double precision if needed
y = double(y);
% if z's range is [0, 255], then convert to [0, 1]
if (max(z(:)) > 10), % a naive check for intensity range
z = z / 255;
end
% if y's range is [0, 255], then convert to [0, 1]
if (max(y(:)) > 10), % a naive check for intensity range
y = y / 255;
end
end
if (size(z,3) ~= 1) | (size(y,3) ~= 1),
error('BM3D accepts only grayscale 2D images.');
end
% Check if the true image y is a valid one; if not, then we cannot compute PSNR, etc.
y_is_invalid_image = (length(size(z)) ~= length(size(y))) | (size(z,1) ~= size(y,1)) | (size(z,2) ~= size(y,2));
if (y_is_invalid_image),
dump_output_information = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Print image information to the screen
%%%%
if dump_output_information == 1,
fprintf('Image: %s (%dx%d), sigma: %.1f\n', image_name, size(z,1), size(z,2), sigma);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 1. Produce the basic estimate by HT filtering
%%%%
tic;
y_hat = bm3d_thr(z, hadper_trans_single_den, Nstep, N1, N2, lambda_thr2D,...
lambda_thr3D, tau_match*N1*N1/(255*255), (Ns-1)/2, (sigma/255), thrToIncStep, single(Tfor), single(Tinv)', inverse_hadper_trans_single_den, single(thr_mask), Wwin2D, smallLN, stepFS );
estimate_elapsed_time = toc;
if dump_output_information == 1,
PSNR_INITIAL_ESTIMATE = 10*log10(1/mean((y(:)-double(y_hat(:))).^2));
fprintf('BASIC ESTIMATE, PSNR: %.2f dB\n', PSNR_INITIAL_ESTIMATE);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Step 2. Produce the final estimate by Wiener filtering (using the
%%%% hard-thresholding initial estimate)
%%%%
tic;
y_est = bm3d_wiener(z, y_hat, hadper_trans_single_den, Nstep_wiener, N1_wiener, N2_wiener, ...
'unused arg', tau_match_wiener*N1_wiener*N1_wiener/(255*255), (Ns_wiener-1)/2, (sigma/255), 'unused arg', single(TforW), single(TinvW)', inverse_hadper_trans_single_den, Wwin2D_wiener, smallLNW, stepFSW, single(ones(N1_wiener)) );
wiener_elapsed_time = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Calculate the final estimate's PSNR, print it, and show the
%%%% denoised image next to the noisy one
%%%%
y_est = double(y_est);
PSNR = 0; %% Remains 0 if the true image y is not available
if (~y_is_invalid_image), % checks if y is a valid image
PSNR = 10*log10(1/mean((y(:)-y_est(:)).^2)); % y is valid
end
if dump_output_information == 1,
fprintf('FINAL ESTIMATE (total time: %.1f sec), PSNR: %.2f dB\n', ...
wiener_elapsed_time + estimate_elapsed_time, PSNR);
figure, imshow(z); title(sprintf('Noisy %s, PSNR: %.3f dB (sigma: %d)', ...
image_name(1:end-4), 10*log10(1/mean((y(:)-z(:)).^2)), sigma));
figure, imshow(y_est); title(sprintf('Denoised %s, PSNR: %.3f dB', ...
image_name(1:end-4), PSNR));
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some auxiliary functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% Create forward and inverse transform matrices, which allow for perfect
% reconstruction. The forward transform matrix is normalized so that the
% l2-norm of each basis element is 1.
%
% [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)
%
% INPUTS:
%
% N --> Size of the transform (for wavelets, must be 2^K)
%
% transform_type --> 'dct', 'dst', 'hadamard', or anything that is
% listed by 'help wfilters' (bi-orthogonal wavelets)
% 'DCrand' -- an orthonormal transform with a DC and all
% the other basis elements of random nature
%
% dec_levels --> If a wavelet transform is generated, this is the
% desired decomposition level. Must be in the
% range [0, log2(N)-1], where "0" implies
% full decomposition.
%
% OUTPUTS:
%
% Tforward --> (N x N) Forward transform matrix
%
% Tinverse --> (N x N) Inverse transform matrix
%
if exist('dec_levels') ~= 1,
dec_levels = 0;
end
if N == 1,
Tforward = 1;
elseif strcmp(transform_type, 'hadamard') == 1,
Tforward = hadamard(N);
elseif (N == 8) & strcmp(transform_type, 'bior1.5')==1 % hardcoded transform so that the wavelet toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.219417649252501 0.449283757993216 0.449283757993216 0.219417649252501 -0.219417649252501 -0.449283757993216 -0.449283757993216 -0.219417649252501;
0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846 -0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284;
-0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284 0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846;
0.707106781186547 -0.707106781186547 0 0 0 0 0 0;
0 0 0.707106781186547 -0.707106781186547 0 0 0 0;
0 0 0 0 0.707106781186547 -0.707106781186547 0 0;
0 0 0 0 0 0 0.707106781186547 -0.707106781186547];
elseif (N == 8) & strcmp(transform_type, 'dct')==1 % hardcoded transform so that the signal processing toolbox is not needed to generate it
Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;
0.490392640201615 0.415734806151273 0.277785116509801 0.097545161008064 -0.097545161008064 -0.277785116509801 -0.415734806151273 -0.490392640201615;
0.461939766255643 0.191341716182545 -0.191341716182545 -0.461939766255643 -0.461939766255643 -0.191341716182545 0.191341716182545 0.461939766255643;
0.415734806151273 -0.097545161008064 -0.490392640201615 -0.277785116509801 0.277785116509801 0.490392640201615 0.097545161008064 -0.415734806151273;
0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274 0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274;
0.277785116509801 -0.490392640201615 0.097545161008064 0.415734806151273 -0.415734806151273 -0.097545161008064 0.490392640201615 -0.277785116509801;
0.191341716182545 -0.461939766255643 0.461939766255643 -0.191341716182545 -0.191341716182545 0.461939766255643 -0.461939766255643 0.191341716182545;
0.097545161008064 -0.277785116509801 0.415734806151273 -0.490392640201615 0.490392640201615 -0.415734806151273 0.277785116509801 -0.097545161008064];
elseif (N == 8) & strcmp(transform_type, 'dst')==1 % hardcoded transform so that the PDE toolbox is not needed to generate it
Tforward = [ 0.161229841765317 0.303012985114696 0.408248290463863 0.464242826880013 0.464242826880013 0.408248290463863 0.303012985114696 0.161229841765317;
0.303012985114696 0.464242826880013 0.408248290463863 0.161229841765317 -0.161229841765317 -0.408248290463863 -0.464242826880013 -0.303012985114696;
0.408248290463863 0.408248290463863 0 -0.408248290463863 -0.408248290463863 0 0.408248290463863 0.408248290463863;
0.464242826880013 0.161229841765317 -0.408248290463863 -0.303012985114696 0.303012985114696 0.408248290463863 -0.161229841765317 -0.464242826880013;
0.464242826880013 -0.161229841765317 -0.408248290463863 0.303012985114696 0.303012985114696 -0.408248290463863 -0.161229841765317 0.464242826880013;
0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863;
0.303012985114696 -0.464242826880013 0.408248290463863 -0.161229841765317 -0.161229841765317 0.408248290463863 -0.464242826880013 0.303012985114696;
0.161229841765317 -0.303012985114696 0.408248290463863 -0.464242826880013 0.464242826880013 -0.408248290463863 0.303012985114696 -0.161229841765317];
elseif strcmp(transform_type, 'dct') == 1,
Tforward = dct(eye(N));
elseif strcmp(transform_type, 'dst') == 1,
Tforward = dst(eye(N));
elseif strcmp(transform_type, 'DCrand') == 1,
x = randn(N); x(1:end,1) = 1; [Q,R] = qr(x);
if (Q(1) < 0),
Q = -Q;
end;
Tforward = Q';
else %% a wavelet decomposition supported by 'wavedec'
%%% Set periodic boundary conditions, to preserve bi-orthogonality
dwtmode('per','nodisp');
Tforward = zeros(N,N);
for i = 1:N
Tforward(:,i)=wavedec(circshift([1 zeros(1,N-1)],[dec_levels i-1]), log2(N), transform_type); %% construct transform matrix
end
end
%%% Normalize the basis elements
Tforward = (Tforward' * diag(sqrt(1./sum(Tforward.^2,2))))';
%%% Compute the inverse transform matrix
Tinverse = inv(Tforward);
return;
|
github | zongwave/IPASS-master | Demo_IDDBM3D.m | .m | IPASS-master/BM3D/BM3D/IDDBM3D/Demo_IDDBM3D.m | 9,349 | utf_8 | 092ac706ce756d878d1d006a5698eb72 | function [isnr, y_hat] = Demo_IDDBM3D(experiment_number, test_image_name)
% ------------------------------------------------------------------------------------------
%
% Demo software for BM3D-frame based image deblurring
% Public release ver. 0.8 (beta) (June 03, 2011)
%
% ------------------------------------------------------------------------------------------
%
% This function implements the IDDBM3D image deblurring algorithm proposed in:
%
% [1] A.Danielyan, V. Katkovnik, and K. Egiazarian, "BM3D frames and
% variational image deblurring," submitted to IEEE TIP, May 2011
%
% ------------------------------------------------------------------------------------------
%
% authors: Aram Danielyan
% Vladimir Katkovnik
%
% web page: http://www.cs.tut.fi/~foi/GCF-BM3D/
%
% contact: [email protected]
%
% ------------------------------------------------------------------------------------------
% Copyright (c) 2011 Tampere University of Technology.
% All rights reserved.
% This work should be used for nonprofit purposes only.
% ------------------------------------------------------------------------------------------
%
% Disclaimer
% ----------
%
% Any unauthorized use of these routines for industrial or profit-oriented activities is
% expressively prohibited. By downloading and/or using any of these files, you implicitly
% agree to all the terms of the TUT limited license (included in the file Legal_Notice.txt).
% ------------------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FUNCTION INTERFACE:
%
% [psnr, y_hat] = Demo_IDDBM3D(experiment_number, test_image_name)
%
% INPUT:
% 1) experiment_number: 1 -> PSF 1, sigma^2 = 2
% 2 -> PSF 1, sigma^2 = 8
% 3 -> PSF 2, sigma^2 = 0.308
% 4 -> PSF 3, sigma^2 = 49
% 5 -> PSF 4, sigma^2 = 4
% 6 -> PSF 5, sigma^2 = 64
% 7-13 -> experiments 7-13 are not described in [1].
% see this file for the blur and noise parameters.
% 2) test_image_name: a valid filename of a grayscale test image
%
% OUTPUT:
% 1) isnr the output improvement in SNR, dB
% 2) y_hat: the restored image
%
% ! The function can work without any of the input arguments,
% in which case, the internal default ones are used !
%
% To run this demo functions within the BM3D package should be accessible to Matlab
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
addpath('../')
if ~exist('experiment_number','var'), experiment_number=3; end
if ~exist('test_image_name','var'), test_image_name='Cameraman256.png'; end
filename=test_image_name;
if 1 %
initType = 'bm3ddeb'; %use output of the BM3DDEB to initialize the algorithm
else
initType = 'zeros'; %use zero image to initialize the algorithm
end
matchType = 'bm3ddeb'; %build groups using output of the BM3DDEB algorithm
numIt = 200;
fprintf('Experiment number: %d\n', experiment_number);
fprintf('Image: %s\n', filename);
%% ------- Generating bservation ---------------------------------------------
disp('--- Generating observation ----');
y=im2double(imread(filename));
[yN,xN]=size(y);
switch experiment_number
case 1
sigma=sqrt(2)/255;
for x1=-7:7; for x2=-7:7; h(x1+8,x2+8)=1/(x1^2+x2^2+1); end, end; h=h./sum(h(:));
case 2
sigma=sqrt(8)/255;
s1=0; for a1=-7:7; s1=s1+1; s2=0; for a2=-7:7; s2=s2+1; h(s1,s2)=1/(a1^2+a2^2+1); end, end; h=h./sum(h(:));
case 3
BSNR=40;
sigma=-1; % if "sigma=-1", then the value of sigma depends on the BSNR
h=ones(9); h=h./sum(h(:));
case 4
sigma=7/255;
h=[1 4 6 4 1]'*[1 4 6 4 1]; h=h./sum(h(:)); % PSF
case 5
sigma=2/255;
h=fspecial('gaussian', 25, 1.6);
case 6
sigma=8/255;
h=fspecial('gaussian', 25, .4);
%extra experiments
case 7
BSNR=30;
sigma=-1;
h=ones(9); h=h./sum(h(:));
case 8
BSNR=20;
sigma=-1;
h=ones(9); h=h./sum(h(:));
case 9
BSNR=40;
sigma=-1;
h=fspecial('gaussian', 25, 1.6);
case 10
BSNR=20;
sigma=-1;
h=fspecial('gaussian', 25, 1.6);
case 11
BSNR=15;
sigma=-1;
h=fspecial('gaussian', 25, 1.6);
case 12
BSNR=40;
sigma=-1; % if "sigma=-1", then the value of sigma depends on the BSNR
h=ones(19); h=h./sum(h(:));
case 13
BSNR=25;
sigma=-1; % if "sigma=-1", then the value of sigma depends on the BSNR
h=ones(19); h=h./sum(h(:));
end
y_blur = imfilter(y, h, 'circular'); % performs blurring (by circular convolution)
if sigma == -1; %% check whether to use BSNR in order to define value of sigma
sigma=sqrt(norm(y_blur(:)-mean(y_blur(:)),2)^2 /(yN*xN*10^(BSNR/10)));
% Xv% compute sigma from the desired BSNR
end
%%%% Create a blurred and noisy observation
randn('seed',0);
z = y_blur + sigma*randn(yN, xN);
bsnr=10*log10(norm(y_blur(:)-mean(y_blur(:)),2)^2 /sigma^2/yN/xN);
psnr_z =PSNR(y,z,1,0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Observation BSNR: %4.2f, PSNR: %4.2f\n', bsnr, psnr_z);
%% ----- Computing initial estimate ---------------------
disp('--- Computing initial estimate ----');
[dummy, y_hat_RI,y_hat_RWI,zRI] = BM3DDEB_init(experiment_number, y, z, h, sigma);
switch lower(initType)
case 'zeros'
y_hat_init=zeros(size(z));
case 'zri'
y_hat_init=zRI;
case 'ri'
y_hat_init=y_hat_RI;
case 'bm3ddeb'
y_hat_init=y_hat_RWI;
end
switch lower(matchType)
case 'z'
match_im = z;
case 'y'
match_im = y;
case 'zri'
match_im = zRI;
case 'ri'
match_im = y_hat_RI;
case 'bm3ddeb'
match_im = y_hat_RWI;
end
psnr_init = PSNR(y, y_hat_init,1,0);
fprintf('Initialization method: %s\n', initType);
fprintf('Initial estimate ISNR: %4.2f, PSNR: %4.2f\n', psnr_init-psnr_z, psnr_init);
%% ------- Core algorithm ---------------------
%------ Description of the parameters of the IDDBM3D function ----------
%y - true image (use [] if true image is unavaliable)
%z - observed
%h - blurring PSF
%y_hat_init - initial estimate y_0
%match_im - image used to constuct groups and calculate weights g_r
%sigma - standard deviation of the noise
%threshType = 'h'; %use 's' for soft thresholding
%numIt - number of iterations
%gamma - regularization parameter see [1]
%tau - regularization parameter see [1] (thresholding level)
%xi - regularization parameter see [1], it is always set to 1 in this implementation
%showFigure - set to True to display figure with current estimate
%--------------------------------------------------------------------
threshType = 'h';
showFigure = true;
switch threshType
case {'s'}
gamma_tau_xi_inits= [
0.0004509 0.70 1;%1
0.0006803 0.78 1;%2
0.0003485 0.65 1;%3
0.0005259 0.72 1;%4
0.0005327 0.82 1;%5
7.632e-05 0.25 1;%6
0.0005818 0.81 1;%7
0.001149 1.18 1;%8
0.0004155 0.74 1;%9
0.0005591 0.74 1;%10
0.0007989 0.82 1;%11
0.0006702 0.75 1;%12
0.001931 1.83 1;%13
];
case {'h'}
gamma_tau_xi_inits= [
0.00051 3.13 1;%1
0.0006004 2.75 1;%2
0.0004573 2.91 1;%3
0.0005959 2.82 1;%4
0.0006018 3.63 1;%5
0.0001726 2.24 1;%6
0.00062 2.98 1;%7
0.001047 3.80 1;%8
0.0005125 3.00 1;%9
0.0005685 2.80 1;%10
0.0005716 2.75 1;%11
0.0005938 2.55 1;%12
0.001602 4.16 1;%13
];
end
gamma = gamma_tau_xi_inits(experiment_number,1);
tau = gamma_tau_xi_inits(experiment_number,2)/255*2.7;
xi = gamma_tau_xi_inits(experiment_number,3);
disp('-------- Start ----------');
fprintf('Number of iterations to perform: %d\n', numIt);
fprintf('Thresholding type: %s\n', threshType);
y_hat = IDDBM3D(y, h, z, y_hat_init, match_im, sigma, threshType, numIt, gamma, tau, xi, showFigure);
psnr = PSNR(y,y_hat,1,0);
isnr = psnr-psnr_z;
disp('-------- Results --------');
fprintf('Final estimate ISNR: %4.2f, PSNR: %4.2f\n', isnr, psnr);
return;
end
function PSNRdb = PSNR(x, y, maxval, borders)
if ~exist('borders', 'var'), borders = 0; end
if ~exist('maxval', 'var'), maxval = 255; end
xx=borders+1:size(x,1)-borders;
yy=borders+1:size(x,2)-borders;
PSNRdb = zeros(1,size(x,3));
for fr=1:size(x,3)
err = x(xx,yy,fr) - y(xx,yy,fr);
PSNRdb(fr) = 10 * log10((maxval^2)/mean2(err.^2));
end
end |
github | zongwave/IPASS-master | function_CreateLPAKernels.m | .m | IPASS-master/BM3D/BM3D/BM3D-SAPCA/function_CreateLPAKernels.m | 5,192 | utf_8 | b5ac9173b2024d53c79babfd89c0aaf9 | % Creates LPA kernels cell array (function_CreateLPAKernels)
%
% Alessandro Foi - Tampere University of Technology - 2003-2005
% ---------------------------------------------------------------
%
% Builds kernels cell arrays kernels{direction,size}
% and kernels_higher_order{direction,size,1:2}
% kernels_higher_order{direction,size,1} is the 3D matrix
% of all kernels for that particular direction/size
% kernels_higher_order{direction,size,2} is the 2D matrix
% containing the orders indices for the kernels
% contained in kernels_higher_order{direction,size,1}
%
% ---------------------------------------------------------------------
%
% kernels_higher_order{direction,size,1}(:,:,1) is the funcion estimate kernel
% kernels_higher_order{direction,size,1}(:,:,2) is a first derivative estimate kernel
%
% kernels_higher_order{direction,size,1}(:,:,n) is a higher order derivative estimate kernel
% whose orders with respect to x and y are specified in
% kernels_higher_order{direction,size,2}(n,:)=
% =[xorder yorder xorder+yorder]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [kernels, kernels_higher_order]=function_createLPAkernels(m,h1,h2,TYPE,window_type,directional_resolution,sig_winds,beta)
%--------------------------------------------------------------------------
% LPA ORDER AND KERNELS SIZES
%--------------------------------------------------------------------------
% m=[2,0]; % THE VECTOR ORDER OF LPA;
% h1=[1 2 3 4 5]; % sizes of the kernel
% h2=[1 2 3 4 5]; % row vectors h1 and h2 need to have the same lenght
%--------------------------------------------------------------------------
% WINDOWS PARAMETERS
%--------------------------------------------------------------------------
% sig_winds=[h1*1 ; h1*1]; % Gaussian parameter
% beta=1; % Parameter of window 6
% window_type=1 ; % window_type=1 for uniform, window_type=2 for Gaussian
% window_type=6 for exponentions with beta
% window_type=8 for Interpolation
% TYPE=00; % TYPE IS A SYMMETRY OF THE WINDOW
% 00 SYMMETRIC
% 10 NONSYMMETRIC ON X1 and SYMMETRIC ON X2
% 11 NONSYMMETRIC ON X1,X2 (Quadrants)
%
% for rotated directional kernels the method that is used for rotation can be specified by adding
% a binary digit in front of these types, as follows:
%
% 10
% 11 ARE "STANDARD" USING NN (Nearest Neighb.) (you can think of these numbers with a 0 in front)
% 00
%
% 110
% 111 ARE EXACT SAMPLING OF THE EXACT ROTATED KERNEL
% 100
%
% 210
% 211 ARE WITH BILINEAR INTERP
% 200
%
% 310
% 311 ARE WITH BICUBIC INTERP (not reccomended)
% 300
%--------------------------------------------------------------------------
% DIRECTIONAL PARAMETERS
%--------------------------------------------------------------------------
% directional_resolution=4; % number of directions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% From this point onwards this file and the create_LPA_kernels.m should be identical %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lenh=max(length(h1),length(h2));
clear kernels
clear kernels_higher_order
kernels=cell(directional_resolution,lenh);
kernels_higher_order=cell(directional_resolution,lenh,2);
THETASTEP=2*pi/directional_resolution;
THETA=[0:THETASTEP:2*pi-THETASTEP];
s1=0;
for theta=THETA,
s1=s1+1;
for s=1:lenh,
[gh,gh1,gh1degrees]=function_LPAKernelMatrixTheta(ceil(h2(s)),ceil(h1(s)),window_type,[sig_winds(1,s) sig_winds(2,s)],TYPE,theta, m);
kernels{s1,s}=gh; % degree=0 kernel
kernels_higher_order{s1,s,1}=gh1; % degree>=0 kernels
kernels_higher_order{s1,s,2}=gh1degrees; % polynomial indexes matrix
end % different lengths loop
end % different directions loop
|
github | zongwave/IPASS-master | function_Window2D.m | .m | IPASS-master/BM3D/BM3D/BM3D-SAPCA/function_Window2D.m | 2,356 | utf_8 | d7eb1c5259345f71197ec8f94d93107c | % Returns a scalar/matrix weights (window function) for the LPA estimates
% function w=function_Window2D(X,Y,window,sig_wind, beta);
% X,Y scalar/matrix variables
% window - type of the window weight
% sig_wind - std scaling for the Gaussian ro-weight
% beta -parameter of the degree in the weights
%----------------------------------------------------------------------------------
% V. Katkovnik & A. Foi - Tampere University of Technology - 2002-2005
function w=function_Window2D(X,Y,window,sig_wind, beta,ratio);
if nargin == 5
ratio=1;
end
IND=(abs(X)<=1)&(abs(Y)<=1);
IND2=((X.^2+Y.^2)<=1);
IND3=((X.^2+(Y*ratio).^2)<=1);
if window==1 % rectangular symmetric window
w=IND; end
if window==2 %Gaussian
X=X/sig_wind(1);
Y=Y/sig_wind(2);
w = IND.*exp(-(X.^2 + Y.^2)/2); %*(abs(Y)<=0.1*abs(X));%.*IND2; %((X.^2+Y.^2)<=1);
end
if window==3 % Quadratic window
w=(1-(X.^2+Y.^2)).*((X.^2+Y.^2)<=1); end
if window==4 % triangular symmetric window
w=(1-abs(X)).*(1-abs(Y)).*((X.^2+Y.^2)<=1); end
if window==5 % Epanechnikov symmetric window
w=(1-X.^2).*(1-Y.^2).*((X.^2+Y.^2)<=1);
end
if window==6 % Generalized Gaussian
X=X/sig_wind;
Y=Y/sig_wind;
w = exp(-((X.^2 + Y.^2).^beta)/2).*((X.^2+Y.^2)<=1); end
if window==7
X=X/sig_wind;
Y=Y/sig_wind;
w = exp(-abs(X) - abs(Y)).*IND; end
if window==8 % Interpolation
w=(1./(abs(X).^4+abs(Y).^4+0.0001)).*IND2;
end
if window==9 % Interpolation
NORM=(abs(X)).^2+(abs(Y)).^2+0.0001;
w=(1./NORM.*(1-sqrt(NORM)).^2).*(NORM<=1);
end
if window==10
w=((X.^2+Y.^2)<=1);
end
if window==11
temp=asin(Y./sqrt(X.^2+Y.^2+eps));
temp=temp*0.6; % Width of Beam
temp=(temp>0)*min(temp,1)+(temp<=0)*max(temp,-1);
w=max(0,IND.*cos(pi*temp));
end
if window==111
temp=asin(Y./sqrt(X.^2+Y.^2+eps));
temp=temp*0.8; % Width of Beam
temp=(temp>0)*min(temp,1)+(temp<=0)*max(temp,-1);
w=max(0,IND3.*(cos(pi*temp)>0));
% w=((X.^2+Y.^2)<=1);
end
if window==112
temp=atan(Y/(X+eps));
%temp=temp*0.8; % Width of Beam
%temp=(temp>0)*min(temp,1)+(temp<=0)*max(temp,-1);
w=max(0,IND3.*((abs(temp))<=pi/4));
% w=((X.^2+Y.^2)<=1);
end
|
github | zongwave/IPASS-master | function_LPAKernelMatrixTheta.m | .m | IPASS-master/BM3D/BM3D/BM3D-SAPCA/function_LPAKernelMatrixTheta.m | 6,420 | utf_8 | e4d4b5ab9a0cc7fe4e417116778164e7 | % Return the discrete kernels for LPA estimation and their degrees matrix
%
% function [G, G1, index_polynomials]=function_LPAKernelMatrixTheta(h2,h1,window_type,sig_wind,TYPE,theta, m)
%
%
% Outputs:
%
% G kernel for function estimation
% G1 kernels for function and derivative estimation
% G1(:,:,j), j=1 for function estimation, j=2 for d/dx, j=3 for d/dy,
% contains 0 and all higher order kernels (sorted by degree:
% 1 x y y^2 x^3 x^2y xy^2 y^3 etc...)
% index_polynomials matrix of degrees first column x powers, second
% column y powers, third column total degree
%
%
% Inputs:
%
% h2, h1 size of the kernel (size of the "asymmetrical portion")
% m=[m(1) m(2)] the vector order of the LPA any order combination should work
% "theta" is an angle of the directrd window
% "TYPE" is a type of the window support
% "sig_wind" - vector - sigma parameters of the Gaussian wind
% "beta"- parameter of the power in some weights for the window function
% (these last 3 parameters are fed into function_Window2D function)
%
%
% Alessandro Foi, 6 march 2004
function [G, G1, index_polynomials]=function_LPAKernelMatrixTheta(h2,h1,window_type,sig_wind,TYPE,theta, m)
global beta
%G1=0;
m(1)=min(h1,m(1));
m(2)=min(h2,m(2));
% builds ordered matrix of the monomes powers
number_of_polynomials=(min(m)+1)*(max(m)-min(m)+1)+(min(m)+1)*min(m)/2; % =size(index_polynomials,1)
index_polynomials=zeros(number_of_polynomials,2);
index3=1;
for index1=1:min(m)+1
for index2=1:max(m)+2-index1
index_polynomials(index3,:)=[index1-1,index2-1];
index3=index3+1;
end
end
if m(1)>m(2)
index_polynomials=fliplr(index_polynomials);
end
index_polynomials(:,3)=index_polynomials(:,1)+index_polynomials(:,2); %calculates degrees of polynomials
index_polynomials=sortrows(sortrows(index_polynomials,2),3); %sorts polynomials by degree (x first)
%=====================================================================================================================================
halfH=max(h1,h2);
H=-halfH+1:halfH-1;
% creates window function and then rotates it
% win_fun=zeros(halfH-1,halfH-1);
for x1=H
for x2=H
if TYPE==00|TYPE==200|TYPE==300 % SYMMETRIC WINDOW
win_fun1(x2+halfH,x1+halfH)=function_Window2D(x1/h1/(1-1000*eps),x2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
if TYPE==11|TYPE==211|TYPE==311 % NONSYMMETRIC ON X1,X2 WINDOW
win_fun1(x2+halfH,x1+halfH)=(x1>=-0.05)*(x2>=-0.05)*function_Window2D(x1/h1/(1-1000*eps),x2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
if TYPE==10|TYPE==210|TYPE==310 % NONSYMMETRIC ON X1 WINDOW
win_fun1(x2+halfH,x1+halfH)=(x1>=-0.05)*function_Window2D(x1/h1/(1-1000*eps),x2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
if TYPE==100|TYPE==110|TYPE==111 % exact sampling
xt1=x1*cos(-theta)+x2*sin(-theta);
xt2=x2*cos(-theta)-x1*sin(-theta);
if TYPE==100 % SYMMETRIC WINDOW
win_fun1(x2+halfH,x1+halfH)=function_Window2D(xt1/h1/(1-1000*eps),xt2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
if TYPE==111 % NONSYMMETRIC ON X1,X2 WINDOW
win_fun1(x2+halfH,x1+halfH)=(xt1>=-0.05)*(xt2>=-0.05)*function_Window2D(xt1/h1/(1-1000*eps),xt2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
if TYPE==110 % NONSYMMETRIC ON X1 WINDOW
win_fun1(x2+halfH,x1+halfH)=(xt1>=-0.05)*function_Window2D(xt1/h1/(1-1000*eps),xt2/h2/(1-1000*eps),window_type,sig_wind,beta,h2/h1); % weight
end
end
end
end
win_fun=win_fun1;
if (theta~=0)&(TYPE<100)
win_fun=imrotate(win_fun1,theta*180/pi,'nearest'); % use 'nearest' or 'bilinear' for different interpolation schemes ('bicubic'...?)
end
if (theta~=0)&(TYPE>=200)&(TYPE<300)
win_fun=imrotate(win_fun1,theta*180/pi,'bilinear'); % use 'nearest' or 'bilinear' for different interpolation schemes ('bicubic'...?)
end
if (theta~=0)&(TYPE>=300)
win_fun=imrotate(win_fun1,theta*180/pi,'bicubic'); % use 'nearest' or 'bilinear' for different interpolation schemes ('bicubic'...?)
end
% make the weight support a square
win_fun2=zeros(max(size(win_fun)));
win_fun2((max(size(win_fun))-size(win_fun,1))/2+1:max(size(win_fun))-((max(size(win_fun))-size(win_fun,1))/2),(max(size(win_fun))-size(win_fun,2))/2+1:max(size(win_fun))-((max(size(win_fun))-size(win_fun,2))/2))=win_fun;
win_fun=win_fun2;
%=====================================================================================================================================
%%%% rotated coordinates
H=-(size(win_fun,1)-1)/2:(size(win_fun,1)-1)/2;
halfH=(size(win_fun,1)+1)/2;
h_radious=halfH;
Hcos=H*cos(theta); Hsin=H*sin(theta);
%%%% Calculation of FI matrix
FI=zeros(number_of_polynomials);
i1=0;
for s1=H
i1=i1+1;
i2=0;
for s2=H
i2=i2+1;
x1=Hcos(s1+h_radious)-Hsin(s2+h_radious);
x2=Hsin(s1+h_radious)+Hcos(s2+h_radious);
phi=sqrt(win_fun(s2+halfH,s1+halfH))*(prod(((ones(number_of_polynomials,1)*[x1 x2]).^index_polynomials(:,1:2)),2)./prod(gamma(index_polynomials(:,1:2)+1),2).*(-ones(number_of_polynomials,1)).^index_polynomials(:,3));
FI=FI+phi*phi';
end % end of s2
end % end of s1
%FI_inv=((FI+1*eps*eye(size(FI)))^(-1)); % invert FI matrix
FI_inv=pinv(FI); % invert FI matrix (using pseudoinverse)
G1=zeros([size(H,2) size(H,2) number_of_polynomials]);
%%%% Calculation of mask
i1=0;
for s1=H
i1=i1+1;
i2=0;
for s2=H
i2=i2+1;
x1=Hcos(s1+h_radious)-Hsin(s2+h_radious);
x2=Hsin(s1+h_radious)+Hcos(s2+h_radious);
phi=FI_inv*win_fun(s2+halfH,s1+halfH)*(prod(((ones(number_of_polynomials,1)*[x1 x2]).^index_polynomials(:,1:2)),2)./prod(gamma(index_polynomials(:,1:2)+1),2).*(-ones(number_of_polynomials,1)).^index_polynomials(:,3));
G(i2,i1,1)=phi(1); % Function Est
G1(i2,i1,:)=phi(:)'; % Function est & Der est on X Y etc...
end % end of s1
end % end of s2
%keyboard |
github | zongwave/IPASS-master | bfilter.m | .m | IPASS-master/Bilateral/bfilter.m | 4,290 | utf_8 | 14e396b5cb0f534b1709d7c6fc512e35 | % Douglas R. Lanman, Brown University, September 2006.
% [email protected], http://mesh.brown.edu/dlanman
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pre-process input and select appropriate filter.
function B = bfilter(A,w,sigma)
% Verify that the input image exists and is valid.
if ~exist('A','var') || isempty(A)
error('Input image A is undefined or invalid.');
end
if ~isfloat(A) || ~sum([1,3] == size(A,3)) || ...
min(A(:)) < 0 || max(A(:)) > 1
error(['Input image A must be a double precision ',...
'matrix of size NxMx1 or NxMx3 on the closed ',...
'interval [0,1].']);
end
% Verify bilateral filter window size.
if ~exist('w','var') || isempty(w) || ...
numel(w) ~= 1 || w < 1
w = 5;
end
w = ceil(w);
% Verify bilateral filter standard deviations.
if ~exist('sigma','var') || isempty(sigma) || ...
numel(sigma) ~= 2 || sigma(1) <= 0 || sigma(2) <= 0
sigma = [3 0.1];
end
% Apply either grayscale or color bilateral filtering.
if size(A,3) == 1
B = bfltGray(A,w,sigma(1),sigma(2));
else
B = bfltColor(A,w,sigma(1),sigma(2));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements bilateral filtering for grayscale images.
function B = bfltGray(A,w,sigma_d,sigma_r)
% Pre-compute Gaussian distance weights.
[X,Y] = meshgrid(-w:w,-w:w);
%????????e.g.
% [x,y]=meshgrid(-1:1,-1:1)
%
% x =
%
% -1 0 1
% -1 0 1
% -1 0 1
%
%
% y =
%
% -1 -1 -1
% 0 0 0
% 1 1 1
%??????
G = exp(-(X.^2+Y.^2)/(2*sigma_d^2));
% Create waitbar.
h = waitbar(0,'Applying bilateral filter...');
set(h,'Name','Bilateral Filter Progress');
% Apply bilateral filter.
%?????H ??????G ??????????F
dim = size(A);
B = zeros(dim);
for i = 1:dim(1)
for j = 1:dim(2)
% Extract local region.
iMin = max(i-w,1);
iMax = min(i+w,dim(1));
jMin = max(j-w,1);
jMax = min(j+w,dim(2));
%????????????(iMin:iMax,jMin:jMax)
I = A(iMin:iMax,jMin:jMax);%????????????I
% Compute Gaussian intensity weights.
H = exp(-(I-A(i,j)).^2/(2*sigma_r^2));
% Calculate bilateral filter response.
F = H.*G((iMin:iMax)-i+w+1,(jMin:jMax)-j+w+1);
B(i,j) = sum(F(:).*I(:))/sum(F(:));
end
waitbar(i/dim(1));
end
% Close waitbar.
close(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements bilateral filter for color images.
function B = bfltColor(A,w,sigma_d,sigma_r)
% Convert input sRGB image to CIELab color space.
% if exist('applycform','file')
% A = applycform(A,makecform('srgb2lab'));
% else
% A = colorspace('Lab<-RGB',A);
% end
A = zjRGB2Lab(A);
% Pre-compute Gaussian domain weights.
[X,Y] = meshgrid(-w:w,-w:w);
G = exp(-(X.^2+Y.^2)/(2*sigma_d^2));
% Rescale range variance (using maximum luminance).
sigma_r = 100*sigma_r;
% Create waitbar.
% h = waitbar(0,'Applying bilateral filter...');
% set(h,'Name','Bilateral Filter Progress');
% Apply bilateral filter.
dim = size(A);
B = zeros(dim);
for i = 1:dim(1)
for j = 1:dim(2)
% Extract local region.
iMin = max(i-w,1);
iMax = min(i+w,dim(1));
jMin = max(j-w,1);
jMax = min(j+w,dim(2));
I = A(iMin:iMax,jMin:jMax,:);
% Compute Gaussian range weights.
dL = I(:,:,1)-A(i,j,1);
da = I(:,:,2)-A(i,j,2);
db = I(:,:,3)-A(i,j,3);
H = exp(-(dL.^2+da.^2+db.^2)/(2*sigma_r^2));
% Calculate bilateral filter response.
F = H.*G((iMin:iMax)-i+w+1,(jMin:jMax)-j+w+1);
norm_F = sum(F(:));
B(i,j,1) = sum(sum(F.*I(:,:,1)))/norm_F;
B(i,j,2) = sum(sum(F.*I(:,:,2)))/norm_F;
B(i,j,3) = sum(sum(F.*I(:,:,3)))/norm_F;
end
% waitbar(i/dim(1));
end
% Convert filtered image back to sRGB color space.
% if exist('applycform','file')
% B = applycform(B,makecform('lab2srgb'));
% else
% B = colorspace('RGB<-Lab',B);
% end
B=zjLab2RGB(B);
% Close waitbar.
% close(h); |
github | zongwave/IPASS-master | main_3DNR.m | .m | IPASS-master/3DNR/main_3DNR.m | 6,682 | utf_8 | f177462edf06fa0a49921cb8a9670c37 | function main_3DNR()
clear;
clc;
close all;
[filename, pathname, filterindex] = uigetfile( ...
{ '*.bmp','Bitmap files (*.bmp)'; ...
'*.png','PNG files (*.png)'; ...
'*.jpg','JPEG files (*.jpg)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick a file', ...
'MultiSelect', 'on');
if (iscell(filename) == 0);
if filename == 0;
number_of_images = 0;
else
number_of_images = 1;
end
else
number_of_images = length(filename);
end
fullfilename = fullfile(pathname, filename);
if number_of_images == 1
[pathstr, name, ext] = fileparts(fullfilename);
else
[pathstr, name, ext] = fileparts(fullfilename{number_of_images});
end
sum_frame = 0;
if number_of_images > 1
for i = 1: number_of_images
reference{i} = im2double(imread(fullfile(pathname, filename{i})));
sum_frame = sum_frame + reference{i};
end
observed = reference{number_of_images};
average_rgb_frame = sum_frame / number_of_images;
else
reference{1} = im2double(imread(fullfile(pathname, filename)));
observed = reference{1};
average_rgb_frame = reference{1};
end
[image_height, image_width, channel] = size(observed);
fname = [pathstr '/' name '_' mat2str(number_of_images) '_frames_averaged.bmp'];
imwrite(average_rgb_frame, fname);
%
% blocks from referenced frame
%
ref_block_x_radius = 1;
ref_block_y_radius = 1;
ref_block_x_count = 2 * ref_block_x_radius + 1;
ref_block_y_count = 2 * ref_block_y_radius + 1;
ref_block_width = 4;
ref_block_height = 4;
block_x_count = ceil(image_width / ref_block_width);
block_y_count = ceil(image_height / ref_block_height);
for ref_y_block = 0 : ref_block_y_count - 1
for ref_x_block = 1 : ref_block_x_count
ref_block_x_index{ref_x_block + ref_y_block * ref_block_x_count} = (ref_x_block - 1 - ref_block_x_radius);
ref_block_y_index{ref_x_block + ref_y_block * ref_block_x_count} = (ref_y_block - ref_block_y_radius);
end
end
for image_y_start = 1 : ref_block_height : image_height - ref_block_height + 1
for image_x_start = 1 : ref_block_width : image_width - ref_block_width + 1
block_x_index = ceil(image_x_start / ref_block_width);
block_y_index = ceil(image_y_start / ref_block_height);
for ref_y_block = 0 : ref_block_y_count - 1
for ref_x_block = 1 : ref_block_x_count
block_x_start{ref_x_block + ref_y_block * ref_block_x_count} = image_x_start + ref_block_width * ref_block_x_index{ref_x_block + ref_y_block * ref_block_x_count};
block_y_start{ref_x_block + ref_y_block * ref_block_x_count} = image_y_start + ref_block_height * ref_block_y_index{ref_x_block + ref_y_block * ref_block_x_count};
end
end
for block_index = 1 : ref_block_x_count * ref_block_y_count
if (block_x_start{block_index} < 1)
block_x_start{block_index} = 1;
end
if (block_y_start{block_index} < 1)
block_y_start{block_index} = 1;
end
if (image_width - block_x_start{block_index} < ref_block_width - 1)
block_x_start{block_index} = image_width - ref_block_width + 1;
end
if (image_height - block_y_start{block_index} < ref_block_height - 1)
block_y_start{block_index} = image_height - ref_block_height + 1;
end
end
for image_index = 1 : number_of_images
% figure();
for block_index = 1 : ref_block_x_count * ref_block_y_count
reference_blocks{image_index}{block_index} = reference{image_index}(block_y_start{block_index} : block_y_start{block_index} + ref_block_height - 1, block_x_start{block_index} : block_x_start{block_index} + ref_block_width - 1, :);
if (image_index == number_of_images) && (block_index == ref_block_y_radius * ref_block_x_count + ref_block_x_radius + 1)
current_block = reference_blocks{image_index}{block_index};
end
% subplot(ref_block_x_count, ref_block_y_count, block_index);
% imshow(reference_blocks{image_index}{block_index});
end
end
res_block = weighted_average(current_block, reference_blocks);
restored(image_y_start : image_y_start + ref_block_height - 1, image_x_start : image_x_start + ref_block_width - 1, :) = res_block;
end
end
figure();
subplot(2, 2, 1);
imshow(average_rgb_frame);
title(['Averaged image,' mat2str(number_of_images) ' number of images']);
subplot(2, 2, 2);
imshow(observed);
title('orignal image');
subplot(2, 2, 3);
imshow(restored);
title('3D denoise image');
fname_restored = [pathstr '/' name '_' mat2str(number_of_images) '_frames_restored.bmp'];
imwrite(restored, fname_restored);
subplot(2, 2, 4);
imshow(reference_blocks{number_of_images}{ref_block_x_count * ref_block_y_count});
end
function res_block = weighted_average(cur_block, ref_blocks)
image_count = length(ref_blocks);
block_count = length(ref_blocks{1});
weight_sum = 0;
[block_height, block_width, channel] = size(cur_block);
res_block = zeros(block_height, block_width, channel);
for image_index = 1 : image_count
for block_index = 1: block_count
dist = sum(sum( (ref_blocks{image_index}{block_index} - cur_block) .* (ref_blocks{image_index}{block_index} - cur_block) ));
MAG = (block_height * block_width) * ref_blocks{image_index}{block_index}(ceil(block_height/2), ceil(block_width/2)) - sum(sum(ref_blocks{image_index}{block_index}));
MAG = abs(MAG) / (block_height * block_width - 1);
if MAG < 0.5
alpha = 1;
else
alpha = 2;
end
weight = exp(-3.0 * dist(1, 1, :) * alpha);
weight_sum = weight_sum + weight;
res_block(:, :, 1) = res_block(:, :, 1) + ref_blocks{image_index}{block_index}(:, :, 1) .* weight(:, :, 1);
res_block(:, :, 2) = res_block(:, :, 2) + ref_blocks{image_index}{block_index}(:, :, 2) .* weight(:, :, 2);
res_block(:, :, 3) = res_block(:, :, 3) + ref_blocks{image_index}{block_index}(:, :, 3) .* weight(:, :, 3);
end
end
res_block(:, :, 1) = res_block(:, :, 1) ./ weight_sum(:, :, 1);
res_block(:, :, 2) = res_block(:, :, 2) ./ weight_sum(:, :, 2);
res_block(:, :, 3) = res_block(:, :, 3) ./ weight_sum(:, :, 3);
end
|
github | zongwave/IPASS-master | import_video.m | .m | IPASS-master/VideoStab/import_video.m | 1,568 | utf_8 | 4f3b5d25af12d202e844be7fb4c54d3f | % import_video.m - import original video
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [fullname, vid_frame, frame_count, frame_rate, duration, vid_width, vid_height] = import_video(file)
clc;
clear;
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{'*.mp4','MP4 files (*.mp4)'; ...
'*.mpg','MPEG files (*.mpg)'; ...
'*.mov','MOV files (*.mov)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick original shaky video file');
fullname = fullfile(pathname, filename);
vidObj = VideoReader(fullname);
frame_count = 0;
frame_rate = vidObj.FrameRate;
vid_height = vidObj.Height;
vid_width = vidObj.Width;
duration = vidObj.Duration;
figure();
title('Original Video');
currAxes = axes;
while hasFrame(vidObj)
vidFrame = readFrame(vidObj);
frame_count = frame_count + 1;
vid_frame(frame_count).cdata = vidFrame;
image(vid_frame(frame_count).cdata, 'Parent', currAxes);
currAxes.Visible = 'off';
pause(0.001/vidObj.FrameRate);
end
end
|
github | zongwave/IPASS-master | import_image_keypoints.m | .m | IPASS-master/VideoStab/import_image_keypoints.m | 1,618 | utf_8 | 4c6de30ee56355c8aaaf8c830b95763b | % import_image_keypoints.m - import image keypoints to do calibration
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [frame_count, frame_idx, p0, p1] = import_image_keypoints(file)
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{'*.log','LOG files (*.log)'; ...
'*.data','DATA files (*.bmp)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick keypoints file');
fid = fopen(fullfile(pathname, filename));
else
fid = fopen('keypoints.log');
end;
frewind(fid);
calib = textscan(fid, '%s %d %s %f %f %s', 'Delimiter', ',');
fclose(fid);
frame_idx = calib{1};
point_idx = calib{2};
x0 = calib{3};
y0 = calib{4};
x1 = calib{5};
y1 = calib{6};
point_count = size(point_idx);
for i=1:point_count(1)
fidx(i) = textscan(frame_idx{i}, '%*s %d');
px0(i) = textscan(x0{i}, '%*s %*s %*s %f');
py1(i) = textscan(y1{i}, '%f %*s %*s %*s %*s %*s');
end
frame_idx = cell2mat(fidx)';
frame_count = max(frame_idx);
x0 = cell2mat(px0)';
y1 = cell2mat(py1)';
p0 = double([ x0 y0 ]);
p1 = double([ x1 y1 ]);
end
|
github | zongwave/IPASS-master | import_camera_pose.m | .m | IPASS-master/VideoStab/import_camera_pose.m | 6,954 | utf_8 | f0fd1745dcac8421aaaae5600dc0f7e0 | % import_camera_pose.m - import camera pose data acquired from Gyroscope
% & Accelerometer
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [ts, translation, quatern] = import_camera_pose(file)
clear;
clc;
close all
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{ '*.csv','CSV files (*.csv)'; ...
'*.data','DATA files (*.data)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick Gyro & Acc 6-DOF file');
end
[pathstr, name, ext] = fileparts(filename)
if strcmp(ext, '.data')
fid = fopen(fullfile(pathname, filename));
csv_file = [pathname 'gyro_data.csv'];
else
fid = fopen('gyro.data');
end;
if strcmp(ext, '.csv')
format long
gyro_data = dlmread(fullfile(pathname, filename));
figure();
subplot(2, 3, 1);
plot(gyro_data(:, 1), 'r', 'LineWidth', 2);
hold on
plot(gyro_data(:, 2), 'g', 'LineWidth', 2);
hold on
plot(gyro_data(:, 3), 'b', 'LineWidth', 2);
hold on
plot(gyro_data(:, 4), 'k', 'LineWidth', 2);
hold on
title('Gyro Quaternion');
legend('X', 'Y', 'Z', 'W');
subplot(2, 3, 2);
plot(gyro_data(:, 5), 'r', 'LineWidth', 2);
hold on
plot(gyro_data(:, 6), 'g', 'LineWidth', 2);
hold on
plot(gyro_data(:, 7), 'b', 'LineWidth', 2);
hold on
title('Gyro Translation');
legend('X', 'Y', 'Z');
sample_count = size(gyro_data);
quatern = gyro_data(:, 1:4);
translation = gyro_data(:, 5:7);
ts = gyro_data(:, 8);
else
frewind(fid);
frame = textscan(fid, '%s %s %s %s %s', 'Delimiter',':');
fclose(fid);
timestamp = frame{3};
position = frame{4};
orientation = frame{5};
sample_count = size(timestamp);
for i=1:sample_count(1)
ts(i) = textscan(timestamp{i}, '%f');
end
ts = cell2mat(ts)';
d = diff(ts);
frame_gap = (d ./ min(d)) - 1;
display(['avg frame rate: ' num2str(1/mean(d))]);
display(['max frame rate: ' num2str(1/min(d))]);
display(['max frame gap: ' num2str(max(frame_gap))]);
display(['num frames dropped: ' num2str(sum(round(frame_gap)))]);
for i=1:sample_count(1)
translation{i} = textscan(position{i}, '%f %f %f', 'Delimiter', ',');
end
for i=1:sample_count(1)
trans_x(i) = (translation{i}{1});
trans_y(i) = (translation{i}{2});
trans_z(i) = (translation{i}{3});
end
translation = [trans_x; trans_y; trans_z]';
for i=1:sample_count(1)
orientation{i} = textscan(orientation{i}, '%f %f %f %f', 'Delimiter', ',');
end
for i=1:sample_count(1)
orient_x(i) = (orientation{i}{1});
orient_y(i) = (orientation{i}{2});
orient_z(i) = (orientation{i}{3});
orient_w(i) = (orientation{i}{4});
end
quatern = [orient_x; orient_y; orient_z; orient_w]';
if strcmp(ext, '.data')
dlmwrite(csv_file, [quatern translation ts], 'precision', '%12.6f');
end
figure();
subplot(2, 3, 1);
plot(trans_x, 'r', 'LineWidth', 2);
hold on
plot(trans_y, 'g', 'LineWidth', 2);
hold on
plot(trans_z, 'b', 'LineWidth', 2);
hold on
title('Gyro Translation');
legend('X', 'Y', 'Z');
subplot(2, 3, 2);
plot(orient_x, 'r', 'LineWidth', 2);
hold on
plot(orient_y, 'g', 'LineWidth', 2);
hold on
plot(orient_z, 'b', 'LineWidth', 2);
hold on
plot(orient_w, 'k', 'LineWidth', 2);
hold on
title('Gyro Orientation');
legend('X', 'Y', 'Z', 'W');
end
eulerAngle = zeros(3, sample_count(1));
rotAxis = zeros(4, sample_count(1));
rotMatrix = zeros(3, 3, sample_count(1));
% %% Quaternion to Matrix
convertType = int32(0);
convert_rotation(convertType, quatern', eulerAngle, rotAxis, rotMatrix);
points = ones(sample_count(1), 3);
for i=1:size(rotMatrix, 3)
points(i, :) = rotMatrix(:, :, i) * points(i, :)';
end
subplot(2, 3, 3);
plot3(points(:, 1), points(:, 2), points(:, 3), 'r', 'LineWidth', 2);
hold on
title('Transform Points');
xlabel('X', 'Fontsize', 15);
ylabel('Y', 'Fontsize', 15);
zlabel('Z', 'Fontsize', 15);
% %% Quaternion to Euler angle
convertType = int32(1);
convert_rotation(convertType, quatern', eulerAngle, rotAxis, rotMatrix);
eulerAngle = (eulerAngle * 180 / 3.1415926);
subplot(2, 3, 4);
plot(eulerAngle(1, :), 'r', 'LineWidth', 2);
hold on
plot(eulerAngle(2, :), 'g', 'LineWidth', 2);
hold on
plot(eulerAngle(3, :), 'b', 'LineWidth', 2);
hold on
title('Euler Angles');
legend('Euler Angle X(roll)', 'Euler Angle Y(pitch)', 'Euler Angle Z(yaw)');
% %% Quaternion to Rotation Axis
convertType = int32(2);
convert_rotation(convertType, quatern', eulerAngle, rotAxis, rotMatrix);
subplot(2, 3, 5);
plot(rotAxis(1, :), 'r', 'LineWidth', 2);
hold on
plot(rotAxis(2, :), 'g', 'LineWidth', 2);
hold on
plot(rotAxis(3, :), 'b', 'LineWidth', 2);
hold on
title('Rotation Axis');
legend('Rotation Axis X', 'Rotation Axis Y', 'Rotation Axis Z');
subplot(2, 3, 6);
plot(rotAxis(4, :), 'k', 'LineWidth', 2);
hold on
legend('Rotation Axis degree');
%%% Test by SpinCalc
%% Quaternion to Matrix
% rotMatrix_SC = SpinCalc('QtoDCM', quatern, 0.01, 1);
% points = ones(ts_count(1), 3);
% for i=1:size(rotMatrix_SC, 3)
% points(i, :) = rotMatrix_SC(:, :, i) * points(i, :)';
% end
%
% figure();
% subplot(2, 3, 3);
% plot3(points(:, 1), points(:, 2), points(:, 3), 'r', 'LineWidth', 2);
% hold on
% title('SpinCalc Transform Points');
% xlabel('X', 'Fontsize', 15);
% ylabel('Y', 'Fontsize', 15);
% zlabel('Z', 'Fontsize', 15);
% %% Quaternion to Euler angles
% eulerAngle_SC = SpinCalc('QtoEA123', quatern, 0.01, 1);
% subplot(2, 3, 4);
% plot(eulerAngle_SC(:, 1), 'r', 'LineWidth', 2);
% hold on
% plot(eulerAngle_SC(:, 2), 'g', 'LineWidth', 2);
% hold on
% plot(eulerAngle_SC(:, 3), 'b', 'LineWidth', 2);
% hold on
% title('SpinCalc Euler Angles');
% legend('Euler Angles X', 'Euler Angles Y', 'Euler Angles Z');
% %% Quternion to rotation vector
% rotAxis_SC = SpinCalc('QtoEV', quatern, 0.01, 1);
% subplot(2, 3, 5);
% plot(rotAxis_SC(:, 1), 'r', 'LineWidth', 2);
% hold on
% plot(rotAxis_SC(:, 2), 'g', 'LineWidth', 2);
% hold on
% plot(rotAxis_SC(:, 3), 'b', 'LineWidth', 2);
% hold on
% title('SpinCalc Rotation Axis');
% legend('Rotation Axis X', 'Rotation Axis Y', 'Rotation Axis Z');
% subplot(2, 3, 6);
% plot(rotAxis_SC(:, 4), 'k', 'LineWidth', 2);
% hold on
% legend('Rotation Axis degree');
%
% end
|
github | zongwave/IPASS-master | analyze_projective2d.m | .m | IPASS-master/VideoStab/analyze_projective2d.m | 3,766 | utf_8 | 34bcc79f60bb6e618bdf8dbb62dfb619 | % analyze_projective2d.m - Plot projection matrix to analyze
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function analyze_projective2d(file)
clc;
clear;
close all;
if (nargin < 1)
[filename, pathname, filterindex] = uigetfile( ...
{'*.mat','MAT files (*.mat)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick projective 2D file', ...
'MultiSelect', 'on');
if (iscell(filename) == 0)
if filename == 0
num_of_mat = 0;
else
num_of_mat = 1;
end
else
num_of_mat = length(filename);
end
for i=1: num_of_mat
if (iscell(filename) == 0)
rot_mat = load(fullfile(pathname, filename));
else
rot_mat = load(fullfile(pathname, filename{i}));
end
field = fieldnames(rot_mat);
if strcmp(field, 'gyro_mat')
projective2d = rot_mat.gyro_mat;
curve{i} = 'Gyro 3DOF';
elseif strcmp(field, 'rot_mat')
projective2d = rot_mat.rot_mat();
curve{i} = 'Optical Flow';
end
trans_x = projective2d(1, 3, :);
t_x{i} = trans_x(:);
trans_y = projective2d(2, 3, :);
t_y{i} = trans_y(:);
curve_len{i} = size(t_y{i}, 1);
scale_x = projective2d(1, 1, :);
s_x{i} = scale_x(:);
scale_y = projective2d(2, 2, :);
s_y{i} = scale_y(:);
rot_x = projective2d(1, 2, :);
r_x{i} = rot_x(:);
rot_y = projective2d(2, 1, :);
r_y{i} = rot_y(:);
proj_x = projective2d(3, 1, :);
p_x{i} = proj_x(:);
proj_y = projective2d(3, 2, :);
p_y{i} = proj_y(:);
homo_w = projective2d(3, 3, :);
h_w{i} = homo_w(:);
end
if curve_len{1} > 270
curve_step = 3;
elseif curve_len{1} > 180
curve_step = 2;
else
curve_step = 1;
end
figure();
subplot(3, 3, 1);
for i=1: num_of_mat
plot(s_x{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' S_X'], [curve{2} ' S_X']);
subplot(3, 3, 2);
for i=1: num_of_mat
plot(r_x{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' R_X'], [curve{2} ' R_X']);
subplot(3, 3, 3);
for i=1: num_of_mat
plot(t_x{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' T_X'], [curve{2} ' T_X']);
subplot(3, 3, 4);
for i=1: num_of_mat
plot(r_y{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' R_Y'], [curve{2} ' R_Y']);
subplot(3, 3, 5);
for i=1: num_of_mat
plot(s_y{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' S_Y'], [curve{2} ' S_Y']);
subplot(3, 3, 6);
for i=1: num_of_mat
plot(t_y{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' T_Y'], [curve{2} ' T_Y']);
subplot(3, 3, 7);
for i=1: num_of_mat
plot(p_x{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' P_X'], [curve{2} ' P_X']);
subplot(3, 3, 8);
for i=1: num_of_mat
plot(p_y{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' P_Y'], [curve{2} ' P_Y']);
subplot(3, 3, 9);
for i=1: num_of_mat
plot(h_w{i}(1: curve_step: curve_len{i}), 'LineWidth', 2);
hold on
end
legend([curve{1} ' H_W'], [curve{2} ' H_W']);
end
|
github | zongwave/IPASS-master | import_camera_intrinsics.m | .m | IPASS-master/VideoStab/import_camera_intrinsics.m | 2,899 | utf_8 | 6c47f85b592721490e586123d7eec883 | % import_camera_intrinsics.m - import camera calibration data to get
% intrinsic parameters
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [fc, cc, alpha_c, kc, fc_error, cc_error, alpha_c_error, kc_error, frame_size] = import_camera_intrinsics(file)
clc;
clear;
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{'*.mat','MAT files (*.mat)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick camera calibration file');
calib_result = load(fullfile(pathname, filename));
field = fieldnames(calib_result);
% Intrinsic Camera Parameters
% Color CameraIntrinsics by Tango API
% image_width: 1920, image_height :1080,
% fx: 1750.517953, fy: 1752.121844,
% cx: 961.158431, cy: 543.400556,
% image_plane_distance: 1.823456.
% Color Camera Frame with respect to IMU Frame,
% Position: 0.046403, -0.007203, -0.003940.
% Orientation: 0.007697, 0.999966, -0.002460, 0.001833
%-- Focal length:
%fc = [ 1754.975680239204800 ; 1751.235395306768200 ];
fc = getfield(calib_result, 'fc');
% fc = [1750.517953; 1752.121844];
%-- Principal point:
%cc = [ 980.930704001504180 ; 533.190157376837190 ];
cc = getfield(calib_result, 'cc');
% cc = [961.158431; 543.400556];
%-- Skew coefficient:
%alpha_c = 0.000000000000000;
alpha_c = getfield(calib_result, 'alpha_c');
%-- Distortion coefficients:
%kc = [ 0.125138728392555 ; -0.370741771854929 ; -0.002331438922038 ; 0.005065576610383 ; 0.000000000000000 ];
kc = getfield(calib_result, 'kc');
%-- Focal length uncertainty:
%fc_error = [ 44.984729995744409 ; 45.109724834116975 ];
fc_error = getfield(calib_result, 'fc_error');
%-- Principal point uncertainty:
%cc_error = [ 13.861062313971287 ; 8.157315653129363 ];
cc_error = getfield(calib_result, 'cc_error');
%-- Skew coefficient uncertainty:
%alpha_c_error = 0.000000000000000;
alpha_c_error = getfield(calib_result, 'alpha_c_error');
%-- Distortion coefficients uncertainty:
%kc_error = [ 0.016094474616848 ; 0.082081733828857 ; 0.001497247209278 ; 0.002034878656146 ; 0.000000000000000 ];
kc_error = getfield(calib_result, 'kc_error');
%-- Image size:
%nx = 1920;
%ny = 1080;
nx = getfield(calib_result, 'nx');
ny = getfield(calib_result, 'ny');
frame_size = [nx; ny];
end
|
github | zongwave/IPASS-master | video_stabilization.m | .m | IPASS-master/VideoStab/video_stabilization.m | 3,444 | utf_8 | 63a76012bd6a73fb8e6c53ea0bde733f | % video_stabilizaton.m - main function to launch video stabilization
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function video_stabilization(file)
clc
clear
close all
if (nargin < 1)
[filename, pathname] = uigetfile( ...
{'*.mat','Mat files (*.mat)'; ...
'*.data','DATA files (*.data)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick pre-calculated rotation Matrix file');
if filename ~= 0
proj_mat = load(fullfile(pathname, filename));
field = fieldnames(proj_mat);
homo_mat = cell2mat(getfield(proj_mat, cell2mat(field)));
homo_mat = reshape(homo_mat, 3, 3, size(homo_mat, 2)/3);
if strcmp(field, 'homo_mat')
video_stab_interface(0, 0, 0, 0, 0, 0, homo_mat);
rot_mat = homo_mat;
matrix_type = 'Optical Flow Motion Stab';
else
rot_mat = homo_mat;
matrix_type = 'Optical Flow';
end
else
% Intrinsic Camera Parameters
[fc, cc, alpha_c, kc, fc_error, cc_error, alpha_c_error, kc_error, frame_size] = import_camera_intrinsics();
% Extrinsic Camera Parameters
[gyro_ts, gyro_pos, gyro_quat] = import_camera_pose();
frame_ts = gyro_ts;
readout_time = 0;
gyro_delay = 0;
gyro_drifft = 0;
rot_mat = zeros(3, 3, size(gyro_ts, 1));
calib_param = [fc; cc; alpha_c; readout_time; gyro_delay; gyro_drifft];
video_stab_interface(frame_ts, frame_size, gyro_pos', gyro_quat', gyro_ts, calib_param, rot_mat);
matrix_type = 'Gyro 3DOF';
end
[vid_name, vid_frame, frame_count, frame_rate, duration, vid_width, vid_height] = import_video();
if filename ~= 0
save([vid_name '_' matrix_type '_rot.mat'], 'rot_mat');
else
gyro_mat = rot_mat(:, :, 1:frame_count);
save([vid_name '_' matrix_type '_rot.mat'], 'gyro_mat');
end
mat_size = size(rot_mat);
if max(mat_size) < frame_count
warp_count = max(mat_size);
else
warp_count = frame_count;
end
vidObj = VideoWriter([vid_name '_stabilized_' matrix_type '.mp4'], 'MPEG-4');
open(vidObj);
crop_ratio = 0.05;
cropped_x = vid_width*crop_ratio;
cropped_y = vid_height*crop_ratio;
cropped_width = vid_width*(1-2*crop_ratio);
cropped_height = vid_height*(1-2*crop_ratio);
figure();
title(['Stabilized Video: ' matrix_type]);
currAxes = axes;
for i=1: frame_count
if i <= warp_count
warp_idx = i;
else
warp_idx = warp_count;
end
warp_mat = projective2d(inv(rot_mat(:, :, warp_idx)'));
% rot_mat(:, :, warp_idx)
outputView = imref2d([vid_height, vid_width]);
stabilized = imwarp(vid_frame(i).cdata, warp_mat, 'OutputView', outputView);
cropped = imcrop(stabilized, [cropped_x, cropped_y, cropped_width, cropped_height]);
scaled = imresize(cropped, [vid_height, vid_width]);
image(scaled, 'Parent', currAxes);
currAxes.Visible = 'off';
pause(1/frame_rate);
writeVideo(vidObj, scaled)
end
close(vidObj);
end
|
github | zongwave/IPASS-master | sensor_calibraion.m | .m | IPASS-master/VideoStab/sensor_calibraion.m | 2,075 | utf_8 | 87988e8b55e6952551ee3fa327ddeba4 | % sensor_calibration.m - Optimal camera & gyrocope calibration parameters
% by build in function 'fminunc'
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Author: Zong Wei <[email protected]>
%
function [optimal_calib] = sensor_calibraion()
clc;
clear;
close all;
[frame_count, frame_idx, p0, p1] = import_image_keypoints();
[gyro_time, gyro_pos, gyro_quat] = import_camera_pose();
frame_time = gyro_time;
% Intrinsic Camera Parameters
[fc, cc, alpha_c, kc, fc_error, cc_error, alpha_c_error, kc_error, frame_size] = import_camera_intrinsics();
% focal_x; focal_y; orig_x; orig_y; readout_time; gyro_delay; gyro_drifft;
readout_time = 0;
gyro_delay = 0;
gyro_drifft = 0;
init_calib = [fc; cc; alpha_c; readout_time; gyro_delay; gyro_drifft];
rot_mat = zeros(3, 3, size(gyro_quat, 1));
% optimal calibration parameters.
% Set options for fminunc
% options = optimset('GradObj', 'on', 'MaxIter', 400);
options = optimoptions(@fminunc, ...
'Display','iter', ...
'Algorithm','quasi-newton', ...
'MaxFunctionEvaluations',8000);
% Run fminunc to obtain the optimal calibration parameter
optimal_calib = fminunc(@(calib_param)(cost_function(calib_param, ...
frame_idx, p0', p1', frame_time, frame_size, ...
gyro_pos', gyro_quat', gyro_time, ...
rot_mat)), ...
init_calib, options);
display(optimal_calib);
display(init_calib);
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.