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
|
lifeng9472/IBCCF-master
|
getVarReceptiveFields.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/+dagnn/@DagNN/getVarReceptiveFields.m
| 3,635 |
utf_8
|
6d61896e475e64e9f05f10303eee7ade
|
function rfs = getVarReceptiveFields(obj, var)
%GETVARRECEPTIVEFIELDS Get the receptive field of a variable
% RFS = GETVARRECEPTIVEFIELDS(OBJ, VAR) gets the receptivie fields RFS of
% all the variables of the DagNN OBJ into variable VAR. VAR is a variable
% name or index.
%
% RFS has one entry for each variable in the DagNN following the same
% format as has DAGNN.GETRECEPTIVEFIELDS(). For example, RFS(i) is the
% receptive field of the i-th variable in the DagNN into variable VAR. If
% the i-th variable is not a descendent of VAR in the DAG, then there is
% no receptive field, indicated by `rfs(i).size == []`. If the receptive
% field cannot be computed (e.g. because it depends on the values of
% variables and not just on the network topology, or if it cannot be
% expressed as a sliding window), then `rfs(i).size = [NaN NaN]`.
% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi. All rights reserved.
%
% This file is part of the VLFeat library and is made available under the
% terms of the BSD license (see the COPYING file).
if ~isnumeric(var)
var_n = obj.getVarIndex(var) ;
if isnan(var_n)
error('Variable %s not found.', var_n);
end
var = var_n;
end
nv = numel(obj.vars) ;
nw = numel(var) ;
rfs = struct('size', cell(nw, nv), 'stride', cell(nw, nv), 'offset', cell(nw,nv)) ;
for w = 1:numel(var)
rfs(w,var(w)).size = [1 1] ;
rfs(w,var(w)).stride = [1 1] ;
rfs(w,var(w)).offset = [1 1] ;
end
for l = obj.executionOrder
% visit all blocks and get their receptive fields
in = obj.layers(l).inputIndexes ;
out = obj.layers(l).outputIndexes ;
blockRfs = obj.layers(l).block.getReceptiveFields() ;
for w = 1:numel(var)
% find the receptive fields in each of the inputs of the block
for i = 1:numel(in)
for j = 1:numel(out)
rf = composeReceptiveFields(rfs(w, in(i)), blockRfs(i,j)) ;
rfs(w, out(j)) = resolveReceptiveFields([rfs(w, out(j)), rf]) ;
end
end
end
end
end
% -------------------------------------------------------------------------
function rf = composeReceptiveFields(rf1, rf2)
% -------------------------------------------------------------------------
if isempty(rf1.size) || isempty(rf2.size)
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
return ;
end
rf.size = rf1.stride .* (rf2.size - 1) + rf1.size ;
rf.stride = rf1.stride .* rf2.stride ;
rf.offset = rf1.stride .* (rf2.offset - 1) + rf1.offset ;
end
% -------------------------------------------------------------------------
function rf = resolveReceptiveFields(rfs)
% -------------------------------------------------------------------------
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
for i = 1:numel(rfs)
if isempty(rfs(i).size), continue ; end
if isnan(rfs(i).size)
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break ;
end
if isempty(rf.size)
rf = rfs(i) ;
else
if ~isequal(rf.stride,rfs(i).stride)
% incompatible geometry; this cannot be represented by a sliding
% window RF field and may denotes an error in the network structure
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break;
else
% the two RFs have the same stride, so they can be recombined
% the new RF is just large enough to contain both of them
a = rf.offset - (rf.size-1)/2 ;
b = rf.offset + (rf.size-1)/2 ;
c = rfs(i).offset - (rfs(i).size-1)/2 ;
d = rfs(i).offset + (rfs(i).size-1)/2 ;
e = min(a,c) ;
f = max(b,d) ;
rf.offset = (e+f)/2 ;
rf.size = f-e+1 ;
end
end
end
end
|
github
|
lifeng9472/IBCCF-master
|
rebuild.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/+dagnn/@DagNN/rebuild.m
| 3,243 |
utf_8
|
e368536d9e70c805d8424cdd6b593960
|
function rebuild(obj)
%REBUILD Rebuild the internal data structures of a DagNN object
% REBUILD(obj) rebuilds the internal data structures
% of the DagNN obj. It is an helper function used internally
% to update the network when layers are added or removed.
varFanIn = zeros(1, numel(obj.vars)) ;
varFanOut = zeros(1, numel(obj.vars)) ;
parFanOut = zeros(1, numel(obj.params)) ;
for l = 1:numel(obj.layers)
ii = obj.getVarIndex(obj.layers(l).inputs) ;
oi = obj.getVarIndex(obj.layers(l).outputs) ;
pi = obj.getParamIndex(obj.layers(l).params) ;
obj.layers(l).inputIndexes = ii ;
obj.layers(l).outputIndexes = oi ;
obj.layers(l).paramIndexes = pi ;
varFanOut(ii) = varFanOut(ii) + 1 ;
varFanIn(oi) = varFanIn(oi) + 1 ;
parFanOut(pi) = parFanOut(pi) + 1 ;
end
[obj.vars.fanin] = tolist(num2cell(varFanIn)) ;
[obj.vars.fanout] = tolist(num2cell(varFanOut)) ;
if ~isempty(parFanOut)
[obj.params.fanout] = tolist(num2cell(parFanOut)) ;
end
% dump unused variables
keep = (varFanIn + varFanOut) > 0 ;
obj.vars = obj.vars(keep) ;
varRemap = cumsum(keep) ;
% dump unused parameters
keep = parFanOut > 0 ;
obj.params = obj.params(keep) ;
parRemap = cumsum(keep) ;
% update the indexes to account for removed layers, variables and parameters
for l = 1:numel(obj.layers)
obj.layers(l).inputIndexes = varRemap(obj.layers(l).inputIndexes) ;
obj.layers(l).outputIndexes = varRemap(obj.layers(l).outputIndexes) ;
obj.layers(l).paramIndexes = parRemap(obj.layers(l).paramIndexes) ;
obj.layers(l).block.layerIndex = l ;
end
% update the variable and parameter names hash maps
obj.varNames = cell2struct(num2cell(1:numel(obj.vars)), {obj.vars.name}, 2) ;
obj.paramNames = cell2struct(num2cell(1:numel(obj.params)), {obj.params.name}, 2) ;
obj.layerNames = cell2struct(num2cell(1:numel(obj.layers)), {obj.layers.name}, 2) ;
% determine the execution order again (and check for consistency)
obj.executionOrder = getOrder(obj) ;
% --------------------------------------------------------------------
function order = getOrder(obj)
% --------------------------------------------------------------------
hops = cell(1, numel(obj.vars)) ;
for l = 1:numel(obj.layers)
for v = obj.layers(l).inputIndexes
hops{v}(end+1) = l ;
end
end
order = zeros(1, numel(obj.layers)) ;
for l = 1:numel(obj.layers)
if order(l) == 0
order = dagSort(obj, hops, order, l) ;
end
end
if any(order == -1)
warning('The network graph contains a cycle') ;
end
[~,order] = sort(order, 'descend') ;
% --------------------------------------------------------------------
function order = dagSort(obj, hops, order, layer)
% --------------------------------------------------------------------
if order(layer) > 0, return ; end
order(layer) = -1 ; % mark as open
n = 0 ;
for o = obj.layers(layer).outputIndexes ;
for child = hops{o}
if order(child) == -1
return ;
end
if order(child) == 0
order = dagSort(obj, hops, order, child) ;
end
n = max(n, order(child)) ;
end
end
order(layer) = n + 1 ;
% --------------------------------------------------------------------
function varargout = tolist(x)
% --------------------------------------------------------------------
[varargout{1:numel(x)}] = x{:} ;
|
github
|
lifeng9472/IBCCF-master
|
print.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/+dagnn/@DagNN/print.m
| 15,032 |
utf_8
|
7da4e68e624f559f815ee3076d9dd966
|
function str = print(obj, inputSizes, varargin)
%PRINT Print information about the DagNN object
% PRINT(OBJ) displays a summary of the functions and parameters in the network.
% STR = PRINT(OBJ) returns the summary as a string instead of printing it.
%
% PRINT(OBJ, INPUTSIZES) where INPUTSIZES is a cell array of the type
% {'input1nam', input1size, 'input2name', input2size, ...} prints
% information using the specified size for each of the listed inputs.
%
% PRINT(___, 'OPT', VAL, ...) accepts the following options:
%
% `All`:: false
% Display all the information below.
%
% `Layers`:: '*'
% Specify which layers to print. This can be either a list of
% indexes, a cell array of array names, or the string '*', meaning
% all layers.
%
% `Parameters`:: '*'
% Specify which parameters to print, similar to the option above.
%
% `Variables`:: []
% Specify which variables to print, similar to the option above.
%
% `Dependencies`:: false
% Whether to display the dependency (geometric transformation)
% of each variables from each input.
%
% `Format`:: 'ascii'
% Choose between `ascii`, `latex`, `csv`, 'digraph', and `dot`.
% The first three format print tables; `digraph` uses the plot function
% for a `digraph` (supported in MATLAB>=R2015b) and the last one
% prints a graph in `dot` format. In case of zero outputs, it
% attmepts to compile and visualise the dot graph using `dot` command
% and `start` (Windows), `display` (Linux) or `open` (Mac OSX) on your system.
% In the latter case, all variables and layers are included in the
% graph, regardless of the other parameters.
%
% `FigurePath`:: 'tempname.pdf'
% Sets the path where any generated `dot` figure will be saved. Currently,
% this is useful only in combination with the format `dot`.
% By default, a unique temporary filename is used (`tempname`
% is replaced with a `tempname()` call). The extension specifies the
% output format (passed to dot as a `-Text` parameter).
% If not extension provided, PDF used by default.
% Additionally, stores the .dot file used to generate the figure to
% the same location.
%
% `dotArgs`:: ''
% Additional dot arguments. E.g. '-Gsize="7"' to generate a smaller
% output (for a review of the network structure etc.).
%
% `MaxNumColumns`:: 18
% Maximum number of columns in each table.
%
% See also: DAGNN, DAGNN.GETVARSIZES().
if nargin > 1 && ischar(inputSizes)
% called directly with options, skipping second argument
varargin = {inputSizes, varargin{:}} ;
inputSizes = {} ;
end
opts.all = false ;
opts.format = 'ascii' ;
opts.figurePath = 'tempname.pdf' ;
opts.dotArgs = '';
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.layers = '*' ;
opts.parameters = [] ;
opts.variables = [] ;
if opts.all || nargin > 1
opts.variables = '*' ;
end
if opts.all
opts.parameters = '*' ;
end
opts.memory = true ;
opts.dependencies = opts.all ;
opts.maxNumColumns = 18 ;
opts = vl_argparse(opts, varargin) ;
if nargin == 1, inputSizes = {} ; end
varSizes = obj.getVarSizes(inputSizes) ;
paramSizes = cellfun(@size, {obj.params.value}, 'UniformOutput', false) ;
str = {''} ;
if strcmpi(opts.format, 'dot')
str = printDot(obj, varSizes, paramSizes, opts) ;
if nargout == 0
displayDot(str, opts) ;
end
return ;
end
if strcmpi(opts.format,'digraph')
str = printdigraph(obj, varSizes) ;
return ;
end
if ~isempty(opts.layers)
table = {'func', '-', 'type', 'inputs', 'outputs', 'params', 'pad', 'stride'} ;
for l = select(obj, 'layers', opts.layers)
layer = obj.layers(l) ;
table{l+1,1} = layer.name ;
table{l+1,2} = '-' ;
table{l+1,3} = player(class(layer.block)) ;
table{l+1,4} = strtrim(sprintf('%s ', layer.inputs{:})) ;
table{l+1,5} = strtrim(sprintf('%s ', layer.outputs{:})) ;
table{l+1,6} = strtrim(sprintf('%s ', layer.params{:})) ;
if isprop(layer.block, 'pad')
table{l+1,7} = pdims(layer.block.pad) ;
else
table{l+1,7} = 'n/a' ;
end
if isprop(layer.block, 'stride')
table{l+1,8} = pdims(layer.block.stride) ;
else
table{l+1,8} = 'n/a' ;
end
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.parameters)
table = {'param', '-', 'dims', 'mem', 'fanout'} ;
for v = select(obj, 'params', opts.parameters)
table{v+1,1} = obj.params(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(paramSizes{v}) ;
table{v+1,4} = pmem(prod(paramSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.params(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.variables)
table = {'var', '-', 'dims', 'mem', 'fanin', 'fanout'} ;
for v = select(obj, 'vars', opts.variables)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(varSizes{v}) ;
table{v+1,4} = pmem(prod(varSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.vars(v).fanin) ;
table{v+1,6} = sprintf('%d',obj.vars(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.memory
paramMem = sum(cellfun(@getMem, paramSizes)) ;
varMem = sum(cellfun(@getMem, varSizes)) ;
table = {'params', 'vars', 'total'} ;
table{2,1} = pmem(paramMem) ;
table{2,2} = pmem(varMem) ;
table{2,3} = pmem(paramMem + varMem) ;
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.dependencies
% print variable to input dependencies
inputs = obj.getInputs() ;
rfs = obj.getVarReceptiveFields(inputs) ;
for i = 1:size(rfs,1)
table = {sprintf('rf in ''%s''', inputs{i}), '-', 'size', 'stride', 'offset'} ;
for v = 1:size(rfs,2)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(rfs(i,v).size) ;
table{v+1,4} = pdims(rfs(i,v).stride) ;
table{v+1,5} = pdims(rfs(i,v).offset) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
end
% finish
str = horzcat(str{:}) ;
if nargout == 0,
fprintf('%s',str) ;
clear str ;
end
end
% -------------------------------------------------------------------------
function str = printtable(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = printtablechunk(opts, table(:, [1 sel])) ;
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function str = printtablechunk(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
switch opts.format
case 'ascii'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
case 'latex'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1}= sprintf('\\end{tabular}\n') ;
case 'csv'
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds,', sizes(j)) ;
str{end+1} = sprintf(fmt, ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
otherwise
error('Uknown format %s', opts.format) ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
end
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(isnan(x))
s = 'n/a' ;
return ;
end
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
end
% -------------------------------------------------------------------------
function x = player(x)
% -------------------------------------------------------------------------
if numel(x) < 7, return ; end
if x(1:6) == 'dagnn.', x = x(7:end) ; end
end
% -------------------------------------------------------------------------
function m = getMem(sz)
% -------------------------------------------------------------------------
m = prod(sz) * 4 ;
if isnan(m), m = 0 ; end
end
% -------------------------------------------------------------------------
function sel = select(obj, type, pattern)
% -------------------------------------------------------------------------
if isnumeric(pattern)
sel = pattern ;
else
if isstr(pattern)
if strcmp(pattern, '*')
sel = 1:numel(obj.(type)) ;
return ;
else
pattern = {pattern} ;
end
end
sel = find(cellfun(@(x) any(strcmp(x, pattern)), {obj.(type).name})) ;
end
end
% -------------------------------------------------------------------------
function h = printdigraph(net, varSizes)
% -------------------------------------------------------------------------
if exist('digraph') ~= 2
error('MATLAB graph support not present.');
end
s = []; t = []; w = [];
varsNames = {net.vars.name};
layerNames = {net.layers.name};
numVars = numel(varsNames);
spatSize = cellfun(@(vs) vs(1), varSizes);
spatSize(isnan(spatSize)) = 1;
varChannels = cellfun(@(vs) vs(3), varSizes);
varChannels(isnan(varChannels)) = 0;
for li = 1:numel(layerNames)
l = net.layers(li); lidx = numVars + li;
s = [s l.inputIndexes];
t = [t lidx*ones(1, numel(l.inputIndexes))];
w = [w spatSize(l.inputIndexes)];
s = [s lidx*ones(1, numel(l.outputIndexes))];
t = [t l.outputIndexes];
w = [w spatSize(l.outputIndexes)];
end
nodeNames = [varsNames, layerNames];
g = digraph(s, t, w);
lw = 5*g.Edges.Weight/max([g.Edges.Weight; 5]);
h = plot(g, 'NodeLabel', nodeNames, 'LineWidth', lw);
highlight(h, numVars+1:numVars+numel(layerNames), 'MarkerSize', 8, 'Marker', 's');
highlight(h, 1:numVars, 'MarkerSize', 5, 'Marker', 's');
cmap = copper;
varNvalRel = varChannels./max(varChannels);
for vi = 1:numel(varChannels)
highlight(h, vi, 'NodeColor', cmap(max(round(varNvalRel(vi)*64), 1),:));
end
axis off;
layout(h, 'force');
end
% -------------------------------------------------------------------------
function str = printDot(net, varSizes, paramSizes, otps)
% -------------------------------------------------------------------------
str = {} ;
str{end+1} = sprintf('digraph DagNN {\n\tfontsize=12\n') ;
font_style = 'fontsize=12 fontname="helvetica"';
for v = 1:numel(net.vars)
label=sprintf('{{%s} | {%s | %s }}', net.vars(v).name, pdims(varSizes{v}), pmem(4*prod(varSizes{v}))) ;
str{end+1} = sprintf('\tvar_%s [label="%s" shape=record style="solid,rounded,filled" color=cornsilk4 fillcolor=beige %s ]\n', ...
net.vars(v).name, label, font_style) ;
end
for p = 1:numel(net.params)
label=sprintf('{{%s} | {%s | %s }}', net.params(p).name, pdims(paramSizes{p}), pmem(4*prod(paramSizes{p}))) ;
str{end+1} = sprintf('\tpar_%s [label="%s" shape=record style="solid,rounded,filled" color=lightsteelblue4 fillcolor=lightsteelblue %s ]\n', ...
net.params(p).name, label, font_style) ;
end
for l = 1:numel(net.layers)
label = sprintf('{ %s | %s }', net.layers(l).name, class(net.layers(l).block)) ;
str{end+1} = sprintf('\t%s [label="%s" shape=record style="bold,filled" color="tomato4" fillcolor="tomato" %s ]\n', ...
net.layers(l).name, label, font_style) ;
for i = 1:numel(net.layers(l).inputs)
str{end+1} = sprintf('\tvar_%s->%s [weight=10]\n', ...
net.layers(l).inputs{i}, ...
net.layers(l).name) ;
end
for o = 1:numel(net.layers(l).outputs)
str{end+1} = sprintf('\t%s->var_%s [weight=10]\n', ...
net.layers(l).name, ...
net.layers(l).outputs{o}) ;
end
for p = 1:numel(net.layers(l).params)
str{end+1} = sprintf('\tpar_%s->%s [weight=1]\n', ...
net.layers(l).params{p}, ...
net.layers(l).name) ;
end
end
str{end+1} = sprintf('}\n') ;
str = cat(2,str{:}) ;
end
% -------------------------------------------------------------------------
function displayDot(str, opts)
% -------------------------------------------------------------------------
%mwdot = fullfile(matlabroot, 'bin', computer('arch'), 'mwdot') ;
dotPaths = {'/opt/local/bin/dot', 'dot'} ;
if ismember(computer, {'PCWIN64', 'PCWIN'})
winPath = 'c:\Program Files (x86)';
dpath = dir(fullfile(winPath, 'Graphviz*'));
if ~isempty(dpath)
dotPaths = [{fullfile(winPath, dpath.name, 'bin', 'dot.exe')}, dotPaths];
end
end
dotExe = '' ;
for i = 1:numel(dotPaths)
[~,~,ext] = fileparts(dotPaths{i});
if exist(dotPaths{i},'file') && ~strcmp(ext, '.m')
dotExe = dotPaths{i} ;
break;
end
end
if isempty(dotExe)
warning('Could not genereate a figure because the `dot` utility could not be found.') ;
return ;
end
[path, figName, ext] = fileparts(opts.figurePath) ;
if isempty(ext), ext = '.pdf' ; end
if strcmp(figName, 'tempname')
figName = tempname();
end
in = fullfile(path, [ figName, '.dot' ]) ;
out = fullfile(path, [ figName, ext ]) ;
f = fopen(in, 'w') ; fwrite(f, str) ; fclose(f) ;
cmd = sprintf('"%s" -T%s %s -o "%s" "%s"', dotExe, ext(2:end), ...
opts.dotArgs, out, in) ;
[status, result] = system(cmd) ;
if status ~= 0
error('Unable to run %s\n%s', cmd, result) ;
end
if ~isempty(strtrim(result))
fprintf('Dot output:\n%s\n', result) ;
end
%f = fopen(out,'r') ; file=fread(f, 'char=>char')' ; fclose(f) ;
switch computer
case {'PCWIN64', 'PCWIN'}
system(sprintf('start "" "%s"', out)) ;
case 'MACI64'
system(sprintf('open "%s"', out)) ;
case 'GLNXA64'
system(sprintf('display "%s"', out)) ;
otherwise
fprintf('The figure saved at "%s"\n', out) ;
end
end
|
github
|
lifeng9472/IBCCF-master
|
fromSimpleNN.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/+dagnn/@DagNN/fromSimpleNN.m
| 7,258 |
utf_8
|
83f914aec610125592263d74249f54a7
|
function obj = fromSimpleNN(net, varargin)
% FROMSIMPLENN Initialize a DagNN object from a SimpleNN network
% FROMSIMPLENN(NET) initializes the DagNN object from the
% specified CNN using the SimpleNN format.
%
% SimpleNN objects are linear chains of computational layers. These
% layers exchange information through variables and parameters that
% are not explicitly named. Hence, FROMSIMPLENN() uses a number of
% rules to assign such names automatically:
%
% * From the input to the output of the CNN, variables are called
% `x0` (input of the first layer), `x1`, `x2`, .... In this
% manner `xi` is the output of the i-th layer.
%
% * Any loss layer requires two inputs, the second being a label.
% These are called `label` (for the first such layers), and then
% `label2`, `label3`,... for any other similar layer.
%
% Additionally, given the option `CanonicalNames` the function can
% change the names of some variables to make them more convenient to
% use. With this option turned on:
%
% * The network input is called `input` instead of `x0`.
%
% * The output of each SoftMax layer is called `prob` (or `prob2`,
% ...).
%
% * The output of each Loss layer is called `objective` (or `
% objective2`, ...).
%
% * The input of each SoftMax or Loss layer of type *softmax log
% loss* is called `prediction` (or `prediction2`, ...). If a Loss
% layer immediately follows a SoftMax layer, then the rule above
% takes precendence and the input name is not changed.
%
% FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options:
%
% `CanonicalNames`:: false
% If `true` use the rules above to assign more meaningful
% names to some of the variables.
% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.canonicalNames = false ;
opts = vl_argparse(opts, varargin) ;
import dagnn.*
obj = DagNN() ;
net = vl_simplenn_move(net, 'cpu') ;
net = vl_simplenn_tidy(net) ;
% copy meta-information as is
obj.meta = net.meta ;
for l = 1:numel(net.layers)
inputs = {sprintf('x%d',l-1)} ;
outputs = {sprintf('x%d',l)} ;
params = struct(...
'name', {}, ...
'value', {}, ...
'learningRate', [], ...
'weightDecay', []) ;
if isfield(net.layers{l}, 'name')
name = net.layers{l}.name ;
else
name = sprintf('layer%d',l) ;
end
switch net.layers{l}.type
case {'conv', 'convt'}
sz = size(net.layers{l}.weights{1}) ;
hasBias = ~isempty(net.layers{l}.weights{2}) ;
params(1).name = sprintf('%sf',name) ;
params(1).value = net.layers{l}.weights{1} ;
if hasBias
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
end
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
if hasBias
params(2).learningRate = net.layers{l}.learningRate(2) ;
end
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
if hasBias
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
end
end
switch net.layers{l}.type
case 'conv'
block = Conv() ;
block.size = sz ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.dilate = net.layers{l}.dilate ;
case 'convt'
block = ConvTranspose() ;
block.size = sz ;
block.upsample = net.layers{l}.upsample ;
block.crop = net.layers{l}.crop ;
block.numGroups = net.layers{l}.numGroups ;
end
block.hasBias = hasBias ;
block.opts = net.layers{l}.opts ;
case 'pool'
block = Pooling() ;
block.method = net.layers{l}.method ;
block.poolSize = net.layers{l}.pool ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.opts = net.layers{l}.opts ;
case {'normalize', 'lrn'}
block = LRN() ;
block.param = net.layers{l}.param ;
case {'dropout'}
block = DropOut() ;
block.rate = net.layers{l}.rate ;
case {'relu'}
block = ReLU() ;
block.leak = net.layers{l}.leak ;
case {'sigmoid'}
block = Sigmoid() ;
case {'softmax'}
block = SoftMax() ;
case {'softmaxloss'}
block = Loss('loss', 'softmaxlog') ;
% The loss has two inputs
inputs{2} = getNewVarName(obj, 'label') ;
case {'bnorm'}
block = BatchNorm() ;
params(1).name = sprintf('%sm',name) ;
params(1).value = net.layers{l}.weights{1} ;
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
params(3).name = sprintf('%sx',name) ;
params(3).value = net.layers{l}.weights{3} ;
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
params(2).learningRate = net.layers{l}.learningRate(2) ;
params(3).learningRate = net.layers{l}.learningRate(3) ;
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
params(3).weightDecay = 0 ;
end
otherwise
error([net.layers{l}.type ' is unsupported']) ;
end
obj.addLayer(...
name, ...
block, ...
inputs, ...
outputs, ...
{params.name}) ;
for p = 1:numel(params)
pindex = obj.getParamIndex(params(p).name) ;
if ~isempty(params(p).value)
obj.params(pindex).value = params(p).value ;
end
if ~isempty(params(p).learningRate)
obj.params(pindex).learningRate = params(p).learningRate ;
end
if ~isempty(params(p).weightDecay)
obj.params(pindex).weightDecay = params(p).weightDecay ;
end
end
end
% --------------------------------------------------------------------
% Rename variables to canonical names
% --------------------------------------------------------------------
if opts.canonicalNames
for l = 1:numel(obj.layers)
if l == 1
obj.renameVar(obj.layers(l).inputs{1}, 'input') ;
end
if isa(obj.layers(l).block, 'dagnn.SoftMax')
obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ;
obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ;
end
if isa(obj.layers(l).block, 'dagnn.Loss')
obj.renameVar(obj.layers(l).outputs{1}, 'objective') ;
if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*'))
obj.renameVar(obj.layers(l).inputs{1}, ...
getNewVarName(obj, 'prediction')) ;
end
end
end
end
if isfield(obj.meta, 'inputs')
obj.meta.inputs(1).name = obj.layers(1).inputs{1} ;
end
% --------------------------------------------------------------------
function name = getNewVarName(obj, prefix)
% --------------------------------------------------------------------
t = 0 ;
name = prefix ;
while any(strcmp(name, {obj.vars.name}))
t = t + 1 ;
name = sprintf('%s%d', prefix, t) ;
end
|
github
|
lifeng9472/IBCCF-master
|
vl_simplenn_display.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/simplenn/vl_simplenn_display.m
| 12,455 |
utf_8
|
65bb29cd7c27b68c75fdd27acbd63e2b
|
function [info, str] = vl_simplenn_display(net, varargin)
%VL_SIMPLENN_DISPLAY Display the structure of a SimpleNN network.
% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.
%
% INFO = VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO
% with several statistics for each layer of the network NET.
%
% [INFO, STR] = VL_SIMPLENN_DISPLAY(...) returns also a string STR
% with the text that would otherwise be printed.
%
% The function accepts the following options:
%
% `inputSize`:: auto
% Specifies the size of the input tensor X that will be passed to
% the network as input. This information is used in order to
% estiamte the memory required to process the network. When this
% option is not used, VL_SIMPLENN_DISPLAY() tires to use values
% in the NET structure to guess the input size:
% NET.META.INPUTSIZE and NET.META.NORMALIZATION.IMAGESIZE
% (assuming a batch size of one image, unless otherwise specified
% by the `batchSize` option).
%
% `batchSize`:: []
% Specifies the number of data points in a batch in estimating
% the memory consumption, overriding the last dimension of
% `inputSize`.
%
% `maxNumColumns`:: 18
% Maximum number of columns in a table. Wider tables are broken
% into multiple smaller ones.
%
% `format`:: `'ascii'`
% One of `'ascii'`, `'latex'`, or `'csv'`.
%
% See also: VL_SIMPLENN().
% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.inputSize = [] ;
opts.batchSize = [] ;
opts.maxNumColumns = 18 ;
opts.format = 'ascii' ;
opts = vl_argparse(opts, varargin) ;
% determine input size, using first the option, then net.meta.inputSize,
% and eventually net.meta.normalization.imageSize, if any
if isempty(opts.inputSize)
tmp = [] ;
opts.inputSize = [NaN;NaN;NaN;1] ;
if isfield(net, 'meta')
if isfield(net.meta, 'inputSize')
tmp = net.meta.inputSize(:) ;
elseif isfield(net.meta, 'normalization') && ...
isfield(net.meta.normalization, 'imageSize')
tmp = net.meta.normalization.imageSize ;
end
opts.inputSize(1:numel(tmp)) = tmp(:) ;
end
end
if ~isempty(opts.batchSize)
opts.inputSize(4) = opts.batchSize ;
end
fields={'layer', 'type', 'name', '-', ...
'support', 'filtd', 'filtdil', 'nfilt', 'stride', 'pad', '-', ...
'rfsize', 'rfoffset', 'rfstride', '-', ...
'dsize', 'ddepth', 'dnum', '-', ...
'xmem', 'wmem'};
% get the support, stride, and padding of the operators
for l = 1:numel(net.layers)
ly = net.layers{l} ;
switch ly.type
case 'conv'
ks = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;
ks = (ks - 1) .* ly.dilate + 1 ;
info.support(1:2,l) = ks ;
case 'pool'
info.support(1:2,l) = ly.pool(:) ;
otherwise
info.support(1:2,l) = [1;1] ;
end
if isfield(ly, 'stride')
info.stride(1:2,l) = ly.stride(:) ;
else
info.stride(1:2,l) = 1 ;
end
if isfield(ly, 'pad')
info.pad(1:4,l) = ly.pad(:) ;
else
info.pad(1:4,l) = 0 ;
end
% operator applied to the input image
info.receptiveFieldSize(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
(info.support(1:2,1:l)-1),2) ;
info.receptiveFieldOffset(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;
info.receptiveFieldStride = cumprod(info.stride,2) ;
end
% get the dimensions of the data
info.dataSize(1:4,1) = opts.inputSize(:) ;
for l = 1:numel(net.layers)
ly = net.layers{l} ;
if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')
sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;
info.dataSize(:,l+1) = sz(:) ;
continue ;
end
info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...
sum(info.pad(1:2,l)) - ...
info.support(1,l)) / info.stride(1,l)) + 1 ;
info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...
sum(info.pad(3:4,l)) - ...
info.support(2,l)) / info.stride(2,l)) + 1 ;
info.dataSize(3, l+1) = info.dataSize(3,l) ;
info.dataSize(4, l+1) = info.dataSize(4,l) ;
switch ly.type
case 'conv'
if isfield(ly, 'weights')
f = ly.weights{1} ;
else
f = ly.filters ;
end
if size(f, 3) ~= 0
info.dataSize(3, l+1) = size(f,4) ;
end
case {'loss', 'softmaxloss'}
info.dataSize(3:4, l+1) = 1 ;
case 'custom'
info.dataSize(3,l+1) = NaN ;
end
end
if nargout == 1, return ; end
% print table
table = {} ;
wmem = 0 ;
xmem = 0 ;
for wi=1:numel(fields)
w = fields{wi} ;
switch w
case 'type', s = 'type' ;
case 'stride', s = 'stride' ;
case 'rfsize', s = 'rf size' ;
case 'rfstride', s = 'rf stride' ;
case 'rfoffset', s = 'rf offset' ;
case 'dsize', s = 'data size' ;
case 'ddepth', s = 'data depth' ;
case 'dnum', s = 'data num' ;
case 'nfilt', s = 'num filts' ;
case 'filtd', s = 'filt dim' ;
case 'filtdil', s = 'filt dilat' ;
case 'wmem', s = 'param mem' ;
case 'xmem', s = 'data mem' ;
otherwise, s = char(w) ;
end
table{wi,1} = s ;
% do input pseudo-layer
for l=0:numel(net.layers)
switch char(w)
case '-', s='-' ;
case 'layer', s=sprintf('%d', l) ;
case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;
case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;
case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;
case 'xmem'
a = prod(info.dataSize(:,l+1)) * 4 ;
s = pmem(a) ;
xmem = xmem + a ;
otherwise
if l == 0
if strcmp(char(w),'type'), s = 'input';
else s = 'n/a' ; end
else
ly=net.layers{l} ;
switch char(w)
case 'name'
if isfield(ly, 'name')
s=ly.name ;
else
s='' ;
end
case 'type'
switch ly.type
case 'normalize', s='norm';
case 'pool'
if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
case 'softmax', s='softmx' ;
case 'softmaxloss', s='softmxl' ;
otherwise s=ly.type ;
end
case 'nfilt'
switch ly.type
case 'conv'
if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;
else, a = size(ly.filters,4) ; end
s=sprintf('%d',a) ;
otherwise
s='n/a' ;
end
case 'filtd'
switch ly.type
case 'conv'
s=sprintf('%d',size(ly.weights{1},3)) ;
otherwise
s='n/a' ;
end
case 'filtdil'
switch ly.type
case 'conv'
s=sprintf('%d',ly.dilate) ;
otherwise
s='n/a' ;
end
case 'support'
s = pdims(info.support(:,l)) ;
case 'stride'
s = pdims(info.stride(:,l)) ;
case 'pad'
s = pdims(info.pad(:,l)) ;
case 'rfsize'
s = pdims(info.receptiveFieldSize(:,l)) ;
case 'rfoffset'
s = pdims(info.receptiveFieldOffset(:,l)) ;
case 'rfstride'
s = pdims(info.receptiveFieldStride(:,l)) ;
case 'wmem'
a = 0 ;
if isfield(ly, 'weights') ;
for j=1:numel(ly.weights)
a = a + numel(ly.weights{j}) * 4 ;
end
end
% Legacy code to be removed
if isfield(ly, 'filters') ;
a = a + numel(ly.filters) * 4 ;
end
if isfield(ly, 'biases') ;
a = a + numel(ly.biases) * 4 ;
end
s = pmem(a) ;
wmem = wmem + a ;
end
end
end
table{wi,l+2} = s ;
end
end
str = {} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = ptable(opts, table(:,[1 sel])) ;
end
table = {...
'parameter memory', sprintf('%s (%.2g parameters)', pmem(wmem), wmem/4);
'data memory', sprintf('%s (for batch size %d)', pmem(xmem), info.dataSize(4,1))} ;
str{end+1} = ptable(opts, table) ;
str = horzcat(str{:}) ;
if nargout == 0
fprintf('%s', str) ;
clear info str ;
end
% -------------------------------------------------------------------------
function str = ptable(opts, table)
% -------------------------------------------------------------------------
switch opts.format
case 'ascii', str = pascii(table) ;
case 'latex', str = platex(table) ;
case 'csv', str = pcsv(table) ;
end
str = horzcat(str,sprintf('\n')) ;
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
% -------------------------------------------------------------------------
function str = pascii(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = pcsv(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
str{end+1} = sprintf('%s,', ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = platex(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1} = sprintf('\\end{tabular}\n') ;
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
% -------------------------------------------------------------------------
function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem)
% -------------------------------------------------------------------------
if nargin <= 1
cpuMem = 0 ;
gpuMem = 0 ;
end
if isstruct(s)
for f=fieldnames(s)'
f = char(f) ;
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ;
end
end
elseif iscell(s)
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ;
end
elseif isnumeric(s)
if isa(s, 'single')
mult = 4 ;
else
mult = 8 ;
end
if isa(s,'gpuArray')
gpuMem = gpuMem + mult * numel(s) ;
else
cpuMem = cpuMem + mult * numel(s) ;
end
end
|
github
|
lifeng9472/IBCCF-master
|
vl_test_economic_relu.m
|
.m
|
IBCCF-master/external_libs/matconvnet/matlab/xtest/vl_test_economic_relu.m
| 790 |
utf_8
|
35a3dbe98b9a2f080ee5f911630ab6f3
|
% VL_TEST_ECONOMIC_RELU
function vl_test_economic_relu()
x = randn(11,12,8,'single');
w = randn(5,6,8,9,'single');
b = randn(1,9,'single') ;
net.layers{1} = struct('type', 'conv', ...
'filters', w, ...
'biases', b, ...
'stride', 1, ...
'pad', 0);
net.layers{2} = struct('type', 'relu') ;
res = vl_simplenn(net, x) ;
dzdy = randn(size(res(end).x), 'like', res(end).x) ;
clear res ;
res_ = vl_simplenn(net, x, dzdy) ;
res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ;
a=whos('res_') ;
b=whos('res__') ;
assert(a.bytes > b.bytes) ;
vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;
vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;
vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
|
github
|
lifeng9472/IBCCF-master
|
get_subwindow.m
|
.m
|
IBCCF-master/utility/get_subwindow.m
| 858 |
utf_8
|
dff8bc269574f16ee9c269250d675e7e
|
function out = get_subwindow(im, pos, sz)
%GET_SUBWINDOW Obtain sub-window from image, with replication-padding.
% Returns sub-window of image IM centered at POS ([y, x] coordinates),
% with size SZ ([height, width]). If any pixels are outside of the image,
% they will replicate the values at the borders.
%
% Joao F. Henriques, 2014
% http://www.isr.uc.pt/~henriques/
if isscalar(sz), %square sub-window
sz = [sz, sz];
end
ys = floor(pos(1)) + (1:sz(1)) - floor(sz(1)/2);
xs = floor(pos(2)) + (1:sz(2)) - floor(sz(2)/2);
% Check for out-of-bounds coordinates, and set them to the values at the borders
xs = floor(clamp(xs, 1, size(im,2)));
ys = floor(clamp(ys, 1, size(im,1)));
%extract image
out = im(ys, xs, :);
end
function y = clamp(x, lb, ub)
% Clamp the value using lowerBound and upperBound
y = max(x, lb);
y = min(y, ub);
end
|
github
|
fudanxu/CV-CNN-master
|
calculate_acc.m
|
.m
|
CV-CNN-master/Test Demo/calculate_acc.m
| 15,446 |
utf_8
|
b92eeffb33cb272289b888c460b69cb9
|
%*****************************************************************
%Description: classification accuracy and confusion matrix
% e.g. accuracy1 refers to the accuracy of the 1st class.
% m1_2 refers to the probability of misclassifying the 1st class into the 2nd class.
%input: class predict from test_imaging.m; label
%output: accuracy; confusion matrix
%*****************************************************************
function [accuracy, confusion_matrix] = calculate_acc(label,class_img)
c = class_img;
[row,col] = size(c);
num1 = length(find(label(1:row,1:col)==1));
num2 = length(find(label(1:row,1:col)==2));
num3 = length(find(label(1:row,1:col)==3));
num4 = length(find(label(1:row,1:col)==4));
num5 = length(find(label(1:row,1:col)==5));
num6 = length(find(label(1:row,1:col)==6));
num7 = length(find(label(1:row,1:col)==7));
num8 = length(find(label(1:row,1:col)==8));
num9 = length(find(label(1:row,1:col)==9));
num10 = length(find(label(1:row,1:col)==10));
num11 = length(find(label(1:row,1:col)==11));
num12 = length(find(label(1:row,1:col)==12));
num13 = length(find(label(1:row,1:col)==13));
num14 = length(find(label(1:row,1:col)==14));
mask = zeros(row,col);
for i = 1:row
for j = 1:col
if (label(i,j)==1)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp1 = mask.*c;
m1_1 = length(find(temp1==1)); m1_2 = length(find(temp1==2)); m1_3 = length(find(temp1==3));
m1_4 = length(find(temp1==4)); m1_5 = length(find(temp1==5)); m1_6 = length(find(temp1==6));
m1_7 = length(find(temp1==7)); m1_8 = length(find(temp1==8)); m1_9 = length(find(temp1==9));
m1_10 = length(find(temp1==10)); m1_11 = length(find(temp1==11)); m1_12 = length(find(temp1==12));
m1_13 = length(find(temp1==13)); m1_14 = length(find(temp1==14)); m1= [m1_1/num1, m1_2/num1,m1_3/num1,m1_4/num1, m1_5/num1,m1_6/num1,m1_7/num1,m1_8/num1 , m1_9/num1,m1_10/num1,m1_11/num1 ,m1_12/num1,m1_13/num1,m1_14/num1];
accuracy1 = m1_1/num1;
for i = 1:row
for j = 1:col
if (label(i,j)==2)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp2 = mask.*c;
m2_1 = length(find(temp2==1)); m2_2 = length(find(temp2==2)); m2_3 = length(find(temp2==3));
m2_4 = length(find(temp2==4)); m2_5 = length(find(temp2==5)); m2_6 = length(find(temp2==6));
m2_7 = length(find(temp2==7)); m2_8 = length(find(temp2==8)); m2_9 = length(find(temp2==9));
m2_10 = length(find(temp2==10)); m2_11 = length(find(temp2==11)); m2_12 = length(find(temp2==12));
m2_13 = length(find(temp2==13)); m2_14 = length(find(temp2==14));
m2= [m2_1/num2, m2_2/num2,m2_3/num2,m2_4/num2, m2_5/num2,m2_6/num2,m2_7/num2,m2_8/num2 , m2_9/num2,m2_10/num2,m2_11/num2 ,m2_12/num2,m2_13/num2,m2_14/num2];
accuracy2 = m2_2/num2;
for i = 1:row
for j = 1:col
if (label(i,j)==3)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp3 = mask.*c;
m3_1 = length(find(temp3==1)); m3_2 = length(find(temp3==2)); m3_3 = length(find(temp3==3));
m3_4 = length(find(temp3==4)); m3_5 = length(find(temp3==5)); m3_6 = length(find(temp3==6));
m3_7 = length(find(temp3==7)); m3_8 = length(find(temp3==8)); m3_9 = length(find(temp3==9));
m3_10 = length(find(temp3==10)); m3_11 = length(find(temp3==11)); m3_12 = length(find(temp3==12));
m3_13 = length(find(temp3==13)); m3_14 = length(find(temp3==14));
m3= [m3_1/num3, m3_2/num3,m3_3/num3,m3_4/num3, m3_5/num3,m3_6/num3,m3_7/num3,m3_8/num3 , m3_9/num3,m3_10/num3,m3_11/num3 ,m3_12/num3,m3_13/num3,m3_14/num3];
accuracy3 = m3_3/num3;
for i = 1:row
for j = 1:col
if (label(i,j)==4)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp4 = mask.*c;
m4_1 = length(find(temp4==1)); m4_2 = length(find(temp4==2)); m4_3 = length(find(temp4==3));
m4_4 = length(find(temp4==4)); m4_5 = length(find(temp4==5)); m4_6 = length(find(temp4==6));
m4_7 = length(find(temp4==7)); m4_8 = length(find(temp4==8)); m4_9 = length(find(temp4==9));
m4_10 = length(find(temp4==10)); m4_11 = length(find(temp4==11)); m4_12 = length(find(temp4==12));
m4_13 = length(find(temp4==13)); m4_14 = length(find(temp4==14));
m4= [m4_1/num4, m4_2/num4,m4_3/num4,m4_4/num4, m4_5/num4,m4_6/num4,m4_7/num4,m4_8/num4 , m4_9/num4,m4_10/num4,m4_11/num4 ,m4_12/num4,m4_13/num4,m4_14/num4];
accuracy4 = m4_4/num4;
for i = 1:row
for j = 1:col
if (label(i,j)==5)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp5 = mask.*c;
m5_1 = length(find(temp5==1)); m5_2 = length(find(temp5==2)); m5_3 = length(find(temp5==3));
m5_4 = length(find(temp5==4)); m5_5 = length(find(temp5==5)); m5_6 = length(find(temp5==6));
m5_7 = length(find(temp5==7)); m5_8 = length(find(temp5==8)); m5_9 = length(find(temp5==9));
m5_10 = length(find(temp5==10)); m5_11 = length(find(temp5==11)); m5_12 = length(find(temp5==12));
m5_13 = length(find(temp5==13)); m5_14 = length(find(temp5==14));
m5= [m5_1/num5, m5_2/num5,m5_3/num5,m5_4/num5, m5_5/num5,m5_6/num5,m5_7/num5,m5_8/num5 , m5_9/num5,m5_10/num5,m5_11/num5 ,m5_12/num5,m5_13/num5,m5_14/num5];
accuracy5 = m5_5/num5;
for i = 1:row
for j = 1:col
if (label(i,j)==6)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp6 = mask.*c;
m6_1 = length(find(temp6==1)); m6_2 = length(find(temp6==2)); m6_3 = length(find(temp6==3));
m6_4 = length(find(temp6==4)); m6_5 = length(find(temp6==5)); m6_6 = length(find(temp6==6));
m6_7 = length(find(temp6==7)); m6_8 = length(find(temp6==8)); m6_9 = length(find(temp6==9));
m6_10 = length(find(temp6==10)); m6_11 = length(find(temp6==11)); m6_12 = length(find(temp6==12));
m6_13 = length(find(temp6==13)); m6_14 = length(find(temp6==14));
m6= [m6_1/num6, m6_2/num6,m6_3/num6,m6_4/num6, m6_5/num6,m6_6/num6,m6_7/num6,m6_8/num6 , m6_9/num6,m6_10/num6,m6_11/num6 ,m6_12/num6,m6_13/num6,m6_14/num6];
accuracy6 = m6_6/num6;
for i = 1:row
for j = 1:col
if (label(i,j)==7)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp7 = mask.*c;
m7_1 = length(find(temp7==1)); m7_2 = length(find(temp7==2)); m7_3 = length(find(temp7==3));
m7_4 = length(find(temp7==4)); m7_5 = length(find(temp7==5)); m7_6 = length(find(temp7==6));
m7_7 = length(find(temp7==7)); m7_8 = length(find(temp7==8)); m7_9 = length(find(temp7==9));
m7_10 = length(find(temp7==10)); m7_11 = length(find(temp7==11)); m7_12 = length(find(temp7==12));
m7_13 = length(find(temp7==13)); m7_14 = length(find(temp7==14));
m7= [m7_1/num7, m7_2/num7,m7_3/num7,m7_4/num7, m7_5/num7,m7_6/num7,m7_7/num7,m7_8/num7 , m7_9/num7,m7_10/num7,m7_11/num7 ,m7_12/num7,m7_13/num7,m7_14/num7];
accuracy7 = m7_7/num7;
for i = 1:row
for j = 1:col
if (label(i,j)==8)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp8 = mask.*c;
m8_1 = length(find(temp8==1)); m8_2 = length(find(temp8==2)); m8_3 = length(find(temp8==3));
m8_4 = length(find(temp8==4)); m8_5 = length(find(temp8==5)); m8_6 = length(find(temp8==6));
m8_7 = length(find(temp8==7)); m8_8 = length(find(temp8==8)); m8_9 = length(find(temp8==9));
m8_10 = length(find(temp8==10)); m8_11 = length(find(temp8==11)); m8_12 = length(find(temp8==12));
m8_13 = length(find(temp8==13)); m8_14 = length(find(temp8==14));
m8= [m8_1/num8, m8_2/num8,m8_3/num8,m8_4/num8, m8_5/num8,m8_6/num8,m8_7/num8,m8_8/num8 , m8_9/num8,m8_10/num8,m8_11/num8 ,m8_12/num8,m8_13/num8,m8_14/num8 ];
accuracy8 = m8_8/num8;
for i = 1:row
for j = 1:col
if (label(i,j)==9)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp9 = mask.*c;
m9_1 = length(find(temp9==1)); m9_2 = length(find(temp9==2)); m9_3 = length(find(temp9==3));
m9_4 = length(find(temp9==4)); m9_5 = length(find(temp9==5)); m9_6 = length(find(temp9==6));
m9_7 = length(find(temp9==7)); m9_8 = length(find(temp9==8)); m9_9 = length(find(temp9==9));
m9_10 = length(find(temp9==10)); m9_11 = length(find(temp9==11)); m9_12 = length(find(temp9==12));
m9_13 = length(find(temp9==13)); m9_14 = length(find(temp9==14));
m9= [m9_1/num9, m9_2/num9,m9_3/num9,m9_4/num9, m9_5/num9,m9_6/num9,m9_7/num9,m9_8/num9 , m9_9/num9,m9_10/num9,m9_11/num9 ,m9_12/num9,m9_13/num9,m9_14/num9 ];
accuracy9 = m9_9/num9;
for i = 1:row
for j = 1:col
if (label(i,j)==10)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp10 = mask.*c;
m10_1 = length(find(temp10==1)); m10_2 = length(find(temp10==2)); m10_3 = length(find(temp10==3));
m10_4 = length(find(temp10==4)); m10_5 = length(find(temp10==5)); m10_6 = length(find(temp10==6));
m10_7 = length(find(temp10==7)); m10_8 = length(find(temp10==8)); m10_9 = length(find(temp10==9));
m10_10 = length(find(temp10==10)); m10_11 = length(find(temp10==11)); m10_12 = length(find(temp10==12));
m10_13 = length(find(temp10==13)); m10_14 = length(find(temp10==14));
m10= [m10_1/num10, m10_2/num10,m10_3/num10,m10_4/num10, m10_5/num10,m10_6/num10,m10_7/num10,m10_8/num10 , m10_9/num10,m10_10/num10,m10_11/num10 ,m10_12/num10,m10_13/num10,m10_14/num10];
accuracy10 = m10_10/num10;
for i = 1:row
for j = 1:col
if (label(i,j)==11)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp11 = mask.*c;
m11_1 = length(find(temp11==1)); m11_2 = length(find(temp11==2)); m11_3 = length(find(temp11==3));
m11_4 = length(find(temp11==4)); m11_5 = length(find(temp11==5)); m11_6 = length(find(temp11==6));
m11_7 = length(find(temp11==7)); m11_8 = length(find(temp11==8)); m11_9 = length(find(temp11==9));
m11_10 = length(find(temp11==10)); m11_11 = length(find(temp11==11)); m11_12 = length(find(temp11==12));
m11_13 = length(find(temp11==13)); m11_14 = length(find(temp11==14));
m11= [m11_1/num11, m11_2/num11,m11_3/num11,m11_4/num11, m11_5/num11,m11_6/num11,m11_7/num11,m11_8/num11 , m11_9/num11,m11_10/num11,m11_11/num11 ,m11_12/num11,m11_13/num11,m11_14/num11];
accuracy11 = m11_11/num11;
for i = 1:row
for j = 1:col
if (label(i,j)==12)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp12 = mask.*c;
m12_1 = length(find(temp12==1)); m12_2 = length(find(temp12==2)); m12_3 = length(find(temp12==3));
m12_4 = length(find(temp12==4)); m12_5 = length(find(temp12==5)); m12_6 = length(find(temp12==6));
m12_7 = length(find(temp12==7)); m12_8 = length(find(temp12==8)); m12_9 = length(find(temp12==9));
m12_10 = length(find(temp12==10)); m12_11 = length(find(temp12==11)); m12_12 = length(find(temp12==12));
m12_13 = length(find(temp12==13)); m12_14 = length(find(temp12==14));
m12= [m12_1/num12, m12_2/num12,m12_3/num12,m12_4/num12, m12_5/num12,m12_6/num12,m12_7/num12,m12_8/num12 , m12_9/num12,m12_10/num12,m12_11/num12 ,m12_12/num12,m12_13/num12,m12_14/num12 ];
accuracy12 = m12_12/num12;
for i = 1:row
for j = 1:col
if (label(i,j)==13)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp13 = mask.*c;
m13_1 = length(find(temp13==1)); m13_2 = length(find(temp13==2)); m13_3 = length(find(temp13==3));
m13_4 = length(find(temp13==4)); m13_5 = length(find(temp13==5)); m13_6 = length(find(temp13==6));
m13_7 = length(find(temp13==7)); m13_8 = length(find(temp13==8)); m13_9 = length(find(temp13==9));
m13_10 = length(find(temp13==10)); m13_11 = length(find(temp13==11)); m13_12 = length(find(temp13==12));
m13_13 = length(find(temp13==13)); m13_14 = length(find(temp13==14));
m13= [m13_1/num13, m13_2/num13,m13_3/num13,m13_4/num13, m13_5/num13,m13_6/num13,m13_7/num13,m13_8/num13 , m13_9/num13,m13_10/num13,m13_11/num13 ,m13_12/num13,m13_13/num13,m13_14/num13];
accuracy13 = m13_13/num13;
for i = 1:row
for j = 1:col
if (label(i,j)==14)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
temp14 = mask.*c;
m14_1 = length(find(temp14==1)); m14_2 = length(find(temp14==2)); m14_3 = length(find(temp14==3));
m14_4 = length(find(temp14==4)); m14_5 = length(find(temp14==5)); m14_6 = length(find(temp14==6));
m14_7 = length(find(temp14==7)); m14_8 = length(find(temp14==8)); m14_9 = length(find(temp14==9));
m14_10 = length(find(temp14==10)); m14_11 = length(find(temp14==11)); m14_12 = length(find(temp14==12));
m14_13 = length(find(temp14==13)); m14_14 = length(find(temp14==14));
m14= [m14_1/num14, m14_2/num14,m14_3/num14,m14_4/num14, m14_5/num14,m14_6/num14,m14_7/num14,m14_8/num14 , m14_9/num14,m14_10/num14,m14_11/num14 ,m14_12/num14,m14_13/num14,m14_14/num14];
accuracy14 = m14_14/num14;
m = m1_1+m2_2+m3_3+m4_4+m5_5+m6_6+m7_7+m8_8+m9_9+m10_10+m11_11+m12_12+m13_13+m14_14;
num = num1+num2+num3+num4+num5+num6+num7+num8+num9+num10+num11+num12+num13+num14;
accuracy = m/num;
confusion_matrix = [m1_1/num1,m1_2/num1,m1_3/num1,m1_4/num1,m1_5/num1,m1_6/num1,m1_7/num1,m1_8/num1,m1_9/num1,m1_10/num1,m1_11/num1,m1_12/num1,m1_3/num1,m1_14/num1;
m2_1/num2,m2_2/num2,m2_3/num2,m2_4/num2,m2_5/num2,m2_6/num2,m2_7/num2,m2_8/num2,m2_9/num2,m2_10/num2,m2_11/num2,m2_12/num2,m2_3/num2,m2_14/num2;
m3_1/num3,m3_2/num3,m3_3/num3,m3_4/num3,m3_5/num3,m3_6/num3,m3_7/num3,m3_8/num3,m3_9/num3,m3_10/num3,m3_11/num3,m3_12/num3,m3_3/num3,m3_14/num3;
m4_1/num4,m4_2/num1,m4_3/num4,m4_4/num4,m4_5/num4,m4_6/num4,m4_7/num4,m4_8/num4,m4_9/num4,m4_10/num4,m4_11/num4,m4_12/num4,m4_3/num4,m4_14/num4;
m5_1/num5,m5_2/num5,m5_3/num5,m5_4/num5,m5_5/num5,m5_6/num5,m5_7/num5,m5_8/num5,m5_9/num5,m5_10/num5,m5_11/num5,m5_12/num5,m5_3/num5,m5_14/num5;
m6_1/num6,m6_2/num6,m6_3/num6,m6_4/num6,m6_5/num6,m6_6/num6,m6_7/num6,m6_8/num6,m6_9/num6,m6_10/num6,m6_11/num6,m6_12/num6,m6_3/num6,m6_14/num6;
m7_1/num7,m7_2/num7,m7_3/num7,m7_4/num7,m7_5/num7,m7_6/num7,m7_7/num7,m7_8/num7,m7_9/num7,m7_10/num7,m7_11/num7,m7_12/num7,m7_3/num7,m7_14/num7;
m8_1/num8,m8_2/num8,m8_3/num8,m8_4/num8,m8_5/num8,m8_6/num8,m8_7/num8,m8_8/num8,m8_9/num8,m8_10/num8,m8_11/num8,m8_12/num8,m8_3/num8,m8_14/num8;
m9_1/num9,m9_2/num9,m9_3/num9,m9_4/num9,m9_5/num9,m9_6/num9,m9_7/num9,m9_8/num9,m9_9/num9,m9_10/num9,m9_11/num9,m9_12/num9,m9_3/num9,m9_14/num9;
m10_1/num10,m10_2/num10,m10_3/num10,m10_4/num10,m10_5/num10,m10_6/num10,m10_7/num10,m10_8/num10,m10_9/num10,m10_10/num10,m10_11/num10,m10_12/num10,m10_3/num10,m10_14/num10;
m11_1/num11,m11_2/num11,m11_3/num11,m11_4/num11,m11_5/num11,m11_6/num11,m11_7/num11,m11_8/num11,m11_9/num11,m11_10/num11,m11_11/num11,m11_12/num11,m11_3/num11,m11_14/num11;
m12_1/num12,m12_2/num12,m12_3/num12,m12_4/num12,m12_5/num12,m12_6/num12,m12_7/num12,m12_8/num12,m12_9/num12,m12_10/num12,m12_11/num12,m12_12/num12,m12_3/num12,m12_14/num12;
m13_1/num13,m13_2/num13,m13_3/num13,m13_4/num13,m13_5/num13,m13_6/num13,m13_7/num13,m13_8/num13,m13_9/num13,m13_10/num13,m13_11/num13,m13_12/num13,m13_13/num13,m13_14/num13;
m14_1/num14,m14_2/num14,m14_3/num14,m14_4/num14,m14_5/num14,m14_6/num14,m14_7/num14,m14_8/num14,m14_9/num14,m14_10/num14,m14_11/num14,m14_12/num14,m14_3/num14,m14_14/num14;
];
|
github
|
fudanxu/CV-CNN-master
|
test_imaging.m
|
.m
|
CV-CNN-master/Test Demo/test_imaging.m
| 3,971 |
utf_8
|
2439c8a8fc85ed630752b9d26968ea9b
|
%*****************************************************************
%Description: classification result based on CV-CNN
%input: test result from CV_CNN--test_img_oo.mat
%output: classification result:class_img.mat
% classification image: ImageRGB.mat
%Note: This code is taking Flevoland dataset as an example.
%*****************************************************************
function [class_img,ImageRGB] = test_imaging(test_img_oo)
test = test_img_oo;
[~,col] = size(test);
B = zeros(1,col);
G = zeros(1,col);
R = zeros(1,col);
class = zeros(1,col);
for i = 1:col
m = max(real(test(:,i))+imag(test(:,i)));
pos = find( real(test(:,i))+imag(test(:,i)) == m );
% color is corresponding to the legend
if pos == 1 % Potato
R(:,i) = 255/255;
G(:,i) = 128/255;
B(:,i) = 0/255;
class(1,i) = 1;
elseif pos == 2 % Fruit
R(:,i) = 138/255;
G(:,i) = 42/255;
B(:,i) = 116/255;
class(1,i) = 2;
elseif pos == 3 % Oats
R(:,i) = 0/255;
G(:,i) = 0/255;
B(:,i) = 255/255;
class(1,i) = 3;
elseif pos == 4 % Beet
R(:,i) = 255/255;
G(:,i) = 0/255;
B(:,i) = 0/255;
class(1,i) = 4;
elseif pos == 5 % Barley
R(:,i) = 120/255;
G(:,i) = 178/255;
B(:,i) = 215/255;
class(1,i) = 5;
elseif pos == 6 % Onions
R(:,i) = 0/255;
G(:,i) = 102/255;
B(:,i) = 255/255;
class(1,i) = 6;
elseif pos == 7 % Wheats
R(:,i) = 251/255;
G(:,i) = 232/255;
B(:,i) = 45/255;
class(1,i) = 7;
elseif pos == 8 % Beans
R(:,i) = 0/255;
G(:,i) = 255/255;
B(:,i) = 0/255;
class(1,i) = 8;
elseif pos == 9 % Peas
R(:,i) = 204/255;
G(:,i) = 102/255;
B(:,i) = 255/255;
class(1,i) = 9;
elseif pos == 10 % Maize
R(:,i) = 0/255;
G(:,i) = 204/255;
B(:,i) = 102/255;
class(1,i) = 10;
elseif pos == 11 % Flax
R(:,i) = 204/255;
G(:,i) = 255/255;
B(:,i) = 204/255;
class(1,i) = 11;
elseif pos == 12 % Rapeseed
R(:,i) = 204/255;
G(:,i) = 1/255;
B(:,i) = 102/255;
class(1,i) = 12;
elseif pos == 13 % Grass
R(:,i) = 255/255;
G(:,i) = 204/255;
B(:,i) = 204/255;
class(1,i) = 13;
elseif pos == 14 % Luceme
R(:,i) = 102/255;
G(:,i) = 0/255;
B(:,i) = 204/255;
class(1,i) = 14;
end
end
row1 = ceil((1024-12)/3); col1 = ceil((1020-12)/3);
R = reshape(R,row1,col1);
G = reshape(G,row1,col1);
B = reshape(B,row1,col1);
class = reshape(class,row1,col1);
m=1;n=1;
for i=1:size(R,1)
for j=1:size(R,2)
R_ex(m:m+2,n:n+2) = repmat(R(i,j),3,3); % 3:sampling step, 2 = 3-1
G_ex(m:m+2,n:n+2) = repmat(G(i,j),3,3);
B_ex(m:m+2,n:n+2) = repmat(B(i,j),3,3);
class_img(m:m+2,n:n+2) = repmat(class(i,j),3,3);
n = n+3;
end
n=1;
m = m+3;
end
class_img = class_img';
ImageRGB(:,:,1) = R_ex';
ImageRGB(:,:,2) = G_ex';
ImageRGB(:,:,3) = B_ex';
figure
imshow(ImageRGB); title('Classification Image');
%% classification reslut overlaid ground truth area
load label.mat;
[row2,col2,~] = size(ImageRGB);
mask = zeros(row2,col2);
for i = 1:row2
for j = 1:col2
if (label(i,j) ~= 0)
mask(i,j) = 1;
else
mask(i,j) = 0;
end
end
end
R = mask.*ImageRGB(:,:,1);
G = mask.*ImageRGB(:,:,2);
B = mask.*ImageRGB(:,:,3);
ImageRGB_overlaid(:,:,1) = R;
ImageRGB_overlaid(:,:,2) = G;
ImageRGB_overlaid(:,:,3) = B;
figure
imshow(ImageRGB_overlaid); title('Classification Image overlaid Ground Truth');
end
|
github
|
devraj89/GCDL---Generalized-Coupled-Dictionary-Learning-Algorithm-master
|
coupled_DL_recoupled_CCCA_mod.m
|
.m
|
GCDL---Generalized-Coupled-Dictionary-Learning-Algorithm-master/coupled_DL_recoupled_CCCA_mod.m
| 5,504 |
utf_8
|
83b762ff0b7da4e2075ebe020121adef
|
% Main Function of Coupled Dictionary Learning
% Input:
% Alphap,Alphas: Initial sparse coefficient of two domains
% Xh ,Xl : Image Data Pairs of two domains
% Dh ,Dl : Initial Dictionaries
% Wh ,Wl : Initial Projection Matrix
% par : Parameters
%
%
% Output
% Alphap,Alphas: Output sparse coefficient of two domains
% Dh ,Dl : Output Coupled Dictionaries
% Uh ,Ul : Output Projection Matrix for Alpha
%
function [Alphah, Alphal, XH_t, XL_t, Dh, Dl, Wh, Wl, Uh, Ul, f] = coupled_DL_recoupled_CCCA_mod(Alphah, Alphal, XH_t, XL_t, Dh, Dl, Wh, Wl, par, label_h, label_l,knn,eta,option)
% coupled_DL_recoupled(Alphah, Alphal, XH_t, XL_t, Dh, Dl, Wh, Wl, par);
%% parameter setting
[dimX, numX] = size(XH_t);
dimY = size(Alphah, 1);
numD = size(Dh, 2);
rho = par.rho;
lambda1 = par.lambda1;
lambda2 = par.lambda2;
mu = par.mu;
sqrtmu = sqrt(mu);
nu = par.nu;
nIter = par.nIter;
t0 = par.t0;
epsilon = par.epsilon;
param.lambda = lambda1; % not more than 20 non-zeros coefficients
param.lambda2 = lambda2;
%param.mode = 1; % penalized formulation
param.approx=0;
param.K = par.K;
param.L = par.L;
f = 0;
%keyboard;
%% Initialize Us, Up as I
% initially Wl and Wh are the identity matrices
Ul = Wl;
Uh = Wh;
% Iteratively solve D A U
for t = 1 : 10
%% Updating Ws and Wp => Updating Us and Up
% Find the transformation matrices using CCA
set_kapa_cca;
% modifications
if option==1
[Wl,Wh,~] = cluster_cca_mod(full(Alphal),full(Alphah),label_l,label_h,kapa_cca,knn,eta);
elseif option==2
% GCDL 1
[Wl,Wh,~] = cluster_cca_mod2(full(Alphal),full(Alphah),label_l,label_h,kapa_cca,knn,eta,0);
elseif option==3
[Wl,Wh,~] = cluster_cca_mod2(full(Alphal),full(Alphah),label_l,label_h,kapa_cca,knn,eta,1);
elseif option==4
% GCDL 2
[Wl,Wh,~] = cluster_cca_mod3(full(Alphal),full(Alphah),label_l,label_h,kapa_cca,knn,eta,0);
elseif option==5
[Wl,Wh,~] = cluster_cca_mod3(full(Alphal),full(Alphah),label_l,label_h,kapa_cca,knn,eta,1);
end
Wl = real(Wl);
Wh = real(Wh);
Ul = Wl.';
Uh = Wh.';
sub_id = unique(label_h);
nSub = length(sub_id);
Alphal_full = full(Alphal);
Alphah_full = full(Alphah);
Alphal_inclass = zeros(size(Alphal_full,1),nSub);
Alphah_inclass = Alphal_inclass;
Xl_inclass = -0.5*ones(nSub,length(label_l));
Xh_inclass = -0.5*ones(nSub,length(label_h));
% Here I am normalizing the data
for i = 1:length(label_h)
normVal = norm(Uh*Alphah_full(:,i));
Alphah_full(:,i) = Alphah_full(:,i)/normVal;
end;
% Here I am normalizing the data
for i = 1:length(label_l)
normVal = norm(Ul*Alphal_full(:,i));
Alphal_full(:,i) = Alphal_full(:,i)/normVal;
end;
for subNo = 1:nSub
currSubId = sub_id(subNo);
indexvect = find(label_l == currSubId);
Alphal_inclass(:,subNo) = median(Alphal_full(:,indexvect(1:length(indexvect))),2);
Xl_inclass(subNo,indexvect) = 0.8;
indexvect = find(label_h == currSubId);
Alphah_inclass(:,subNo) = median(Alphah_full(:,indexvect(1:length(indexvect))),2);
Xh_inclass(subNo,indexvect) = 0.8;
end;
Ph = (Uh'*Ul*Alphal_inclass)';
Pl = (Ul'*Uh*Alphah_inclass)';
%% Updating Alphas and Alphap
% What Happens If I vary the parameters ?
mu = 0.04;
sqrtmu = sqrt(mu);
% Remember that Xl_inclass is basically Kx and Pl is basically Px
% Remember that Xh_inclass is basically Ky and Ph is basically Py
% The way that Kx and Px are formed are a little different
% instead of Kx being (N1XN2) we make it as Kx(unique labels (N1) X N2)
% So accordingly also Px is formed : for that Alphal_inclasss is used.
% Instead of using all the aplha's data we basically select the
% mean/median of that particular class using the supervised
% information.
% The code will thus run much faster
% From the paper it is given as Px = Ay.'*Ty.'*Tx (Now Tx and Ty are
% the Ul and Uh) and instead of using the whole Ay we utilize a subset
% of that only for faster computation
% Note using the whole matrix works fine but them again it is also time
% consuming
param.lambda = 0.01;
Alphal = mexLasso([XL_t; sqrtmu * Xl_inclass], [Dl; sqrtmu * Pl],param);
param.lambda = 0.01;
Alphah = mexLasso([XH_t; sqrtmu * Xh_inclass], [Dh; sqrtmu * Ph],param);
dictSize = par.K;
%% Updating Ds and Dp
for i=1:dictSize
ai = Alphal(i,:);
Y = XL_t-Dl*Alphal+Dl(:,i)*ai;
di = Y*ai';
di = di./(norm(di,2) + eps);
Dl(:,i) = di;
end
for i=1:dictSize
ai = Alphah(i,:);
Y = XH_t-Dh*Alphah+Dh(:,i)*ai;
di = Y*ai';
di = di./(norm(di,2) + eps);
Dh(:,i) = di;
end
end
return;
|
github
|
hsiboy/Talkie-master
|
lpcQuantise.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/lpcQuantise.m
| 5,008 |
utf_8
|
e6e0b41b2161f2a3fbf580c689b7a207
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Quantise model coefficients, and generate bit codings
function [pitchq,energyq,kq,fields]=lpcQuantise(pitch,energy,k)
fields = zeros(1,13);
energyList = [0,2,3,4,5,7,10,15,20,32,41,57,81,114,161] / 255;
err = 9999;
for b = 1:length(energyList)
if err > abs(energyList(b)-energy)
err = abs(energyList(b)-energy);
energyq = energyList(b);
fields(1) = b-1;
end
end
fields(2) = 0; % Repeat field
pitchList = [0,500,471,444,421,400,381,364,348,333,320,308,296,286,276,267,258,250,242,235,229,222,216,211,205,200,195,190,186,178,170,163,157,151,148,140,136,131,127,121,116,113,110,104,101,99,94,92,87,84,81,78,75,73,70,67,65,63,60,58,56,54,52,50];
err = 9999;
for a = 1:length(pitchList)
if err > abs(pitchList(a)-pitch)
err = abs(pitchList(a)-pitch);
pitchq = pitchList(a);
fields(3) = a-1;
end
end
coefficientsq(1) = 1;
k1List = [-0.978515625,-0.97265625,-0.970703125,-0.966796875,-0.962890625,-0.958984375,-0.953125,-0.94140625,-0.93359375,-0.92578125,-0.916015625,-0.90625,-0.896484375,-0.8828125,-0.869140625,-0.853515625,-0.8046875,-0.740234375,-0.66015625,-0.560546875,-0.443359375,-0.556640625,-0.158203125,0,0.158203125,0.306640625,0.443359375,0.560546875,0.66015625,0.740234375,0.8046875,0.853515625];
err = 9999;
for c = 1:length(k1List)
if err > abs(k1List(c)-k(2))
err = abs(k1List(c)-k(2));
kq(2) = k1List(c);
fields(4) = c-1;
end
end
k2List = [-0.640625,-0.58984375,-0.53515625,-0.474609375,-0.41015625,-0.341796875,-0.267578125,-0.19140625,-0.11328125,-0.033203125,0.046875,0.126953125,0.205078125,0.28125,0.353515625,0.421875,0.486328125,0.544921875,0.599609375,0.6484375,0.69140625,0.732421875,0.767578125,0.798828125,0.826171875,0.849609375,0.87109375,0.888671875,0.904296875,0.91796875,0.9296875,0.98828125];
err = 9999;
for d = 1:length(k2List)
if err > abs(k2List(d)-k(3))
err = abs(k2List(d)-k(3));
kq(3) = k2List(d);
fields(5) = d-1;
end
end
k3List = [-0.859375,-0.7578125,-0.6484375,-0.546875,-0.4375,-0.3359375,-0.2265625,-0.125,-0.015625,-0.546875,0.1953125,0.296875,0.40625,0.5078125,0.6171875,0.71875];
err = 9999;
for e1 = 1:length(k3List)
if err > abs(k3List(e1)-k(4))
err = abs(k3List(e1)-k(4));
kq(4) = k3List(e1);
fields(6) = e1-1;
end
end
k4List = [-0.640625,-0.53125,-0.421875,-0.3125,-0.203125,-0.09375,0.0078125,0.1171875,0.2265625,0.3359375,0.4453125,0.5546875,0.6640625,0.7734375,0.8828125,0.984375];
err = 9999;
for f = 1:length(k4List)
if err > abs(k4List(f)-k(5))
err = abs(k4List(f)-k(5));
kq(5) = k4List(f);
fields(7) = f-1;
end
end
k5List = [-0.640625,-0.546875,-0.4609375,-0.3671875,-0.2734375,-0.1875,-0.09375,-0.0078125,0.0859375,0.1796875,0.265625,0.359375,0.4453125,0.5390625,0.6328125,0.71875];
err = 9999;
for g = 1:length(k5List)
if err > abs(k5List(g)-k(6))
err = abs(k5List(g)-k(6));
kq(6) = k5List(g);
fields(8) = g-1;
end
end
k6List = [-0.5,-0.4140625,-0.328125,-0.2421875,-0.15625,-0.0703125,0.0234375,0.109375,0.1953125,0.28125,0.3671875,0.453125,0.5390625,0.625,0.7109375,0.796875];
err = 9999;
for h = 1:length(k6List)
if err > abs(k6List(h)-k(7))
err = abs(k6List(h)-k(7));
kq(7) = k6List(h);
fields(9) = h-1;
end
end
k7List = [-0.6015625,-0.5078125,-0.4140625,-0.3203125,-0.2265625,-0.1328125,-0.0390625,0.0546875,0.1484375,0.2421875,0.3359375,0.4296875,0.5234375,0.6171875,0.703125,0.796875];
err = 9999;
for w = 1:length(k7List)
if err > abs(k7List(w)-k(8))
err = abs(k7List(w)-k(8));
kq(8) = k7List(w);
fields(10) = w-1;
end
end
k8List = [-0.5,-0.3125,-0.125,0.0546875,0.2421875,0.4296875,0.6171875,0.796875];
err = 9999;
for x = 1:length(k8List)
if err > abs(k8List(x)-k(9))
err = abs(k8List(x)-k(9));
kq(9) = k8List(x);
fields(11) = x-1;
end
end
k9List = [-0.5,-0.34375,-0.1875,-0.03125,0.125,0.2890625,0.4453125,0.6015625];
err = 9999;
for y = 1:length(k9List)
if err > abs(k9List(y)-k(10))
err = abs(k9List(y)-k(10));
kq(10) = k9List(y);
fields(12) = y-1;
end
end
k10List = [-0.3984375,-0.2578125,-0.1171875,0.03125,0.171875,0.25,0.4375,0.6015625];
err = 9999;
for z = 1:length(k10List)
if err > abs(k10List(z)-k(11))
err = abs(k10List(z)-k(11));
kq(11) = k10List(z);
fields(13) = z-1;
end
end
|
github
|
hsiboy/Talkie-master
|
autocorrelate.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/autocorrelate.m
| 293 |
utf_8
|
9bf054c24809b876c95db0b19919c14c
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Calculate autocorrelation of speech segment
function r = autocorrelate(w,len)
r = zeros(1,len);
wlen = length(w);
for n=1:len
r(n) = sum( w(1:wlen-n+1) .* w(n:wlen) );
end
|
github
|
hsiboy/Talkie-master
|
levinsonDurbin.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/levinsonDurbin.m
| 703 |
utf_8
|
020b390fac9fc7ceee90ca98470f9271
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Calculate LPC reflection coefficients
function [k,g] = levinsonDurbin(r,poles)
k(1)=1;
a=zeros(1,poles+1);
at=zeros(1,poles+1);
e=r(1);
for s=1:poles
k(s+1)=-r(s+1);
for t=1:s-1
at(t+1) = a(t+1);
k(s+1) = k(s+1) - a(t+1) * r(s-t+1);
end
if abs(e)<eps
e=0;
break
end
k(s+1) = k(s+1) / e;
a(s+1) = k(s+1);
for u = 1:s-1
a(u+1) = at(u+1) + k(s+1) * at(s-u+1);
end
e = e * (1-k(s+1)*k(s+1));
end
if e<eps
e=0;
end
g = sqrt(e);
|
github
|
hsiboy/Talkie-master
|
lpcSynth.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/lpcSynth.m
| 1,081 |
utf_8
|
1aecd505bd5ad580fec19b230c563c0b
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Synthesise model parameters
function samples=lpcSynth(pitch,energy,coefficients,length,poles,sampleRate)
samples = zeros(1,length);
u = zeros(1,poles+1);
x = zeros(1,poles+1);
% Generate excitation
if pitch>0
% Voiced
excite = zeros(1,length);
for a=1:(sampleRate/pitch):length
excite(floor(a)) = 1;
end
%excite = mod((1:length)*pitch/sampleRate,1)-0.5;
else
% Unvoiced
excite = rand(1,length)-0.5;
end
excite = excite * energy;
% Run through filter
for s=1:length
u(poles+1) = excite(s);
for t=poles:-1:1
u(t) = u(t+1) - coefficients(t+1)*x(t);
end
for v=poles-1:-1:1
x(v+1) = x(v) + coefficients(v+1)*u(v);
end
if x(1) > 1
x(1) = 1;
end
if x(1) < -1
x(1) = -1;
end
x(1) = u(1);
samples(s) = u(1);
end
samples = samples';
|
github
|
hsiboy/Talkie-master
|
bitEmit.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/bitEmit.m
| 327 |
utf_8
|
42d645f5918bde340c98110841d7c429
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Emit a parameter as bits
function bitEmit(val,bits)
bitpos = 2^(bits-1);
for b = 1:bits
if bitand(val,bitpos)
printf('1');
else
printf('0');
end
val = val*2;
end
|
github
|
hsiboy/Talkie-master
|
pitchRefine.m
|
.m
|
Talkie-master/Talkie/encoder/freemat/pitchRefine.m
| 535 |
utf_8
|
72503d815958f9c6ad873c1c6ffbefff
|
% Talkie library
% Copyright 2011 Peter Knight
% This code is released under GPLv2 license.
%
% Home in on best fit pitch
function [pitch,score] = pitchRefine(w,pitchGuess,pitchRange,sampleRate)
score = 0;
phase = (1:length(w))*2*pi/sampleRate;
for (newGuess = pitchGuess-pitchRange:pitchRange/10:pitchGuess+pitchRange)
signal = exp(i*(newGuess*phase))';
pitchScore = abs(mean(w .* signal));
if (pitchScore > score)
score = pitchScore;
pitch = newGuess;
end
end
|
github
|
OperationSmallKat/SmallKat_V2-master
|
LegFPK.m
|
.m
|
SmallKat_V2-master/Kinematics/LegFPK.m
| 1,474 |
utf_8
|
fa6b8372f1493b284a4333f709837c29
|
%Function takes in angles and returns the tip of the quadruped leg in XYZ
%cordinates in base frame
function Tip = LegFPK(p)
%Forward Kinematics
%DH Table for leg
% _________________________________________
% | Link | a | alpha | d | theta |
% | Base | 0 | -90 | 0 | 0 |
% | 1 | .161 | 90 | 0 | q1-pi/2 |
% | 2 | 1.5 | 0 | -.161 | q2 |
% | 3 | 1.5 | 0 | 0 | q3 |
% _________________________________________
%q1 = deg2rad(p(1));
%q2 = deg2rad(p(2));
%q3 = deg2rad(p(3));
q1 = deg2rad(0);
q2 = deg2rad(0);
q3 = deg2rad(0);
A1 = -deg2rad(90);
A2 = deg2rad(90);
a1 = .161;
a2 = 1.5;
a3 = 1.5;
%math stuff
x = a3*sin(q3)*(sin(q1)*sin(q2) - cos(A2)*cos(q1)*cos(q2)) - a2*cos(q2)*sin(q1) - a3*cos(q3)*(cos(q2)*sin(q1) + cos(A2)*cos(q1)*sin(q2)) - a1*sin(q1) - a2*cos(A2)*cos(q1)*sin(q2)
y = a1*cos(A1)*cos(q1) - a2*sin(q2)*(sin(A1)*sin(A2) + cos(A1)*cos(A2)*sin(q1)) - a3*cos(q3)*(sin(q2)*(sin(A1)*sin(A2) + cos(A1)*cos(A2)*sin(q1)) - cos(A1)*cos(q1)*cos(q2)) - a3*sin(q3)*(cos(q2)*(sin(A1)*sin(A2) + cos(A1)*cos(A2)*sin(q1)) + cos(A1)*cos(q1)*sin(q2)) + a2*cos(A1)*cos(q1)*cos(q2)
z = a1*sin(A1)*cos(q1) + a2*sin(q2)*(cos(A1)*sin(A2) - cos(A2)*sin(A1)*sin(q1)) + a3*cos(q3)*(sin(q2)*(cos(A1)*sin(A2) - cos(A2)*sin(A1)*sin(q1)) + sin(A1)*cos(q1)*cos(q2)) + a3*sin(q3)*(cos(q2)*(cos(A1)*sin(A2) - cos(A2)*sin(A1)*sin(q1)) - sin(A1)*cos(q1)*sin(q2)) + a2*sin(A1)*cos(q1)*cos(q2)
%returns tip
Tip = [x,y,z]
end
|
github
|
kishore3229/Matlab-Code-master
|
Line.m
|
.m
|
Matlab-Code-master/Line.m
| 20,312 |
utf_8
|
b842e2fb9fcb2c8e33d588abb27a18c8
|
function varargout = Line(varargin)
% LINE M-file for Line.fig
% LINE, by itself, creates a new LINE or raises the existing
% singleton*.
%
% H = LINE returns the handle to a new LINE or the handle to
% the existing singleton*.
%
% LINE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LINE.M with the given input arguments.
%
% LINE('Property','Value',...) creates a new LINE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Line_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Line_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Line
% Last Modified by GUIDE v2.5 14-Apr-2011 18:20:46
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Line_OpeningFcn, ...
'gui_OutputFcn', @Line_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Line is made visible.
function Line_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Line (see VARARGIN)
% Choose default command line output for Line
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Line wait for user response (see UIRESUME)
% uiwait(handles.Line);
% maximize(handles.Line);
% maximize;
% Set the figure icon
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jframe=get(handles.LTrack,'javaframe');
jIcon=javax.swing.ImageIcon('dental-icon.gif');
jframe.setFigureIcon(jIcon);
% --- Outputs from this function are returned to the command line.
function varargout = Line_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in Home.
function Home_Callback(hObject, eventdata, handles)
% hObject handle to Home (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
% --- Executes on button press in browse.
function browse_Callback(hObject, eventdata, handles)
% hObject handle to browse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
[basefilename,path]= uigetfile({'*.tif'},'Open Tif Image File');
filename= fullfile(path, basefilename);
I = imread (filename);
% if I = [MxNx4]
if(size(I,3)==4)
I(:,:,4)=[]; % convert to I = [MxNx3]
end
% if I = [MxN]
if(size(I,3)==1)
[I]=gray2rgb(I); % convert to I = [MxNx3]
% figure;imshow(I);
end
size(I)
CitraAsli = I;
set(LTproject.LTrack,'CurrentAxes',LTproject.CitraAsli);
set (imshow(CitraAsli));
set(LTproject.LTrack,'Userdata',filename);
set(LTproject.CitraAsli,'Userdata',I);
set(LTproject.filebrowse,'String',strcat('File Location : ',path,basefilename));
% --- Executes on button press in proses.
function proses_Callback(hObject, eventdata, handles)
% hObject handle to proses (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
ImageInput = get(LTproject.CitraAsli,'Userdata');
disp(size(ImageInput));
[GC,ATW,ATG,Vs,ATW2,VsM,dilateEdge] = FnTrackInit8(ImageInput,1);
GreenChan=GC;
%axes (handles.GreenChan);
%imshow(GreenChan);
% imshow (GreenChan);
axes (handles.HistGreenChan);
imhist(GreenChan);
%axes (handles.TrackingAreaWhite);
%imshow (ATW);
%axes (handles.TrackingAreaGray);
%imshow (ATW2);
LT = FnTrack21(GC,VsM,dilateEdge);
axes (handles.MapQuantization);
imshow (LT);
% figure; imshow(LT); title('Hasil Map Quantization');
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton12 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in gapi.
function gapi_Callback(hObject, eventdata, handles)
% hObject handle to gapi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton14.
function pushbutton14_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton14 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in linestrength.
function linestrength_Callback(hObject, eventdata, handles)
% hObject handle to linestrength (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in linetracking.
function linetracking_Callback(hObject, eventdata, handles)
% hObject handle to linetracking (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton17.
function pushbutton17_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton17 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in about.
function about_Callback(hObject, eventdata, handles)
% hObject handle to about (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in reset.
function reset_Callback(hObject, eventdata, handles)
% hObject handle to reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
%set(project.CitraAsli, 'String', ''); ;
set(gcf,'WindowStyle','Normal')
frames = java.awt.Frame.getFrames();
frames(end).setAlwaysOnTop(0);
ReBut = questdlg('Are you really want to reset this application?','Reset','Yes','No','default');
% frames(end).setAlwaysOnTop(1);
switch ReBut
case {'No'}
% set(gcf,'WindowStyle','Modal')
% frames = java.awt.Frame.getFrames();
% frames(end).setAlwaysOnTop(1);
% take no action
case 'Yes'
closeGUI = LTproject.LTrack; %handles.LTproject is the GUI figure
guiPosition = get(LTproject.LTrack,'Position'); %get the position of the GUI
guiName = get(LTproject.LTrack,'Name'); %get the name of the GUI
close(closeGUI); %close the old GUI
eval(guiName) %call the GUI again
end
% --- Executes on button press in close.
function close_Callback(hObject, eventdata, handles)
% hObject handle to close (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
set(gcf,'WindowStyle','Normal')
frames = java.awt.Frame.getFrames();
frames(end).setAlwaysOnTop(0);
pos_size = get(LTproject.LTrack,'Position');
% Call modaldlg with the argument 'Position'.
button = questdlg('Are you really want to close this application?','Close','Yes','No','default');
% Set the figure icon
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jframe=get(handles.LTrack,'javaframe');
jIcon=javax.swing.ImageIcon('dental-icon.gif');
jframe.setFigureIcon(jIcon);
switch button
case {'No'}
case 'Yes'
close;
end
% --- Executes on button press in login.
function login_Callback(hObject, eventdata, handles)
% hObject handle to login (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in logout.
function logout_Callback(hObject, eventdata, handles)
% hObject handle to logout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LTproject = guidata(gcbo);
set(gcf,'WindowStyle','Normal')
frames = java.awt.Frame.getFrames();
frames(end).setAlwaysOnTop(0);
pos_size = get(LTproject.LTrack,'Position');
% Call modaldlg with the argument 'Position'.
button = questdlg('Are you really want to close this application?','close','Yes','No','default');
switch button
case {'No'}
case 'Yes'
close;
end
% --- Executes on button press in save.
function save_Callback(hObject, eventdata, handles)
% hObject handle to save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton28.
function pushbutton28_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton28 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton29.
function pushbutton29_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton29 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton30.
function pushbutton30_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton30 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton31.
function pushbutton31_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton31 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton32.
function pushbutton32_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton32 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton33.
function pushbutton33_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton33 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton34.
function pushbutton34_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton34 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton35.
function pushbutton35_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton35 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton36.
function pushbutton36_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton36 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton37.
function pushbutton37_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton37 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton38.
function pushbutton38_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton38 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton39.
function pushbutton39_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton39 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton40.
function pushbutton40_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton40 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton42.
function pushbutton42_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton42 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton43.
function pushbutton43_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton43 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function LTrack_DeleteFcn(hObject, eventdata, handles)
% --- Executes on button press in filebrowse.
function filebrowse_Callback(hObject, eventdata, handles)
% hObject handle to filebrowse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on selection change in pushbutton45.
function pushbutton45_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton45 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns pushbutton45 contents as cell array
% contents{get(hObject,'Value')} returns selected item from pushbutton45
% --- Executes on button press in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes on button press in pushbutton46.
function pushbutton46_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton46 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton47.
function pushbutton47_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton47 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton48.
function pushbutton48_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton48 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton49.
function pushbutton49_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton49 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton50.
function pushbutton50_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton50 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton51.
function pushbutton51_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton51 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton52.
function pushbutton52_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton52 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object deletion, before destroying properties.
function reset_DeleteFcn(hObject, eventdata, handles)
% hObject handle to reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton55.
function pushbutton55_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton55 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
EnstaBretagneClubRobo/Cordeliere-master
|
variogramfit.m
|
.m
|
Cordeliere-master/Codes_groupe_Krigeage/Kriging_3D/variogramfit.m
| 18,298 |
utf_8
|
ecb3f120bcbef7510fc82ec9051f75d6
|
function [a,c,n,S] = variogramfit(h,gammaexp,a0,c0,numobs,varargin)
% fit a theoretical variogram to an experimental variogram
%
% Syntax:
%
% [a,c,n] = variogramfit(h,gammaexp,a0,c0)
% [a,c,n] = variogramfit(h,gammaexp,a0,c0,numobs)
% [a,c,n] = variogramfit(h,gammaexp,a0,c0,numobs,'pn','pv',...)
% [a,c,n,S] = variogramfit(...)
%
% Description:
%
% variogramfit performs a least squares fit of various theoretical
% variograms to an experimental, isotropic variogram. The user can
% choose between various bounded (e.g. spherical) and unbounded (e.g.
% exponential) models. A nugget variance can be modelled as well, but
% higher nested models are not supported.
%
% The function works best with the function fminsearchbnd available on
% the FEX. You should download it from the File Exchange (File ID:
% #8277). If you don't have fminsearchbnd, variogramfit uses
% fminsearch. The problem with fminsearch is, that it might return
% negative variances or ranges.
%
% The variogram fitting algorithm is in particular sensitive to initial
% values below the optimal solution. In case you have no idea of
% initial values variogramfit calculates initial values for you
% (c0 = max(gammaexp); a0 = max(h)*2/3;). If this is a reasonable
% guess remains to be answered. Hence, visually inspecting your data
% and estimating a theoretical variogram by hand should always be
% your first choice.
%
% Note that for unbounded models, the supplied parameter a0 (range) is
% the distance where gamma equals 95% of the sill variance. The
% returned parameter a0, however, is the parameter r in the model. The
% range at 95% of the sill variance is then approximately 3*r.
%
% Input arguments:
%
% h lag distance of the experimental variogram
% gammaexp experimental variogram values (gamma)
% a0 initial value (scalar) for range
% c0 initial value (scalar) for sill variance
% numobs number of observations per lag distance (used for weight
% function)
%
% Output arguments:
%
% a range
% c sill
% n nugget (empty if nugget variance is not applied)
% S structure array with additional information
% .range
% .sill
% .nugget
% .model - theoretical variogram
% .func - anonymous function of variogram model (only the
% function within range for bounded models)
% .h - distance
% .gamma - experimental variogram values
% .gammahat - estimated variogram values
% .residuals - residuals
% .Rs - R-square of goodness of fit
% .weights - weights
% .exitflag - see fminsearch
% .algorithm - see fminsearch
% .funcCount - see fminsearch
% .iterations - see fminsearch
% .message - see fminsearch
%
% Property name/property values:
%
% 'model' a string that defines the function that can be fitted
% to the experimental variogram.
%
% Supported bounded functions are:
% 'blinear' (bounded linear)
% 'circular' (circular model)
% 'spherical' (spherical model, =default)
% 'pentaspherical' (pentaspherical model)
%
% Supported unbounded functions are:
% 'exponential' (exponential model)
% 'gaussian' (gaussian variogram)
% 'whittle' Whittle's elementary correlation (involves a
% modified Bessel function of the second kind.
% 'stable' (stable models sensu Wackernagel 1995). Same as
% gaussian, but with different exponents. Supply
% the exponent alpha (<2) in an additional pn,pv
% pair:
% 'stablealpha',alpha (default = 1.5).
% 'matern' Matern model. Requires an additional pn,pv pair.
% 'nu',nu (shape parameter > 0, default = 1)
% Note that for particular values of nu the matern
% model reduces to other authorized variogram models.
% nu = 0.5 : exponential model
% nu = 1 : Whittles model
% nu -> inf : Gaussian model
%
% See Webster and Oliver (2001) for an overview on variogram
% models. See Minasny & McBratney (2005) for an introduction
% to the Matern variogram.
%
% 'nugget' initial value (scalar) for nugget variance. The default
% value is []. In this case variogramfit doesn't fit a nugget
% variance.
%
% 'plotit' true (default), false: plot experimental and theoretical
% variogram together.
%
% 'solver' 'fminsearchbnd' (default) same as fminsearch , but with
% bound constraints by transformation (function by John
% D'Errico, File ID: #8277 on the FEX). The advantage in
% applying fminsearchbnd is that upper and lower bound
% constraints can be applied. That prevents that nugget
% variance or range may become negative.
% 'fminsearch'
%
% 'weightfun' 'none' (default). 'cressie85' and 'mcbratney86' require
% you to include the number of observations per experimental
% gamma value (as returned by VARIOGRAM).
% 'cressie85' uses m(hi)/gammahat(hi)^2 as weights
% 'mcbratney86' uses m(hi)*gammaexp(hi)/gammahat(hi)^3
%
%
% Example: fit a variogram to experimental data
%
% load variogramexample
% a0 = 15; % initial value: range
% c0 = 0.1; % initial value: sill
% [a,c,n] = variogramfit(h,gammaexp,a0,c0,[],...
% 'solver','fminsearchbnd',...
% 'nugget',0,...
% 'plotit',true);
%
%
% See also: VARIOGRAM, FMINSEARCH, FMINSEARCHBND
%
%
% References: Wackernagel, H. (1995): Multivariate Geostatistics, Springer.
% Webster, R., Oliver, M. (2001): Geostatistics for
% Environmental Scientists. Wiley & Sons.
% Minsasny, B., McBratney, A. B. (2005): The Matrn function as
% general model for soil variograms. Geoderma, 3-4, 192-207.
%
% Date: 7. October, 2010
% Author: Wolfgang Schwanghart (w.schwanghart[at]unibas.ch)
% check input arguments
if nargin == 0
help variogramfit
return
elseif nargin>0 && nargin < 2;
error('Variogramfit:inputargs',...
'wrong number of input arguments');
end
if ~exist('a0','var') || isempty(a0)
a0 = max(h)*2/3;
end
if ~exist('c0','var') || isempty(c0)
c0 = max(gammaexp);
end
if ~exist('numobs','var') || isempty(a0)
numobs = [];
end
% check input parameters
params.model = 'spherical';
params.nugget = [];
params.plotit = true;
params.solver = {'fminsearchbnd','fminsearch'};
params.stablealpha = 1.5;
params.weightfun = {'none','cressie85','mcbratney86'};
params.nu = 1;
params = parseargs(params,varargin{:});
% check if fminsearchbnd is in the search path
switch lower(params.solver)
case 'fminsearchbnd'
if ~exist('fminsearchbnd.m','file')==2
params.solver = 'fminsearch';
warning('Variogramfit:fminsearchbnd',...
'fminsearchbnd was not found. fminsearch is used instead')
end
end
% check if h and gammaexp are vectors and have the same size
if ~isvector(h) || ~isvector(gammaexp)
error('Variogramfit:inputargs',...
'h and gammaexp must be vectors');
end
% force column vectors
h = h(:);
gammaexp = gammaexp(:);
% check size of supplied vectors
if numel(h) ~= numel(gammaexp)
error('Variogramfit:inputargs',...
'h and gammaexp must have same size');
end
% remove nans;
nans = isnan(h) | isnan(gammaexp);
if any(nans);
h(nans) = [];
gammaexp(nans) = [];
if ~isempty(numobs)
numobs(nans) = [];
end
end
% check weight inputs
if isempty(numobs);
params.weightfun = 'none';
end
% create options for fminsearch
options = optimset('MaxFunEvals',1000000);
% create vector with initial values
% b(1) range
% b(2) sill
% b(3) nugget if supplied
b0 = [a0 c0 params.nugget];
% variogram function definitions
switch lower(params.model)
case 'spherical'
type = 'bounded';
func = @(b,h)b(2)*((3*h./(2*b(1)))-1/2*(h./b(1)).^3);
case 'pentaspherical'
type = 'bounded';
func = @(b,h)b(2)*(15*h./(8*b(1))-5/4*(h./b(1)).^3+3/8*(h./b(1)).^5);
case 'blinear'
type = 'bounded';
func = @(b,h)b(2)*(h./b(1));
case 'circular'
type = 'bounded';
func = @(b,h)b(2)*(1-(2./pi)*acos(h./b(1))+2*h/(pi*b(1)).*sqrt(1-(h.^2)/(b(1)^2)));
case 'exponential'
type = 'unbounded';
func = @(b,h)b(2)*(1-exp(-h./b(1)));
case 'gaussian'
type = 'unbounded';
func = @(b,h)b(2)*(1-exp(-(h.^2)/(b(1)^2)));
case 'stable'
type = 'unbounded';
stablealpha = params.stablealpha;
func = @(b,h)b(2)*(1-exp(-(h.^stablealpha)/(b(1)^stablealpha)));
case 'whittle'
type = 'unbounded';
func = @(b,h)b(2)*(1-h/b(1).*besselk(1,h/b(1)));
case 'matern'
type = 'unbounded';
func = @(b,h)b(2)*(1-(1/((2^(params.nu-1))*gamma(params.nu))) * (h/b(1)).^params.nu .* besselk(params.nu,h/b(1)));
otherwise
error('unknown model')
end
% check if there are zero distances
% if yes, remove them, since the besselk function returns nan for
% zero
switch lower(params.model)
case {'whittle','matern'}
izero = h==0;
if any(izero)
flagzerodistances = true;
else
flagzerodistances = false;
end
otherwise
flagzerodistances = false;
end
% if model type is unbounded, then the parameter b(1) is r, which is
% approximately range/3.
switch type
case 'unbounded'
b0(1) = b0(1)/3;
end
% nugget variance
if isempty(params.nugget)
nugget = false;
funnugget = @(b) 0;
else
nugget = true;
funnugget = @(b) b(3);
end
% generate upper and lower bounds when fminsearchbnd is used
switch lower(params.solver)
case {'fminsearchbnd'};
% lower bounds
lb = zeros(size(b0));
% upper bounds
if nugget;
ub = [inf max(gammaexp) max(gammaexp)]; %
else
ub = [inf max(gammaexp)];
end
end
% create weights (see Webster and Oliver)
switch params.weightfun
case 'cressie85'
weights = @(b,h) (numobs./variofun(b,h).^2)./sum(numobs./variofun(b,h).^2);
case 'mcbratney86'
weights = @(b,h) (numobs.*gammaexp./variofun(b,h).^3)/sum(numobs.*gammaexp./variofun(b,h).^3);
otherwise
weights = @(b,h) 1;
end
% create objective function: weighted least square
objectfun = @(b)sum(((variofun(b,h)-gammaexp).^2).*weights(b,h));
% call solver
switch lower(params.solver)
case 'fminsearch'
% call fminsearch
[b,fval,exitflag,output] = fminsearch(objectfun,b0,options);
case 'fminsearchbnd'
% call fminsearchbnd
[b,fval,exitflag,output] = fminsearchbnd(objectfun,b0,lb,ub,options);
otherwise
error('Variogramfit:Solver','unknown or unsupported solver')
end
% prepare output
a = b(1); %range
c = b(2); %sill
if nugget;
n = b(3);%nugget
else
n = [];
end
% Create structure array with results
if nargout == 4;
S.model = lower(params.model); % model
S.func = func;
S.type = type;
switch S.model
case 'matern';
S.nu = params.nu;
case 'stable';
S.stablealpha = params.stablealpha;
end
S.range = a;
S.sill = c;
S.nugget = n;
S.h = h; % distance
S.gamma = gammaexp; % experimental values
S.gammahat = variofun(b,h); % estimated values
S.residuals = gammaexp-S.gammahat; % residuals
COVyhaty = cov(S.gammahat,gammaexp);
S.Rs = (COVyhaty(2).^2) ./...
(var(S.gammahat).*var(gammaexp)); % Rsquare
S.weights = weights(b,h); %weights
S.weightfun = params.weightfun;
S.exitflag = exitflag; % exitflag (see doc fminsearch)
S.algorithm = output.algorithm;
S.funcCount = output.funcCount;
S.iterations= output.iterations;
S.message = output.message;
end
% if you want to plot the results...
if params.plotit
switch lower(type)
case 'bounded'
plot(h,gammaexp,'rs','MarkerSize',10);
hold on
fplot(@(h) funnugget(b) + func(b,h),[0 b(1)])
fplot(@(h) funnugget(b) + b(2),[b(1) max(h)])
case 'unbounded'
plot(h,gammaexp,'rs','MarkerSize',10);
hold on
fplot(@(h) funnugget(b) + func(b,h),[0 max(h)])
end
axis([0 max(h) 0 max(gammaexp)])
xlabel('lag distance h')
ylabel('\gamma(h)')
hold off
end
% fitting functions for fminsearch/bnd
function gammahat = variofun(b,h)
switch type
% bounded model
case 'bounded'
I = h<=b(1);
gammahat = zeros(size(I));
gammahat(I) = funnugget(b) + func(b,h(I));
gammahat(~I) = funnugget(b) + b(2);
% unbounded model
case 'unbounded'
gammahat = funnugget(b) + func(b,h);
if flagzerodistances
gammahat(izero) = funnugget(b);
end
end
end
end
% and that's it...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction parseargs
function X = parseargs(X,varargin)
%PARSEARGS - Parses name-value pairs
%
% Behaves like setfield, but accepts multiple name-value pairs and provides
% some additional features:
% 1) If any field of X is an cell-array of strings, it can only be set to
% one of those strings. If no value is specified for that field, the
% first string is selected.
% 2) Where the field is not empty, its data type cannot be changed
% 3) Where the field contains a scalar, its size cannot be changed.
%
% X = parseargs(X,name1,value1,name2,value2,...)
%
% Intended for use as an argument parser for functions which multiple options.
% Example usage:
%
% function my_function(varargin)
% X.StartValue = 0;
% X.StopOnError = false;
% X.SolverType = {'fixedstep','variablestep'};
% X.OutputFile = 'out.txt';
% X = parseargs(X,varargin{:});
%
% Then call (e.g.):
%
% my_function('OutputFile','out2.txt','SolverType','variablestep');
% The various #ok comments below are to stop MLint complaining about
% inefficient usage. In all cases, the inefficient usage (of error, getfield,
% setfield and find) is used to ensure compatibility with earlier versions
% of MATLAB.
remaining = nargin-1; % number of arguments other than X
count = 1;
fields = fieldnames(X);
modified = zeros(size(fields));
% Take input arguments two at a time until we run out.
while remaining>=2
fieldname = varargin{count};
fieldind = find(strcmp(fieldname,fields));
if ~isempty(fieldind)
oldvalue = getfield(X,fieldname); %#ok
newvalue = varargin{count+1};
if iscell(oldvalue)
% Cell arrays must contain strings, and the new value must be
% a string which appears in the list.
if ~iscellstr(oldvalue)
error(sprintf('All allowed values for "%s" must be strings',fieldname)); %#ok
end
if ~ischar(newvalue)
error(sprintf('New value for "%s" must be a string',fieldname)); %#ok
end
if isempty(find(strcmp(oldvalue,newvalue))) %#ok
error(sprintf('"%s" is not allowed for field "%s"',newvalue,fieldname)); %#ok
end
elseif ~isempty(oldvalue)
% The caller isn't allowed to change the data type of a non-empty property,
% and scalars must remain as scalars.
if ~strcmp(class(oldvalue),class(newvalue))
error(sprintf('Cannot change class of field "%s" from "%s" to "%s"',...
fieldname,class(oldvalue),class(newvalue))); %#ok
elseif numel(oldvalue)==1 & numel(newvalue)~=1 %#ok
error(sprintf('New value for "%s" must be a scalar',fieldname)); %#ok
end
end
X = setfield(X,fieldname,newvalue); %#ok
modified(fieldind) = 1;
else
error(['Not a valid field name: ' fieldname]);
end
remaining = remaining - 2;
count = count + 2;
end
% Check that we had a value for every name.
if remaining~=0
error('Odd number of arguments supplied. Name-value pairs required');
end
% Now find cell arrays which were not modified by the above process, and select
% the first string.
notmodified = find(~modified);
for i=1:length(notmodified)
fieldname = fields{notmodified(i)};
oldvalue = getfield(X,fieldname); %#ok
if iscell(oldvalue)
if ~iscellstr(oldvalue)
error(sprintf('All allowed values for "%s" must be strings',fieldname)); %#ok
elseif isempty(oldvalue)
error(sprintf('Empty cell array not allowed for field "%s"',fieldname)); %#ok
end
X = setfield(X,fieldname,oldvalue{1}); %#ok
end
end
end
|
github
|
EnstaBretagneClubRobo/Cordeliere-master
|
fminsearchbnd.m
|
.m
|
Cordeliere-master/Codes_groupe_Krigeage/Kriging_3D/fminsearchbnd.m
| 8,444 |
utf_8
|
91711f07f16ddb2b2ecad857de119996
|
function [x,fval,exitflag,output] = fminsearchbnd(fun,x0,LB,UB,options,varargin)
% FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation
% usage: x=FMINSEARCHBND(fun,x0)
% usage: x=FMINSEARCHBND(fun,x0,LB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options)
% usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...)
% usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...)
%
% arguments:
% fun, x0, options - see the help for FMINSEARCH
%
% LB - lower bound vector or array, must be the same size as x0
%
% If no lower bounds exist for one of the variables, then
% supply -inf for that variable.
%
% If no lower bounds at all, then LB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% UB - upper bound vector or array, must be the same size as x0
%
% If no upper bounds exist for one of the variables, then
% supply +inf for that variable.
%
% If no upper bounds at all, then UB may be left empty.
%
% Variables may be fixed in value by setting the corresponding
% lower and upper bounds to exactly the same value.
%
% Notes:
%
% If options is supplied, then TolX will apply to the transformed
% variables. All other FMINSEARCH parameters should be unaffected.
%
% Variables which are constrained by both a lower and an upper
% bound will use a sin transformation. Those constrained by
% only a lower or an upper bound will use a quadratic
% transformation, and unconstrained variables will be left alone.
%
% Variables may be fixed by setting their respective bounds equal.
% In this case, the problem will be reduced in size for FMINSEARCH.
%
% The bounds are inclusive inequalities, which admit the
% boundary values themselves, but will not permit ANY function
% evaluations outside the bounds. These constraints are strictly
% followed.
%
% If your problem has an EXCLUSIVE (strict) constraint which will
% not admit evaluation at the bound itself, then you must provide
% a slightly offset bound. An example of this is a function which
% contains the log of one of its parameters. If you constrain the
% variable to have a lower bound of zero, then FMINSEARCHBND may
% try to evaluate the function exactly at zero.
%
%
% Example usage:
% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
%
% fminsearch(rosen,[3 3]) % unconstrained
% ans =
% 1.0000 1.0000
%
% fminsearchbnd(rosen,[3 3],[2 2],[]) % constrained
% ans =
% 2.0000 4.0000
%
% See test_main.m for other examples of use.
%
%
% See also: fminsearch, fminspleas
%
%
% Author: John D'Errico
% E-mail: [email protected]
% Release: 4
% Release date: 7/23/06
% size checks
xsize = size(x0);
x0 = x0(:);
n=length(x0);
if (nargin<3) || isempty(LB)
LB = repmat(-inf,n,1);
else
LB = LB(:);
end
if (nargin<4) || isempty(UB)
UB = repmat(inf,n,1);
else
UB = UB(:);
end
if (n~=length(LB)) || (n~=length(UB))
error 'x0 is incompatible in size with either LB or UB.'
end
% set default options if necessary
if (nargin<5) || isempty(options)
options = optimset('fminsearch');
end
% stuff into a struct to pass around
params.args = varargin;
params.LB = LB;
params.UB = UB;
params.fun = fun;
params.n = n;
% note that the number of parameters may actually vary if
% a user has chosen to fix one or more parameters
params.xsize = xsize;
params.OutputFcn = [];
% 0 --> unconstrained variable
% 1 --> lower bound only
% 2 --> upper bound only
% 3 --> dual finite bounds
% 4 --> fixed variable
params.BoundClass = zeros(n,1);
for i=1:n
k = isfinite(LB(i)) + 2*isfinite(UB(i));
params.BoundClass(i) = k;
if (k==3) && (LB(i)==UB(i))
params.BoundClass(i) = 4;
end
end
% transform starting values into their unconstrained
% surrogates. Check for infeasible starting guesses.
x0u = x0;
k=1;
for i = 1:n
switch params.BoundClass(i)
case 1
% lower bound only
if x0(i)<=LB(i)
% infeasible starting value. Use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(x0(i) - LB(i));
end
% increment k
k=k+1;
case 2
% upper bound only
if x0(i)>=UB(i)
% infeasible starting value. use bound.
x0u(k) = 0;
else
x0u(k) = sqrt(UB(i) - x0(i));
end
% increment k
k=k+1;
case 3
% lower and upper bounds
if x0(i)<=LB(i)
% infeasible starting value
x0u(k) = -pi/2;
elseif x0(i)>=UB(i)
% infeasible starting value
x0u(k) = pi/2;
else
x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1;
% shift by 2*pi to avoid problems at zero in fminsearch
% otherwise, the initial simplex is vanishingly small
x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k))));
end
% increment k
k=k+1;
case 0
% unconstrained variable. x0u(i) is set.
x0u(k) = x0(i);
% increment k
k=k+1;
case 4
% fixed variable. drop it before fminsearch sees it.
% k is not incremented for this variable.
end
end
% if any of the unknowns were fixed, then we need to shorten
% x0u now.
if k<=n
x0u(k:n) = [];
end
% were all the variables fixed?
if isempty(x0u)
% All variables were fixed. quit immediately, setting the
% appropriate parameters, then return.
% undo the variable transformations into the original space
x = xtransform(x0u,params);
% final reshape
x = reshape(x,xsize);
% stuff fval with the final value
fval = feval(params.fun,x,params.args{:});
% fminsearchbnd was not called
exitflag = 0;
output.iterations = 0;
output.funcCount = 1;
output.algorithm = 'fminsearch';
output.message = 'All variables were held fixed by the applied bounds';
% return with no call at all to fminsearch
return
end
% Check for an outputfcn. If there is any, then substitute my
% own wrapper function.
if ~isempty(options.OutputFcn)
params.OutputFcn = options.OutputFcn;
options.OutputFcn = @outfun_wrapper;
end
% now we can call fminsearch, but with our own
% intra-objective function.
[xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params);
% undo the variable transformations into the original space
x = xtransform(xu,params);
% final reshape to make sure the result has the proper shape
x = reshape(x,xsize);
% Use a nested function as the OutputFcn wrapper
function stop = outfun_wrapper(x,varargin);
% we need to transform x first
xtrans = xtransform(x,params);
% then call the user supplied OutputFcn
stop = params.OutputFcn(xtrans,varargin{1:(end-1)});
end
end % mainline end
% ======================================
% ========= begin subfunctions =========
% ======================================
function fval = intrafun(x,params)
% transform variables, then call original function
% transform
xtrans = xtransform(x,params);
% and call fun
fval = feval(params.fun,reshape(xtrans,params.xsize),params.args{:});
end % sub function intrafun end
% ======================================
function xtrans = xtransform(x,params)
% converts unconstrained variables into their original domains
xtrans = zeros(params.xsize);
% k allows some variables to be fixed, thus dropped from the
% optimization.
k=1;
for i = 1:params.n
switch params.BoundClass(i)
case 1
% lower bound only
xtrans(i) = params.LB(i) + x(k).^2;
k=k+1;
case 2
% upper bound only
xtrans(i) = params.UB(i) - x(k).^2;
k=k+1;
case 3
% lower and upper bounds
xtrans(i) = (sin(x(k))+1)/2;
xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i);
% just in case of any floating point problems
xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i)));
k=k+1;
case 4
% fixed variable, bounds are equal, set it at either bound
xtrans(i) = params.LB(i);
case 0
% unconstrained variable.
xtrans(i) = x(k);
k=k+1;
end
end
end % sub function xtransform end
|
github
|
linwh8/Machine-Learning-master
|
submit.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/submit.m
| 1,605 |
utf_8
|
9b63d386e9bd7bcca66b1a3d2fa37579
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'logistic-regression';
conf.itemName = 'Logistic Regression';
conf.partArrays = { ...
{ ...
'1', ...
{ 'sigmoid.m' }, ...
'Sigmoid Function', ...
}, ...
{ ...
'2', ...
{ 'costFunction.m' }, ...
'Logistic Regression Cost', ...
}, ...
{ ...
'3', ...
{ 'costFunction.m' }, ...
'Logistic Regression Gradient', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Predict', ...
}, ...
{ ...
'5', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Cost', ...
}, ...
{ ...
'6', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
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
|
github
|
linwh8/Machine-Learning-master
|
submitWithConfiguration.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
linwh8/Machine-Learning-master
|
savejson.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
linwh8/Machine-Learning-master
|
loadjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
loadubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
saveubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex2/ex2/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
linwh8/Machine-Learning-master
|
submit.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/submit.m
| 1,567 |
utf_8
|
1dba733a05282b2db9f2284548483b81
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'multi-class-classification-and-neural-networks';
conf.itemName = 'Multi-class Classification and Neural Networks';
conf.partArrays = { ...
{ ...
'1', ...
{ 'lrCostFunction.m' }, ...
'Regularized Logistic Regression', ...
}, ...
{ ...
'2', ...
{ 'oneVsAll.m' }, ...
'One-vs-All Classifier Training', ...
}, ...
{ ...
'3', ...
{ 'predictOneVsAll.m' }, ...
'One-vs-All Classifier Prediction', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Neural Network Prediction Function' ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
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
|
github
|
linwh8/Machine-Learning-master
|
submitWithConfiguration.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
linwh8/Machine-Learning-master
|
savejson.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
linwh8/Machine-Learning-master
|
loadjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
loadubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
saveubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex3/ex3/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
linwh8/Machine-Learning-master
|
submit.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/submit.m
| 1,876 |
utf_8
|
8d1c467b830a89c187c05b121cb8fbfd
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'linear-regression';
conf.itemName = 'Linear Regression with Multiple Variables';
conf.partArrays = { ...
{ ...
'1', ...
{ 'warmUpExercise.m' }, ...
'Warm-up Exercise', ...
}, ...
{ ...
'2', ...
{ 'computeCost.m' }, ...
'Computing Cost (for One Variable)', ...
}, ...
{ ...
'3', ...
{ 'gradientDescent.m' }, ...
'Gradient Descent (for One Variable)', ...
}, ...
{ ...
'4', ...
{ 'featureNormalize.m' }, ...
'Feature Normalization', ...
}, ...
{ ...
'5', ...
{ 'computeCostMulti.m' }, ...
'Computing Cost (for Multiple Variables)', ...
}, ...
{ ...
'6', ...
{ 'gradientDescentMulti.m' }, ...
'Gradient Descent (for Multiple Variables)', ...
}, ...
{ ...
'7', ...
{ 'normalEqn.m' }, ...
'Normal Equations', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId)
% 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
|
github
|
linwh8/Machine-Learning-master
|
submitWithConfiguration.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
linwh8/Machine-Learning-master
|
savejson.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
linwh8/Machine-Learning-master
|
loadjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
loadubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
linwh8/Machine-Learning-master
|
saveubjson.m
|
.m
|
Machine-Learning-master/machine-learning-ex1/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
danfortunato/fast-poisson-solvers-master
|
test_poisson_solid_sphere.m
|
.m
|
fast-poisson-solvers-master/code/tests/test_poisson_solid_sphere.m
| 1,126 |
utf_8
|
6ed07b270536537bf30ee650b8657fa6
|
function pass = test_poisson_solid_sphere( )
% Test the fast Poisson solver for the solid sphere.
tol = 1e-13;
pass = [];
% Test the Fourier modes from -3 to 3
n1 = 21; n2 = 22; n3 = 24;
r = chebpts( n1 );
th = pi*trigpts( n2 );
lam = pi*trigpts( n3 );
[rr, tt, ll] = ndgrid( r, th, lam );
for k = -3:3
exact = @(r, th, lam) (1-r.^2).*r.^abs(k).*sin(lam).^abs(k).*exp(1i*k*th);
rhs = @(r, th, lam) -2*(2*abs(k)+3).*r.^abs(k).*sin(lam).^abs(k).*exp(1i*k*th);
EXACT = exact(rr, tt, ll);
EXACT = vals2coeffs( EXACT );
F = rhs(rr, tt, ll);
F = vals2coeffs( F );
X = poisson_solid_sphere( F, tol );
pass(end+1) = norm( X(:) - EXACT(:) ) < 5*tol;
end
if ( all(pass) )
pass = 1;
end
end
function CFS = vals2coeffs( VALS )
% Convert to Chebyshev--Fourier--Fourier coefficients
[n1, n2, n3] = size( VALS );
CFS = VALS;
for k = 1:n3
CFS(:,:,k) = chebtech2.vals2coeffs( CFS(:,:,k) );
CFS(:,:,k) = trigtech.vals2coeffs( CFS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( CFS(:,j,:), n1, n3 );
vj = trigtech.vals2coeffs( vj.' ).';
CFS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
test_poisson_cylinder.m
|
.m
|
fast-poisson-solvers-master/code/tests/test_poisson_cylinder.m
| 1,519 |
utf_8
|
f9543dd46c7b1087eb78685bd60ccdbd
|
function pass = test_poisson_cylinder( )
% Test the fast Poisson solver for the solid cylinder.
tol = 1e-13;
pass = [];
% Test the Fourier modes from -3 to 3
n1 = 21; n2 = 22; n3 = 24;
r = chebpts( n1 );
th = pi*trigpts( n2 );
z = chebpts( n3 );
[rr, tt, zz] = ndgrid( r, th, z );
for k = -3:3
exact = @(r, th, z) (1-r.^2).*(1-z.^2).*r.^abs(k).*exp(1i*k*th);
rhs = @(r, th, z) 2*(r.^2+2*(abs(k)+1)*z.^2-2*abs(k)-3).*r.^abs(k).*exp(1i*k*th);
EXACT = exact(rr, tt, zz);
EXACT = vals2coeffs( EXACT );
F = rhs(rr, tt, zz);
F = vals2coeffs( F );
X = poisson_cylinder( F, tol );
pass(end+1) = norm( X(:) - EXACT(:) ) < tol;
end
% Cartesian test case
n1 = 55; n2 = 84; n3 = 42;
r = chebpts( n1 );
th = pi*trigpts( n2 );
z = chebpts( n3 );
[rr, tt, zz] = ndgrid( r, th, z );
xx = rr.*cos(tt);
yy = rr.*sin(tt);
v = @(x,y,z) (1-x.^2-y.^2).*(1-z.^2).*(z.*cos(4*pi*(x.^2))+cos(4*pi*y.*z));
f = lap(chebfun3(v));
V = vals2coeffs(v(xx,yy,zz));
F = vals2coeffs(f(xx,yy,zz));
X = poisson_cylinder( F, tol );
pass(end+1) = norm( X(:) - V(:) ) < tol;
if ( all(pass) )
pass = 1;
end
end
function CFS = vals2coeffs( VALS )
% Convert to Chebyshev--Fourier--Chebyshev coefficients
[n1, n2, n3] = size( VALS );
CFS = VALS;
for k = 1:n3
CFS(:,:,k) = chebtech2.vals2coeffs( CFS(:,:,k) );
CFS(:,:,k) = trigtech.vals2coeffs( CFS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( CFS(:,j,:), n1, n3 );
vj = chebtech2.vals2coeffs( vj.' ).';
CFS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
cylinderplot.m
|
.m
|
fast-poisson-solvers-master/code/vis/cylinderplot.m
| 1,544 |
utf_8
|
2d67bc792ceef9447aed1ca8ea5fc8c8
|
function cylinderplot( X, type )
if ( nargin == 1 )
type = 'coeffs';
end
switch type
case 'coeffs'
ff = coeffs2vals( X );
case 'vals'
ff = X;
otherwise
error('Unknown input type.');
end
if ( ~isreal(ff) )
ff = real( ff );
end
[n1, n2, n3] = size( X );
r = chebpts( n1 );
th = [pi*trigpts( n2 ); pi];
z = chebpts( n3 );
% Remove doubled-up data
r = r(floor(n1/2)+1:end);
ff = ff(floor(n1/2)+1:end,:,:);
ff(:,end+1,:) = ff(:,1,:);
[tt, rr, zz] = meshgrid(th, r, z);
% Slices in the cylinder to plot
rslice = 0;
tslice = tt(1,[1 floor(n2/4)+1 floor(n2/2)+1 floor(3*n2/4)+1],1);
zslice = squeeze(zz(1,1,[floor(n3/4)+1 floor(n3/2)+1 floor(3*n3/4)+1]));
hslicer = slice(tt,rr,zz,ff,tslice,rslice,zslice);
hold on
for j = 1:numel(hslicer)
h = hslicer(j);
[xs,ys,zs] = pol2cart(h.XData,h.YData,h.ZData);
surf(xs,ys,zs,h.CData,'EdgeColor','none','FaceColor','Interp');
end
delete(hslicer)
axis([-1 1 -1 1 -1 1])
daspect([1 1 1])
hold off
set(gca, 'Position', [0 0 1 1], 'CameraViewAngleMode', 'Manual')
colorbar('FontSize', 16, 'Position', [0.84 0.09 0.04 0.8])
axis off
end
function VALS = coeffs2vals( CFS )
% Convert to Chebyshev--Fourier--Chebyshev values
[n1, n2, n3] = size( CFS );
VALS = CFS;
for k = 1:n3
VALS(:,:,k) = chebtech2.coeffs2vals( VALS(:,:,k) );
VALS(:,:,k) = trigtech.coeffs2vals( VALS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( VALS(:,j,:), n1, n3 );
vj = chebtech2.coeffs2vals( vj.' ).';
VALS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
sphereplot.m
|
.m
|
fast-poisson-solvers-master/code/vis/sphereplot.m
| 1,582 |
utf_8
|
3a5c2ce9a787a82b96537ab3ad728363
|
function sphereplot( X, type )
if ( nargin == 1 )
type = 'coeffs';
end
switch type
case 'coeffs'
ff = coeffs2vals( X );
case 'vals'
ff = X;
otherwise
error('Unknown input type.');
end
if ( ~isreal(ff) )
ff = real( ff );
end
[n1, n2, n3] = size( X );
r = chebpts( n1 );
th = [pi*trigpts( n2 ); pi];
lam = [pi*trigpts( n3 ); pi] - pi/2;
% Remove doubled-up data
r = r(floor(n1/2)+1:end);
lam = lam(floor(n3/2)+1:end);
ff = ff(floor(n1/2)+1:end,:,floor(n3/2)+1:end);
ff(:,end+1,:) = ff(:,1,:);
ff(:,:,end+1) = ff(:,:,1);
[tt, rr, ll] = meshgrid(th, r, lam);
% Slices in the sphere to plot
rslice = 0;
tslice = squeeze(tt(1,[1 floor(n2/4)+1 floor(n2/2)+1 floor(3*n2/4)+1],1));
lslice = 0;
hslicer = slice(tt,rr,ll,ff,tslice,rslice,lslice);
hold on
for j = 1:numel(hslicer)
h = hslicer(j);
[xs,ys,zs] = sph2cart(h.XData,h.ZData,h.YData);
surf(xs,ys,zs,h.CData,'EdgeColor','none','FaceColor','Interp');
end
delete(hslicer)
axis([-1 1 -1 1 -1 1])
daspect([1 1 1])
hold off
set(gca, 'Position', [0 0 1 1], 'CameraViewAngleMode', 'Manual')
colorbar('FontSize', 16, 'Position', [0.84 0.18 0.04 0.64])
axis off
end
function VALS = coeffs2vals( CFS )
% Convert to Chebyshev--Fourier--Fourier values
[n1, n2, n3] = size( CFS );
VALS = CFS;
for k = 1:n3
VALS(:,:,k) = chebtech2.coeffs2vals( VALS(:,:,k) );
VALS(:,:,k) = trigtech.coeffs2vals( VALS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( VALS(:,j,:), n1, n3 );
vj = trigtech.coeffs2vals( vj.' ).';
VALS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
makeFigures.m
|
.m
|
fast-poisson-solvers-master/code/vis/makeFigures.m
| 8,407 |
utf_8
|
17263bf3508fea3a8bab732b39db2f3a
|
function makeFigures( name, writeToDisk )
%MAKEFIGURES Make figures for the paper.
%
% name: The name of the figure to generate.
% Options are 'all' (default) or one of the following:
% - 'FiniteDifferenceTimings'
% - 'SquareSolution'
% - 'SquareTimings'
% - 'CylinderSolution'
% - 'CylinderTimings'
% - 'SphereSolution'
% - 'CubeSolution'
% - 'CubeTimings'
%
% writeToDisk: Logical flag indicating whether to write the figure to
% disk (1, default) or just display the figure (0).
close all
if ( nargin < 1 ), name = 'all'; end
if ( nargin < 2 ), writeToDisk = 1; end
figs = { 'FiniteDifferenceTimings' @FiniteDifferenceTimings 'vector' ;
'SquareSolution' @SquareSolutionFigure 'raster' ;
'SquareTimings' @SquareTimingsFigure 'vector' ;
'CylinderSolution' @CylinderSolutionFigure 'raster' ;
'CylinderTimings' @CylinderTimingsFigure 'vector' ;
'SphereSolution' @SphereSolutionFigure 'raster' ;
'CubeSolution' @CubeSolutionFigure 'raster' ;
'CubeTimings' @CubeTimingsFigure 'vector' };
for i = 1:length(figs)
[figname, figfun, figformat] = figs{i,:};
if ( strcmp(name, figname) || strcmp(name, 'all') )
feval( figfun );
writefig( figname, writeToDisk, figformat );
end
end
end
function c = colorpalette()
%COLORPALETTE Define the colors to be used for all figures.
c = magma();
end
function writefig( filename, writeToDisk, format )
%WRITEFIG Write a figure to disk.
shg
if ( writeToDisk )
savefig(strcat(filename, '.fig'));
if ( strcmp(format, 'vector') )
print('-depsc', strcat(filename, '.eps'));
elseif ( strcmp(format, 'raster') )
print('-dpng', '-r500', strcat(filename, '.png'));
end
end
end
function FiniteDifferenceTimings()
nn = floor(logspace(1,3.7,50));
t_adi3 = zeros(size(nn));
t_adi6 = zeros(size(nn));
t_adi13 = zeros(size(nn));
t_fft = zeros(size(nn));
j = 1;
for n = nn
% ADI
F = ones(n,n);
s = tic;
X_ADI3 = FiniteDifference_ADI(F, 1e-3);
t_adi3(j) = toc(s);
s = tic;
X_ADI6 = FiniteDifference_ADI(F, 1e-6);
t_adi6(j) = toc(s);
s = tic;
X_ADI13 = FiniteDifference_ADI(F, 1e-13);
t_adi13(j) = toc(s);
% FFT
f = @(x,y) 1+0*x;
s = tic;
X_FFT = FiniteDifference_FFT(f, n);
t_fft(j) = toc(s);
fprintf('n = %g\n', n)
j = j + 1;
end
loglog(nn, t_fft, 'LineWidth', 2), hold on
loglog(nn, t_adi3, 'LineWidth', 2)
loglog(nn, t_adi6, 'LineWidth', 2)
loglog(nn, t_adi13, 'LineWidth', 2)
loglog(nn, 2e-7*nn.^2.*log(nn), 'k--', 'LineWidth', 2), hold off
legend('FFT', ...
['ADI, ' char(1013) ' = 10^{ -3}' ], ...
['ADI, ' char(1013) ' = 10^{ -6}' ], ...
['ADI, ' char(1013) ' = 10^{ -13}'], ...
'Location', 'NorthWest');
set(gca, 'FontSize', 16)
xlim([min(nn) max(nn)])
ylim([1e-4 10])
end
function SquareSolutionFigure()
m = 200; n = 200;
f = chebfun2( @(x,y) -100*x.*sin(20*pi*x.^2.*y).*cos(4*pi*(x+y)) );
F = coeffs2( f, m, n );
X = poisson_rectangle( F );
u = chebfun2( X, 'coeffs' );
plot(u)
view(2)
colormap(colorpalette())
colorbar('FontSize', 16)
axis square
axis off
end
function SquareTimingsFigure()
nn_lyap = floor(logspace(1,3.7,40));
t_lyap = zeros(size(nn_lyap));
j = 1;
for n = nn_lyap
fprintf('n = %g\n', n);
F = ones(n, n);
fprintf(' lyap: ');
s = tic;
X_LYAP = fastPoisson2D_lyap( F, n );
t_lyap(j) = toc(s);
fprintf('%g s\n', t_lyap(j));
j = j + 1;
end
nn_adi = floor(logspace(1,4,40));
t_adi3 = zeros(size(nn_adi));
t_adi6 = zeros(size(nn_adi));
t_adi13 = zeros(size(nn_adi));
j = 1;
for n = nn_adi
fprintf('n = %g\n', n);
F = ones(n, n);
s = tic;
X_ADI3 = poisson_rectangle( F, 1e-3 );
t_adi3(j) = toc(s);
fprintf(' ADI 1e-3: %g s\n', t_adi3(j));
s = tic;
X_ADI6 = poisson_rectangle( F, 1e-6 );
t_adi6(j) = toc(s);
fprintf(' ADI 1e-6: %g s\n', t_adi6(j));
s = tic;
X_ADI13 = poisson_rectangle( F, 1e-13 );
t_adi13(j) = toc(s);
fprintf(' ADI 1e-13: %g s\n', t_adi13(j));
j = j + 1;
end
loglog(nn_adi, t_adi3, 'LineWidth', 2), hold on,
loglog(nn_adi, t_adi6, 'LineWidth', 2)
loglog(nn_adi, t_adi13, 'LineWidth', 2)
loglog(nn_lyap, t_lyap, 'LineWidth', 2)
nn = nn_adi(nn_adi > 500);
loglog(nn, 2.2e-8*nn.^2.*log(nn).^2, 'k--', 'LineWidth', 2)
loglog(nn, 6.1e-9*nn.^3, 'k--', 'LineWidth', 2), hold off
legend(['ADI, ' char(1013) ' = 10^{ -3}' ], ...
['ADI, ' char(1013) ' = 10^{ -6}' ], ...
['ADI, ' char(1013) ' = 10^{ -13}'], ...
'Bartels-Stewart', 'Location', 'NorthWest')
set(gca, 'FontSize', 16)
xlim([min(nn_adi) max(nn_adi)])
ylim([2e-4 400])
end
function CylinderSolutionFigure()
function CFS = vals2coeffs( VALS )
% Convert to Chebyshev--Fourier--Chebyshev coefficients
[n1, n2, n3] = size( VALS );
CFS = VALS;
for k = 1:n3
CFS(:,:,k) = chebtech2.vals2coeffs( CFS(:,:,k) );
CFS(:,:,k) = trigtech.vals2coeffs( CFS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( CFS(:,j,:), n1, n3 );
vj = chebtech2.vals2coeffs( vj.' ).';
CFS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
n1 = 55; n2 = 84; n3 = 42;
r = chebpts( n1 );
th = pi*trigpts( n2 );
z = chebpts( n3 );
[rr, tt, zz] = ndgrid( r, th, z );
xx = rr.*cos(tt);
yy = rr.*sin(tt);
v = @(x,y,z) (1-x.^2-y.^2).*(1-z.^2).*(z.*cos(4*pi*(x.^2))+cos(4*pi*y.*z));
f = lap(chebfun3(v));
F = vals2coeffs(f(xx,yy,zz));
X = poisson_cylinder( F );
colormap(colorpalette())
cylinderplot(X, 'coeffs')
end
function CylinderTimingsFigure()
nn = floor(logspace(1,2.6,50));
t = zeros(size(nn));
j = 1;
for n = nn
fprintf('n = %g\n', n);
F = ones(n, n, n);
s = tic;
X = poisson_cylinder( F );
t(j) = toc(s);
fprintf('%g s\n', t(j));
j = j + 1;
end
loglog(nn, t, 'LineWidth', 2), hold on
nn2 = nn(nn > 110);
loglog(nn2, 1e-7*nn2.^3.*log(nn2).^2, 'k--', 'LineWidth', 2), hold off
set(gca, 'FontSize', 16)
xlim([min(nn) max(nn)])
ylim([7e-3 500])
end
function SphereSolutionFigure()
function CFS = vals2coeffs( VALS )
% Convert to Chebyshev--Fourier--Fourier coefficients
[n1, n2, n3] = size( VALS );
CFS = VALS;
for k = 1:n3
CFS(:,:,k) = chebtech2.vals2coeffs( CFS(:,:,k) );
CFS(:,:,k) = trigtech.vals2coeffs( CFS(:,:,k).' ).';
end
for j = 1:n2
vj = reshape( CFS(:,j,:), n1, n3 );
vj = trigtech.vals2coeffs( vj.' ).';
CFS(:,j,:) = reshape( vj, n1, 1, n3 );
end
end
n1 = 31; n2 = 32; n3 = 32;
r = chebpts( n1 );
lam = pi*trigpts( n2 );
th = pi*trigpts( n3 );
[rr, tt, ll] = ndgrid( r, th, lam );
k = 2;
rhs = @(r, th, lam) -2*(2*abs(k)+3).*r.^abs(k).*sin(lam).^abs(k).*exp(1i*k*th);
F = rhs(rr, tt, ll);
F = vals2coeffs( F );
X = poisson_solid_sphere( F );
colormap(colorpalette())
sphereplot( X )
end
function CubeSolutionFigure()
m = 10; n = 10; p = 10;
u = chebfun3( @(x,y,z) (1-x.^2).*(1-y.^2).*(1-z.^2).*cos(x.*y.*z.^2) );
f = lap( u );
F = coeffs3( f, m, n, p );
X = poisson_cube( F );
colormap(colorpalette())
cubeplot( X )
end
function CubeTimingsFigure()
nn = floor(logspace(1,1.7,17));
t = zeros(size(nn));
j = 1;
for n = nn
fprintf('n = %g\n', n);
F = ones(n, n, n);
s = tic;
X = poisson_cube( F );
t(j) = toc(s);
fprintf('%g s\n', t(j));
j = j + 1;
end
loglog(nn, t, 'LineWidth', 2), hold on
nn2 = nn(nn > 25);
loglog(nn2, 7.6e-4*nn2.^3.*log(nn2).^3, 'k--', 'LineWidth', 2), hold off
set(gca, 'FontSize', 16)
xlim([min(nn) max(nn)])
ylim([10 10000])
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
poisson_cube.m
|
.m
|
fast-poisson-solvers-master/code/cube/poisson_cube.m
| 7,599 |
utf_8
|
248560894cdfa152de45a95b4f04d275
|
function X = poisson_cube( F, tol )
%POISSON_CUBE Fast Poisson solver for the cube.
% POISSON_CUBE( F ) solves laplacian(U) = F on [-1,1]x[-1,1]x[-1,1] with
% zero Dirichlet boundary conditions. That is, U satisfies
%
% U_{x,x} + U_{y,y} + U_{z,z} = F, on [-1,1]^3 U = 0 on boundary
%
% F is input as an M x N x P matrix of Chebyshev coefficients. The
% equation is solved using an M x N x P discretization.
%
% POISSON_CUBE( F, TOL ) solves to the specified error tolerance.
% DEVELOPER'S NOTE:
%
% METHOD: Spectral method (in coefficient space). We use a C^{(3/2)} basis
% to discretize the equation, resulting in a discretization of the form
% (kron(A,A,I) + kron(A,I,A) + kron(I,A,A)) X(:) = F(:), where A is a
% symmetric tridiagonal matrix.
%
% LINEAR ALGEBRA: Matrix equations. The matrix equation is solved by a
% three-level nested alternating direction implicit (ADI) method.
%
% SOLVE COMPLEXITY: O(M*N*P*log(MAX(M,N,P))^3*log(1/eps)) with M*N*P =
% total degrees of freedom. This is not theoretically justified.
%
% AUTHORS: Dan Fortunato ([email protected])
% Alex Townsend ([email protected])
%
% The fast Poisson solver is based on:
%
% D. Fortunato and A. Townsend, Fast Poisson solvers for spectral methods,
% in preparation, 2017.
if ( nargin < 2 )
tol = 1e-13;
end
[m, n, p] = size( F );
% Convert the RHS to C^{(3/2)} coefficients
F = cheb2ultra_tensor( F );
% Construct Tm, Tn, Tp
jjm = (0:m-1)';
dsub = -1./(2*(jjm+3/2)).*(jjm+1).*(jjm+2)*1/2./(1/2+jjm+2);
dsup = -1./(2*(jjm+3/2)).*(jjm+1).*(jjm+2)*1/2./(1/2+jjm);
d = -dsub - dsup;
Mm = spdiags([dsub d dsup], [-2 0 2], m, m);
invDm = spdiags(-1./(jjm.*(jjm+3)+2), 0, m, m);
Tm = invDm * Mm;
jjn = (0:n-1)';
dsub = -1./(2*(jjn+3/2)).*(jjn+1).*(jjn+2)*1/2./(1/2+jjn+2);
dsup = -1./(2*(jjn+3/2)).*(jjn+1).*(jjn+2)*1/2./(1/2+jjn);
d = -dsub - dsup;
Mn = spdiags([dsub d dsup], [-2 0 2], n, n);
invDn = spdiags(-1./(jjn.*(jjn+3)+2), 0, n, n);
Tn = invDn * Mn;
jjp = (0:p-1)';
dsub = -1./(2*(jjp+3/2)).*(jjp+1).*(jjp+2)*1/2./(1/2+jjp+2);
dsup = -1./(2*(jjp+3/2)).*(jjp+1).*(jjp+2)*1/2./(1/2+jjp);
d = -dsub - dsup;
Mp = spdiags([dsub d dsup], [-2 0 2], p, p);
invDp = spdiags(-1./(jjp.*(jjp+3)+2), 0, p, p);
Tp = invDp * Mp;
% Diagonally scale the RHS, as in the 2D Poisson solver
[ii, jj, kk] = ndgrid( jjm, jjn, jjp );
F = -F ./ (ii.*(ii+3)+2) ./ (jj.*(jj+3)+2) ./ (kk.*(kk+3)+2);
Im = eye( m );
In = eye( n );
Ip = eye( p );
% Let U = kron(Tp,Tn,Im), V = kron(Ip,Tn,Tm), W = kron(Tp,In,Tm).
% Then Poisson can be written as (U + V + W) x = f with x = X(:), f = F(:).
% We will solve this using a three-level nested ADI iteration.
X = zeros( m, n, p );
% Calculate ADI shifts based on bounds on the eigenvalues of Tm, Tn, Tp
innertol = 1e-16;
a = @(n) -39*n^-4;
b = @(n) -4/pi^2;
% TODO: Calculate shifts based on m, n, and p
[p1, ~] = ADIshifts(b(n)^2, a(n)^2, -a(n)^2, -b(n)^2, tol);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ADI LEVEL 1: Solve ((U+V) + W) x = f %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:numel(p1)
fprintf('Outer iteration: %g / %g\n', i, numel(p1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ADI LEVEL 2: Solve ((U+p1(i)I/2) + (V+p1(i)I/2)) x = f - (W-p1(i)I) x_i %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
RHSi = F + p1(i)*X;
for j = 1:n
RHSi(:,j,:) = squeeze(RHSi(:,j,:)) - Tm*squeeze(X(:,j,:))*Tp';
end
[p2, ~] = ADIshifts(b(n)^2+p1(i)/2, a(n)^2+p1(i)/2, -a(n)^2+p1(i)/2, -b(n)^2+p1(i)/2, innertol);
for j = 1:numel(p2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ADI LEVEL 3: Solve ((U+p1(i)I/2) + p2(j)I) x = f - (W-p1(i)I) x_i - ((V+p1(i)I/2) - p2(j)I) x_j %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This decouples in one dimension, yielding: T*X_k*T' + s*X_k = F_k
% We can rewrite this as: s*T\X_k + X_k*T' = T\F_k
% and solve it fast using ADI.
RHSj = RHSi - p1(i)/2*X + p2(j)*X;
for k = 1:p
RHSj(:,:,k) = squeeze(RHSj(:,:,k)) - Tm*squeeze(X(:,:,k))*Tn';
end
s = p1(i)/2 + p2(j);
[p3, q3] = ADIshifts(-5/a(n)*s, -1/b(n)*s, a(n), b(n), innertol);
for k = 1:m
RHSk = squeeze(RHSj(k,:,:));
Xk = zeros(n, p);
FF = Tn \ RHSk;
for l = 1:numel(p3)
Xk = ( FF - (s*(Tn\Xk) + p3(l)*Xk) ) / (p3(l)*Ip - Tp');
Xk = (s*In+q3(l)*Tn) \ ( RHSk - Tn*Xk*(q3(l)*Ip-Tp') );
end
X(k,:,:) = Xk;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ADI LEVEL 3: Solve ((V+p1(i)I/2) + p2(j)I) x = f - (W-p1(i)I) x_i - ((U+p1(i)I/2) - p2(j)I) x_j %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This decouples in one dimension, yielding: T*X_k*T' + s*X_k = F_k
% We can rewrite this as: s*T\X_k + X_k*T' = T\F_k
% and solve it fast using ADI.
RHSj = RHSi - p1(i)/2*X + p2(j)*X;
for k = 1:m
RHSj(k,:,:) = squeeze(RHSj(k,:,:)) - Tn*squeeze(X(k,:,:))*Tp';
end
s = p1(i)/2 + p2(j);
[p3, q3] = ADIshifts(-5/a(n)*s, -1/b(n)*s, a(n), b(n), innertol);
for k = 1:p
RHSk = squeeze(RHSj(:,:,k));
Xk = zeros(m, n);
FF = Tm \ RHSk;
for l = 1:numel(p3)
Xk = ( FF - (s*(Tm\Xk)+p3(l)*Xk) ) / (p3(l)*In-Tn');
Xk = (s*Im+q3(l)*Tm) \ ( RHSk - Tm*Xk*(q3(l)*In-Tn') );
end
X(:,:,k) = Xk;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ADI LEVEL 2: Solve (W + p1(i)I) x = f - ((U+V)-p1(i)I) x_i %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This decouples in one dimension, yielding: T*X_k*T' + s*X_k = F_k
% We can rewrite this as: s*T\X_k + X_k*T' = T\F_k
% and solve it fast using ADI.
RHSi = F + p1(i)*X;
for j = 1:p
RHSi(:,:,j) = RHSi(:,:,j) - Tm*X(:,:,j)*Tn';
end
for j = 1:m
RHSi(j,:,:) = squeeze(RHSi(j,:,:)) - Tn*squeeze(X(j,:,:))*Tp';
end
s = p1(i);
[p3, q3] = ADIshifts(-5/a(n)*s, -1/b(n)*s, a(n), b(n), innertol);
for j = 1:n
RHSj = squeeze(RHSi(:,j,:));
Xk = zeros(m, p);
FF = Tm \ RHSj;
for l = 1:numel(p3)
Xk = ( FF - (s*(Tm\Xk)+p3(l)*Xk) ) / (p3(l)*Ip-Tp');
Xk = (s*Im+q3(l)*Tm) \ ( RHSj - Tm*Xk*(q3(l)*Ip-Tp') );
end
X(:,j,:) = Xk;
end
end
% Convert back to Chebyshev
X = ultra1mx2cheb_tensor( X );
end
function X = cheb2ultra_tensor( X )
%CHEB2ULTRA_TENSOR Convert tensor Chebyshev coefficients to C^{(3/2)}
[m, n, p] = size( X );
for k = 1:p
X(:,:,k) = cheb2ultra( cheb2ultra( X(:,:,k) ).' ).';
end
S = leg2ultra_mat( p );
for i = 1:m
for j = 1:n
X(i,j,:) = S * cheb2leg( cheb2leg( permute(X(i,j,:),[3 2 1]) ).' ).';
end
end
end
function X = ultra1mx2cheb_tensor( X )
%ULTRA1MX2CHEB_TENSOR Convert tensor (1-x.^2)T_k coefficients to T_k
[m, n, p] = size( X );
for k = 1:p
X(:,:,k) = ultra1mx2cheb( ultra1mx2cheb( X(:,:,k) ).' ).';
end
S = ultra1mx2leg_mat( p );
for i = 1:m
for j = 1:n
X(i,j,:) = leg2cheb( leg2cheb( S * permute(X(i,j,:),[3 2 1]) ).' ).';
end
end
end
|
github
|
danfortunato/fast-poisson-solvers-master
|
poisson_rectangle.m
|
.m
|
fast-poisson-solvers-master/code/rectangle/poisson_rectangle.m
| 6,949 |
utf_8
|
a25dca19c5ab567ed3de01eb824d80fd
|
function X = poisson_rectangle( F, varargin )
%POISSON_RECTANGLE Fast Poisson solver for the rectangle.
% POISSON_RECTANGLE( F ) solves laplacian(U) = F on [-1,1]x[-1,1] with
% zero Dirichlet boundary conditions. That is, U satisfies
%
% U_{x,x} + U_{y,y} = F, on [-1,1]x[-1,1] U = 0 on boundary
%
% F is input as an M x N matrix of Chebyshev coefficients. The equation
% is solved using an M x N discretization. G can be a scalar, a function
% handle, or any chebfun2 object satisfying the Dirichlet data.
%
% POISSON_RECTANGLE( F, TOL ) solves to the specified error tolerance.
%
% POISSON_RECTANGLE( F, [A B C D] ) solves on the domain [A,B]x[C,D].
%
% POISSON_RECTANGLE( F, [A B C D], TOL ) solves on the domain [A,B]x[C,D]
% to the specified error tolerance.
%
% POISSON_RECTANGLE( F, LBC, RBC, DBC, UBC ) solves using the given
% Dirichlet data. The data are given as function handles.
%
% POISSON_RECTANGLE( F, LBC, RBC, DBC, UBC, [A B C D] ) solves using the
% given Dirichlet data on the domain [A,B]x[C,D].
%
% POISSON_RECTANGLE( F, LBC, RBC, DBC, UBC, TOL ) solves using the
% given Dirichlet data to the specified error tolerance.
%
% POISSON_RECTANGLE( F, LBC, RBC, DBC, UBC, [A B C D], TOL ) solves using
% given Dirichlet data on the domain [A,B]x[C,D] to the specified error
% tolerance.
% DEVELOPER'S NOTE:
%
% METHOD: Spectral method (in coefficient space). We use a C^{(3/2)} basis
% to discretize the equation, resulting in a discretization of the form
% AX + XA = F, where A is a symmetric tridiagonal matrix.
%
% LINEAR ALGEBRA: Matrix equations. The matrix equation is solved by the
% alternating direction implicit (ADI) method.
%
% SOLVE COMPLEXITY: O(M*N*log(MAX(M,N))*log(1/eps)) with M*N = total
% degrees of freedom.
%
% AUTHORS: Dan Fortunato ([email protected])
% Alex Townsend ([email protected])
%
% The fast Poisson solver is based on:
%
% D. Fortunato and A. Townsend, Fast Poisson solvers for spectral methods,
% in preparation, 2017.
[m, n] = size( F );
% Default arguments
dom = [-1, 1, -1, 1];
tol = 1e-13;
BC = zeros(m, n);
nonzeroBC = false;
% Parse the inputs
if ( nargin == 2 )
if ( numel(varargin{1}) == 1 )
% Call is POISSON_RECTANGLE( F, tol )
tol = varargin{1};
else
% Call is POISSON_RECTANGLE( F, dom )
dom = varargin{1};
end
elseif ( nargin == 3 )
% Call is POISSON_RECTANGLE( F, dom, tol )
[dom, tol] = varargin{:};
elseif ( nargin == 5 )
% Call is POISSON_RECTANGLE( F, lbc, rbc, dbc, ubc )
[lbc, rbc, dbc, ubc] = varargin{:};
nonzeroBC = true;
elseif ( nargin == 6 )
[lbc, rbc, dbc, ubc] = varargin{1:4};
nonzeroBC = true;
if ( numel(varargin{5}) == 1 )
% Call is POISSON_RECTANGLE( F, lbc, rbc, dbc, ubc, tol )
tol = varargin{5};
else
% Call is POISSON_RECTANGLE( F, lbc, rbc, dbc, ubc, dom )
dom = varargin{5};
end
elseif ( nargin == 7 )
% Call is POISSON_RECTANGLE( F, lbc, rbc, dbc, ubc, dom, tol )
[lbc, rbc, dbc, ubc, dom, tol] = varargin{:};
nonzeroBC = true;
elseif ( nargin ~= 1 )
error('POISSON_RECTANGLE:ARG', 'Invalid number of arguments.');
end
% Check that the domain is valid
if ( numel(dom) ~= 4 )
error('POISSON_RECTANGLE:DOMAIN', 'Invalid domain specification.');
end
% Solve for u on the given domain, adjust diffmat to including scaling:
scl_x = (2/(dom(2)-dom(1)))^2;
scl_y = (2/(dom(4)-dom(3)))^2;
% Solver only deals with zero homogeneous Dirichlet conditions. Therefore,
% if nonzero Dirichlet conditions are given, we solve lap(u) = f with
% u|bc = g as u = v + w, where v|bc = g, and lap(w) = f - lap(v), w|bc = 0:
if ( nonzeroBC )
% Check that the boundary conditions are valid
if ~( isa(lbc, 'function_handle') && ...
isa(rbc, 'function_handle') && ...
isa(dbc, 'function_handle') && ...
isa(ubc, 'function_handle') )
error('POISSON_RECTANGLE:BC', ...
'Dirichlet data needs to be given as a function handle.');
end
% Make sure the Dirichlet data match at the corners
if ~( lbc(dom(3)) == dbc(dom(1)) && ...
lbc(dom(4)) == ubc(dom(1)) && ...
rbc(dom(3)) == dbc(dom(2)) && ...
rbc(dom(4)) == ubc(dom(2)) )
error('POISSON_RECTANGLE:BC', 'Corners must match.');
end
% First convert the boundary data from function handles to coefficients
lbc_cfs = fun2coeffs( lbc, m, dom(3:4) );
rbc_cfs = fun2coeffs( rbc, m, dom(3:4) );
dbc_cfs = fun2coeffs( dbc, n, dom(1:2) );
ubc_cfs = fun2coeffs( ubc, n, dom(1:2) );
% Now compute an interpolant of the boundary data
BC(1,:) = (ubc_cfs + dbc_cfs)/2;
BC(2,:) = (ubc_cfs - dbc_cfs)/2;
BC(1:2,1) = (rbc_cfs(1:2) + lbc_cfs(1:2))/2 - sum(BC(1:2,3:2:end),2);
BC(1:2,2) = (rbc_cfs(1:2) - lbc_cfs(1:2))/2 - sum(BC(1:2,4:2:end),2);
BC(3:end,1) = (rbc_cfs(3:end) + lbc_cfs(3:end))/2;
BC(3:end,2) = (rbc_cfs(3:end) - lbc_cfs(3:end))/2;
% Adjust the rhs
% TODO: Remove this call to chebfun2
u_lap = lap( chebfun2(BC, dom, 'coeffs') );
u_lap = coeffs2( u_lap, m, n );
F = F - u_lap;
end
% Convert rhs to C^{(3/2)} coefficients:
F = cheb2ultra( cheb2ultra( F ).' ).';
% Construct M, the multiplication matrix for (1-x^2) in the C^(3/2) basis
jj = (0:n-1)';
dsub = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj+2);
dsup = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj);
d = -dsub - dsup;
Mn = spdiags([dsub d dsup], [-2 0 2], n, n);
% Construct D^{-1}, which undoes the scaling from the Laplacian identity
invDn = spdiags(-1./(jj.*(jj+3)+2), 0, n, n);
Tn = scl_y * invDn * Mn;
jj = (0:m-1)';
dsub = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj+2);
dsup = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj);
d = -dsub - dsup;
Mm = spdiags([dsub d dsup], [-2 0 2], m, m);
invDm = spdiags(-1./(jj.*(jj+3)+2), 0, m, m);
% Construct T = D^{-1} * M:
Tm = scl_x * invDm * Mm;
F = invDm * F * invDn;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%% Alternating Direction Implicit method %%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Solve TmX + XTn' = F using ADI, which requires O(n^2log(n)log(1/eps))
% operations:
% Calculate ADI shifts based on bounds on the eigenvalues of Tn and Tm:
a = -4/pi^2 * scl_y;
b = -39*n^-4 * scl_y;
c = 39*m^-4 * scl_x;
d = 4/pi^2 * scl_x;
[p, q] = ADIshifts(a, b, c, d, tol);
% Run the ADI method:
A = Tm; B = -Tn;
% Extract diagonals from A and B and call ADI C code
da = diag(A); db = diag(B);
ua = diag(A,2); ub = diag(B,2);
la = diag(A,-2); lb = diag(B,-2);
X = adi( da, ua, la, db, ub, lb, p, q, F );
% Convert back to Chebyshev
X = ultra1mx2cheb( ultra1mx2cheb( X ).' ).';
X = X + BC;
end
function cfs = fun2coeffs( fun, n, dom )
% Convert from a function handle to Chebyshev coefficients
vals = fun( chebpts(n, dom) );
cfs = chebtech2.vals2coeffs( vals );
end
|
github
|
andregouws/mrMeshPy-master
|
meshBuild_mrMeshPy.m
|
.m
|
mrMeshPy-master/matlabRoutines/meshBuild_mrMeshPy.m
| 7,428 |
utf_8
|
cd89bff29e221fafb60854fb3e73728c
|
function [vw,newMeshNum] = meshBuild_mrMeshPy(vw,hemisphere)
% COPY OF ORIGINAL meshBuild adapted for mrMeshPy - AG 2017
% Build a 3D mesh for visualization and analysis
%
% [vw,newMeshNum,meshBuildPath] = meshBuild(vw,[hemisphere],meshBuildPath);
%
% Using mrVista data, build a mesh, save it in a file in the anatomy
% directory, and add the mesh to the 3D Control Window pull down
% options.
%
% vw: A VISTASOFT view structure
% hemisphere: left, right or both. Default: left
%
% A mrMeshPy window is opened as well, showing the computed mesh.
%
% Example:
% [VOLUME{1},newMeshNum,meshBuildPath] = meshBuild(VOLUME{1},'left','/home/user/mrMeshPy/matlabRoutines');
% VOLUME{1} = viewSet(VOLUME{1},'currentmeshn',newMeshNum);
%
% See also: meshBuildFromClass, meshBuildFromNiftiClass, meshSmooth,
% meshColor
%
% 11/05 ras: also saves mesh path.
%
% (c) Stanford VISTA Team 2008
%
%
% Programming TODO. Check this!
% We have (or had?) trouble for building 'both' meshes. We need a new
% procedure.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COPY OF ORIGINAL meshBuild adapted for mrMeshPy - AG 2017 - in trying to
% keep as many things consistent with the previous mrMesh, I have stripped
% out this part of the stream and changed the bits we need for mrMeshPy
% This cascade calls adapted versions of mrmBuild and meshBuildFromClass
% Andre Gouws 2017
disp 'meshBuild called'
% Be sure anatomy is loaded (we need it for the mmPerVox field)
if isempty(vw.anat), vw = loadAnat(vw); end
if ieNotDefined('hemisphere'), hemisphere = 'left'; end
newMeshNum = viewGet(vw,'nmesh') + 1;
% Parameters we establish in this routine
[meshName,numGrayLayers,hemiNum] = readParams(newMeshNum,hemisphere);
if isempty(meshName), newMeshNum = newMeshNum - 1; return; end % User pressed cancel.
% mmPerVox = viewGet(vw,'mmPerVoxel');
wbar = mrvWaitbar(0.1, ...
sprintf('meshBuild: Combining white and gray matter...'));
% Load left, right, or both hemispheres.
if (hemiNum==1)
[voxels,vw] = meshGetWhite(vw, 'left', numGrayLayers);
elseif (hemiNum==2)
[voxels,vw] = meshGetWhite(vw, 'right', numGrayLayers);
elseif (hemiNum == 0)
[voxels,vw] = meshGetWhite(vw, 'left', numGrayLayers);
[voxels,vw] = meshGetWhite(vw, 'right', numGrayLayers,voxels);
end
% host = 'localhost';
% windowID = -1;
% We build a smoothed (mesh) and an unsmoothed mesh (tenseMesh) with these calls
mrvWaitbar(0.35,wbar,sprintf('Building mesh'));
[newMesh, tenseMesh] = mrmBuild_mrMeshPy(voxels,viewGet(vw,'mmPerVox'),1);
% Must have a name
newMesh = meshSet(newMesh,'name',meshName);
tenseMesh = meshSet(tenseMesh,'name',sprintf('%s-tense',meshName));
% mrvWaitbar(0.65,wbar,sprintf('meshBuild: Unsmoothed mesh vertex to gray mapping'));
initVertices = meshGet(tenseMesh,'vertices');
newMesh = meshSet(newMesh,'initialvertices',initVertices);
vertexGrayMap = mrmMapVerticesToGray(...
initVertices, ...
viewGet(vw,'nodes'), ...
viewGet(vw,'mmPerVox'),...
viewGet(vw,'edges'));
newMesh = meshSet(newMesh,'vertexGrayMap',vertexGrayMap);
newMesh = meshSet(newMesh,'name',meshName);
newMesh = meshSet(newMesh,'nGrayLayers',numGrayLayers);
mrvWaitbar(0.9,wbar,sprintf('meshBuild: Saving mesh file %s',meshGet(newMesh,'name')));
% Save mesh file
[newMesh newMesh.path] = mrmWriteMeshFile(newMesh);
mrvWaitbar(1,wbar,sprintf('meshBuild: Done'));
pause(0.5);
close(wbar);
% Now refresh the UI
vw = viewSet(vw,'add and select mesh',newMesh);
return;
%---------------------------------------
function classFile = verifyClassFile(vw,hemisphere)
classFile = viewGet(vw,'classFileName',hemisphere);
str = sprintf('Class %s',classFile);
r=questdlg(str);
if ~strcmp(r,'Yes')
switch hemisphere
case 'left'
vw = viewSet(vw,'leftClassFileName',[]);
case 'right'
vw = viewSet(vw,'rightClassFileName',[]);
end
classFile = viewGet(vw,'classFileName',hemisphere);
end
return;
%---------------------------------------
function voxels = classExtractWhite(voxels,data,voi,whiteValue)
%
% ras 05/07: the indexing of data seems off to me -- is this correct?
voxels(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) = ...
voxels(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) ...
| (data(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) == whiteValue);
return;
%----------------------------------------
function [meshName,numGrayLayers,hemiNum,alpha,restrictVOI,relaxIterations] = ...
readParams(newMeshNum,hemisphere)
%
% readParams
%
% Internal routine to read the parameters for meshBuild
%
meshName = sprintf('%sSmooth',hemisphere);
numGrayLayers = 0;
switch hemisphere
case 'left'
hemiNum = 1;
case 'right'
hemiNum = 2;
case 'both'
hemiNum = 0;
end
% transparency level (transparency is off by default, but if it gets turned
% on, this alpha parameter will have an effect).
alpha = 200;
restrictVOI = 1;
relaxIterations = 0.2;
prompt = {'Mesh Name:',...
'Number of Gray Layers (0-4):',...
'Hemisphere (0=both, 1=left, 2=right):',...
% 'Default alpha (0-255):',...
% 'Inflation (0=none, 1=lots):',...
% 'Restrict to class VOI (0|1):'};
};
defAns = {meshName,...
num2str(numGrayLayers),...
num2str(hemiNum),...
% num2str(alpha),...
% num2str(relaxIterations),...
% num2str(restrictVOI)};
};
resp = inputdlg(prompt, 'meshBuild Parameters', 1, defAns);
if(~isempty(resp))
meshName = resp{1};
numGrayLayers = str2num(resp{2});
hemiNum = str2num(resp{3});
% alpha = str2num(resp{4});
% relaxIterations = round(str2num(resp{5})*160); % Arbitrary choice, scales iters [0,160]
% restrictVOI = str2num(resp{6});
else
meshName = [];
numGrayLayers = [];
hemiNum = [];
% alpha = [];
% relaxIterations = []; % Arbitrary choice, scales iters [0,160]
% restrictVOI = [];
end
return;
%---------------------------------
function [voxels,vw] = meshGetWhite(vw, hemiName, numGrayLayers, voxels)
%
%
%
if ieNotDefined('vw'), error('You must send in a volume vw'); end
if ieNotDefined('hemiName'), error('You must define right,left or both'); end
if ieNotDefined('numGrayLayers'), numGrayLayers = 0; end
classFile = verifyClassFile(vw,hemiName);
if isempty(classFile),
close(wbar); newMeshNum = -1;
voxels = [];
return;
end
classFileParam = [hemiName,'ClassFile'];
vw = viewSet(vw,classFileParam,classFile);
classData = viewGet(vw,'classdata',hemiName);
if ieNotDefined('voxels'),
voxelsOld = uint8(zeros(classData.header.xsize, ...
classData.header.ysize, ...
classData.header.zsize));
else
voxelsOld = voxels;
end
voxels = zeros(classData.header.xsize, ...
classData.header.ysize, ...
classData.header.zsize);
% Restrict the white matter volume to a size equal to the ROI in which it
% was selected
voxels = classExtractWhite(voxels,...
classData.data,classData.header.voi,classData.type.white);
% msh = meshColor(meshSmooth(meshBuildFromClass(voxels,[1 1 1])));
% meshVisualize(msh);
% Add the gray matter
if(numGrayLayers>0)
[nodes,edges,classData] = mrgGrowGray(classData,numGrayLayers);
voxels = ...
uint8( (classData.data == classData.type.white) | ...
(classData.data == classData.type.gray));
end
voxels = uint8(voxels | voxelsOld);
return;
|
github
|
andregouws/mrMeshPy-master
|
gui_3dWindow_MeshPy.m
|
.m
|
mrMeshPy-master/matlabRoutines/gui_3dWindow_MeshPy.m
| 13,690 |
utf_8
|
76cdbce38b30bf8891fc8e73e619c3e5
|
function varargout = gui_3dWindow_MeshPy(varargin)
% GUI_3DWINDOW_MESHPY MATLAB code for gui_3dWindow_MeshPy.fig
% GUI_3DWINDOW_MESHPY, by itself, creates a new GUI_3DWINDOW_MESHPY or raises the existing
% singleton*.
%
% H = GUI_3DWINDOW_MESHPY returns the handle to a new GUI_3DWINDOW_MESHPY or the handle to
% the existing singleton*.
%
% GUI_3DWINDOW_MESHPY('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI_3DWINDOW_MESHPY.M with the given input arguments.
%
% GUI_3DWINDOW_MESHPY('Property','Value',...) creates a new GUI_3DWINDOW_MESHPY or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_3dWindow_MeshPy_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_3dWindow_MeshPy_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui_3dWindow_MeshPy
% Last Modified by GUIDE v2.5 26-Sep-2017 13:56:57
% Andre' Gouws 2017
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_3dWindow_MeshPy_OpeningFcn, ...
'gui_OutputFcn', @gui_3dWindow_MeshPy_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% Hack - TODO fix - this puts the VOLUME in the scope of this gui
VOLUME = evalin('base','VOLUME','VOLUME'); %% HACK TODO fix
% --- Executes just before gui_3dWindow_MeshPy is made visible.
function gui_3dWindow_MeshPy_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui_3dWindow_MeshPy (see VARARGIN)
% Choose default command line output for gui_3dWindow_MeshPy
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui_3dWindow_MeshPy wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = gui_3dWindow_MeshPy_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%% disabled for now - TODO
% --- Executes on button press in launch_button.
function launch_button_Callback(hObject, eventdata, handles)
[myfile,mydir]= uigetfile({'*.mat','MAT-files (*.mat)'});
meshFilePath = [mydir,myfile];
myPid = num2str(feature('getpid'));
if ~isfield(VOLUME{1},'meshNum3d') %% TODO - this willneed to reflect the current volume and x-ref the correct mesh
meshInstance = '1';
else
meshInstance = num2str(VOLUME{1}.meshNum3d + 1);
end
evalstr = ['/home/andre/mrMeshPy/launchMeshPy.sh /home/andre/mrMeshPy/meshPy_v03.py ',meshFilePath,' ',myPid,' ',meshInstance,' &'];
disp(['ran command: ', evalstr]);
system(evalstr);
%%
% --- Executes on button press in pushbutton_update.
function pushbutton_update_Callback(hObject, eventdata, handles)
mrGlobals;
set( findall(handles.uipanel1, '-property', 'Enable'), 'Enable', 'off')
try
currMesh = VOLUME{1}.meshNum3d;
[VOLUME{1},~,~,~,VOLUME{1}.mesh{currMesh}] = meshColorOverlay(VOLUME{1},0);
mrMeshPySend('updateMeshData',VOLUME{1});
catch
disp 'error in update mesh routine';
end
set( findall(handles.uipanel1, '-property', 'Enable'), 'Enable', 'On')
% --- Executes on button press in pushbutton_LoadMesh.
function pushbutton_LoadMesh_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_LoadMesh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mrGlobals;
% keep tack of whether the VOLUME actually changes - i.e. make sure a new
% mesh has been loaded and the user hasn't hit cancel
try
currMeshCount = length(VOLUME{1}.mesh);
catch
currMeshCount = 0;
end
% load the mesh to the VOLUME struct
VOLUME{1} = meshLoad(VOLUME{1},'./'); %start in the current directory for now %TODO later give options?
try length(VOLUME{1}.mesh)
if length(VOLUME{1}.mesh) > currMeshCount %a new mesh has been added
% create a unique ID for the mesh based on a timestamp (clock)
VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID = makeUniqueID;
% send the newly loaded mesh to the viewer via the VOLUME
mrMeshPySend('sendNewMeshData',VOLUME{1});
handles = guidata(hObject); % Update!
currString = get(handles.popupmenu_Meshes,'string')
if strcmp(currString,'None')
newstring = char(['mesh-',VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID]);
else
newstring = char(currString,['mesh-',VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID]);
end
%disp 'here1'
%VOLUME{1}.meshNum3d
set(handles.popupmenu_Meshes,'value',VOLUME{1}.meshNum3d) ;
set(handles.popupmenu_Meshes,'string',newstring);
%disp 'here2'
else % no new mesh added
disp('User cancelled mesh load or there was an error loading ...');
end
catch % no new mesh added
disp('User cancelled mesh load or there was an error loading ...');
end
% --- Executes on selection change in popupmenu_Meshes.
function popupmenu_Meshes_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_Meshes (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_Meshes contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_Meshes
mrGlobals;
% % %assignin('base','hObj',hObject)
% % %contents = cellstr(get(hObject,'String'))
% % %meshNum = contents{get(hObject,'Value')}
meshNum = hObject.Value; %should be the index
%%%meshNum = meshNum(5:end); %TODO improve
VOLUME{1}.meshNum3d = meshNum;
% --- Executes during object creation, after setting all properties.
function popupmenu_Meshes_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_Meshes (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_getROI.
function pushbutton_getROI_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_getROI (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mrGlobals;
mrMeshPySend('checkMeshROI',VOLUME{1});
% --- Executes on button press in pushbutton_smooth.
function pushbutton_smooth_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_smooth (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mrGlobals;
handles = guidata(hObject); % Update!
relax = get(handles.edit_relaxationFactor,'String')
iterations = get(handles.edit_iterations,'String')
relax = str2num(relax);
iterations = str2num(iterations);
%assignin('base','iterations',iterations);
%assignin('base','relax',relax);
currMeshID = VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID;
%disp('here1')
% send (with VOLUME also)
mrMeshPySend('smoothMesh',{currMeshID,iterations,relax,VOLUME{1}});
function edit_relaxationFactor_Callback(hObject, eventdata, handles)
% hObject handle to edit_relaxationFactor (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 edit_relaxationFactor as text
% str2double(get(hObject,'String')) returns contents of edit_relaxationFactor as a double
% --- Executes during object creation, after setting all properties.
function edit_relaxationFactor_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_relaxationFactor (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 edit_iterations_Callback(hObject, eventdata, handles)
% hObject handle to edit_iterations (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 edit_iterations as text
% str2double(get(hObject,'String')) returns contents of edit_iterations as a double
% --- Executes during object creation, after setting all properties.
function edit_iterations_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_iterations (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_buildMesh.
function pushbutton_buildMesh_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_buildMesh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mrGlobals;
handles = guidata(hObject)
set( findall(handles.uipanel1, '-property', 'Enable'), 'Enable', 'off')
%try
% get user option or left or right
[s,v] = listdlg('PromptString','Select hemisphere:',...
'SelectionMode','single',...
'ListString',{'left','right'});
if s == 1
hemi = 'left';
elseif s == 2
hemi = 'right';
else
disp('error selecting mesh');
return
end
% build the mesh
VOLUME{1} = meshBuild_mrMeshPy(VOLUME{1}, hemi);
% ask if we would like to load to mrMeshPy?
% Include the desired Default answer
options.Interpreter = 'tex';
options.Default = 'Yes';
% Use the TeX interpreter in the question
qstring = 'Would you like to load the mesh to mrMeshPy?';
loadNow = questdlg(qstring,'Mesh ready .. load?',...
'Yes','No',options)
if strcmp(loadNow,'No')
return
else
%assume yes
% create a unique ID for the mesh based on a timestamp (clock)
VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID = makeUniqueID;
% send the newly loaded mesh to the viewer
mrMeshPySend('sendNewMeshData',VOLUME{1});
handles = guidata(hObject); % Update!
currString = get(handles.popupmenu_Meshes,'string')
if strcmp(currString,'None')
newstring = char(['mesh-',VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID]);
else
newstring = char(currString,['mesh-',VOLUME{1}.mesh{VOLUME{1}.meshNum3d}.mrMeshPyID]);
end
set(handles.popupmenu_Meshes,'value',VOLUME{1}.meshNum3d) ;
set(handles.popupmenu_Meshes,'string',newstring);
end
%catch
% disp 'error in build mesh routine';
%end
set( findall(handles.uipanel1, '-property', 'Enable'), 'Enable', 'On')
|
github
|
andregouws/mrMeshPy-master
|
meshAmplitudeMaps.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshAmplitudeMaps.m
| 13,889 |
utf_8
|
97f639d9be02689fcb8ab234637239b1
|
function [images, mapVals] = meshAmplitudeMaps(V, dialogFlag, varargin);
% Produce images of response amplitudes (estimated one of a number of
% different ways) for different event-related conditions on a mesh.
%
% NOTE: this will modify the 'map' field of the view.
%
% USAGE:
% [images mapVals] = meshAmplitudeMaps(grayView, [dialogFlag], [options]);
%
% INPUTS:
% grayView: mrVista gray view, with a mesh open. Will show maps on the
% currently-selected mesh, if there are more than one. The gray view
% should have a 'GLMs' data type, and be pointed at the appropriate GLM
% from which to load amplitude information.
%
% useDialog: 1 to put up a dialog to set the parameters, 0 otherwise.
%
% options: options can be specified as 'optionName', [value], ...
% pairs. Options are below:
%
% ampType: one of 'z-score', 'subtracted-betas', or 'raw-betas'; a ampType
% for determining the amplitude of each voxel to each stimulus. The
% methods are as follows:
% 'raw-betas': raw beta coefficients from the GLM. Each value
% represents the estimated response of that voxel to the stimulus
% compared to the baseline condition.
%
% 'subtracted-betas': beta coefficients minus the "cocktail blank,"
% which is the mean beta value for that voxel, across all conditions.
%
% 'z-score': the subtracted-beta value, divided by the estimated
% standard devation for the model fitting. The standard deviation is
% defined as
% sqrt( residual ^2 / [degrees of freedom] )
% and reflects the goodness-of-fit of the GLM as a whole. This causes
% voxels with a poor GLM fit to have amplitudes closer to zero.
%
% plotFlag: flag to show the set of images returned in a montage. If 0,
% will not plot; if 1 will plot. You can also specify a size for the
% montage, as in plotFlag = [nRows, nCols]; otherwise the rows and
% columns will be approximately square.
%
% nRows, nCols: alternate method for specifying the montage size
% (rather than using the 'plotFlag' option described above).
%
% cropX, cropY: specify zoom ranges in the X and Y dimensions for each
% mesh image. If omitted, will show the entire mesh.
%
% whichConds: select only a subset of conditions to analyze. [By
% default, will present all conditions]. For the normalization
% amplitude types (subtracted-betas and z-scores), the choice of which
% conditions to include affects how the normalization is carried out.
%
% preserveCoords: flag to return mapVals with exactly the same number
% of columns as the ROI coordinates. If this is set to 1, and certain
% ROI coordinates don't have data, mapVals will have NaN for that
% column. If 0 [default], these columns are automatically removed
% from the matrix.
%
% OUTPUTS:
% images: nRows x nCols cell array containing mesh images for each
% condition in the GLM.
%
% mapVals: conditions x voxels matrix containing the amplitude values
% used in the map images for the selected ROI.
%
% ras, 03/2008.
if notDefined('V'), V = getSelectedGray; end
if notDefined('dialogFlag'), dialogFlag = (length(varargin)<=1); end
%% checks
% check that a mesh is loaded
msh = viewGet(V, 'CurMesh');
if isempty(msh)
error('Need to load a mesh.')
end
% check that a GLM has been run
if ~isequal(viewGet(V, 'DTName'), 'GLMs')
error('Need to be in the GLMs data type.')
end
% get scan num, # of non-null conditions
scan = viewGet(V, 'CurScan');
stim = er_concatParfiles(V);
N = length(stim.condNames) - 1; % omit baseline condition
%% params
% default params
preserveCoords = 0;
ampType = 'z-score';
whichMeshes = V.meshNum3d;
cropX = [1:512];
cropY = [1:512];
cmap = mrvColorMaps('coolhot', 128);
clim = [-2 2];
saveAmps = 0;
plotFlag = 1;
titleFlag = 1;
% figure out # of rows, cols for the image montage
if length(plotFlag) > 1
nRows = plotFlag(1);
nCols = plotFlag(2);
else
nRows = ceil( sqrt(N) );
nCols = ceil( N/nRows );
end
% grab the current map mode (which contains the color map and
% color limits) -- we'll assume these settings are the ones you want to
% apply to each map (loadParameterMap below may over-ride these in the view,
% so we restore them later):
mapMode = V.ui.mapMode;
mapWin = getMapWindow(V);
% get params from dialog if needed
if dialogFlag==1
[params ok] = meshAmplitudeMapGUI(V);
if ~ok, disp('User aborted'); return; end
ampType = params.ampType;
plotFlag = params.plotFlag;
titleFlag = params.titleFlag;
cropX = params.cropX;
if isempty(cropX), cropX = [1:512]; end
cropY = params.cropY;
if isempty(cropY), cropY = [1:512]; end
preserveCoords = params.preserveCoords;
whichConds = params.whichConds;
whichMeshes = params.whichMeshes;
cmap = params.cmap;
clim = params.clim;
nRows = params.montageSize(1);
nCols = params.montageSize(2);
saveAmps = params.saveAmps;
if length(V.ROIs) >= 1 & ~isequal(params.maskRoi, 'none')
% we modify the view's ROIs here, but don't return the modified
% view:
oldROIs = V.ROIs;
oldSelROI = V.selectedROI;
roiNum = findROI(V, params.maskRoi);
V.ROIs = V.ROIs(roiNum);
V.ROIs.name = 'mask';
V.selectedROI = 1;
end
end
% set the map mode settings to reflect the request color map and limits
if ischar(cmap)
mapMode.cmap = [gray(128); mrvColorMaps(cmap, 128)];
else
mapMode.cmap = [gray(128); cmap];
end
mapMode.clipMode = clim;
% parse options (these will override the dialog values)
for ii = 1:2:length(varargin)
val = varargin{ii+1};
eval( sprintf('%s = val;', varargin{ii}) );
end
%% if the beta maps haven't been xformed from inplanes, do it now
testFile = fullfile( dataDir(V), sprintf('betas-predictor%i.mat', N) );
if ~exist(testFile, 'file')
hI = initHiddenInplane('GLMs', 1);
for i = 1:N % loop across conditions
mapPath = fullfile(dataDir(hI), 'RawMaps', ...
sprintf('betas_predictor%i.mat', i));
hI = loadParameterMap(hI, mapPath);
V = ip2volParMap(hI, V, 0, 1, 'linear'); % trilinear interpolation
mapPath = fullfile(dataDir(hI), 'RawMaps', ...
sprintf('stdDev_predictor%i.mat', i));
hI = loadParameterMap(hI, mapPath);
V = ip2volParMap(hI, V, 0, 1, 'linear');
end
hI = loadParameterMap(hI, 'Residual Variance.mat');
V = ip2volParMap(hI, V, 0, 1, 'linear');
end
if notDefined('whichConds'),
whichConds=1:1:N;
else
N=length(whichConds);
end
%% get the amplitude estimate for each voxel
switch lower(ampType)
case 'subtracted-betas'
for i = 1:N
n=whichConds(i);
mapName = sprintf('betas-predictor%i', n);
V = loadParameterMap(V, mapName);
mapVals(i,:) = V.map{scan};
end
% remove the "cocktail blank" or mean of all conditions for each voxel
mapVals = mapVals - repmat( nanmean(mapVals), [N 1] );
case {'raw-betas' 'rawbetas' 'raw betas'}
for i = 1:N
n=whichConds(i);
mapName = sprintf('betas-predictor%i', n);
V = loadParameterMap(V, mapName);
mapVals(i,:) = V.map{scan};
end
case {'z-score' 'z score' 'zscore'}
% load the betas
for i = 1:N
n=whichConds(i);
mapName = sprintf('betas-predictor%i', n);
V = loadParameterMap(V, mapName);
mapVals(i,:) = V.map{scan};
end
% load the residual variance map
V = loadParameterMap(V, 'Residual Variance');
sigmaVals = V.map{scan};
% convert from res. var -> std. dev
% (we need some info from the GLM model: degrees of freedom)
modelFile = sprintf('Inplane/GLMs/Scan%i/glmSlice1.mat', scan);
load(modelFile, 'dof');
sigmaVals = sqrt( sigmaVals .^ 2 ./ dof );
% remove the "cocktail blank" or DC component for each voxel
mapVals = mapVals - repmat( nanmean(mapVals), [N 1] );
% now, normalize by dividing by the estimated residual variance at
% each voxel
mapVals = mapVals ./ repmat( sigmaVals, [N 1] );
otherwise
error('Invalid amplitude type.')
end
%% main loop -- get the images
for n = 1:N
% for convenient storage, know what category/position this is:
% (we fill the conditions in row-major order: march across columns)
row = ceil(n / nCols);
col = mod(n-1, nCols) + 1;
% set the map values
V.map = cell(1, numScans(V));
V.map{scan} = mapVals(n,:);
% set the color map and color limits
% (the saved param map may have over-set this):
V.ui.mapMode = mapMode;
V = setMapWindow(V, mrvMinmax(V.map{scan}));
for h = 1:length(whichMeshes)
% update the mesh
V.meshNum3d = whichMeshes(h);
meshColorOverlay(V);
% grab the image
img{h} = mrmGet(V.mesh{whichMeshes(h)}, 'screenshot') ./ 255;
% crop the image if requested
if ~isempty(cropX) & ~isempty(cropY)
img{h} = img{h}(cropY,cropX,:);
end
end
% add image to list of images
% (make montage if taking a shot of multiple meshes)
if length(whichMeshes)==1
images{row, col} = img{1};
else
images{row, col} = imageMontage(img, 1, length(whichMeshes));
end
end
%% restore the ROIs if we were masking
if exist('oldROIs', 'var')
V.ROIs = oldROIs;
V.selectedROI = oldSelROI;
updateGlobal(V);
if checkfields(V, 'ui', 'windowHandle')
refreshScreen(V);
end
end
%% display the images if selected
if ~isequal(plotFlag, 0)
% we'll want the event-related info for the condition names
trials = er_concatParfiles(V);
% we'll manually specify subplot sizes -- large:
if titleFlag==1
% we'll want to space out the axes to allow space for the condition
% labels
width = (1 / nCols) * 0.8;
height = (1 / nRows) * 0.8;
else
% the images will be flush against one another
width = 1 / nCols;
height = 1 / nRows;
end
% open the figure
figure('Units', 'norm', 'Position', [0.2 0 .7 .35], 'Name', 'Mesh Images');
% plot each mesh image in a subplot:
% allow for some images to be omitted if the user specified
% a montage size that is smaller than the # of images
% (e.g., an extra 'scrambled' condition)
for n = 1:nRows*nCols
row = ceil(n / nCols);
col = mod(n-1, nCols) + 1;
subplot('Position', [(col-1)*width, 1 - row*height, width, height]);
imagesc(images{row,col}); axis image; axis off;
if titleFlag==1
cond = whichConds(n) + 1; % +1 for baseline condition name
title(trials.condNames{cond});
end
end
% add a colorbar
cmap = viewGet(V, 'OverlayColormap');
clim = viewGet(V, 'MapClim');
cbar = cbarCreate(cmap, ampType, 'Clim', clim);
hPanel = mrvPanel('below', .2);
hAxes = axes('Parent', hPanel, 'Units', 'norm', 'Position', [.3 .5 .4 .2]);
cbarDraw(cbar, hAxes);
end
%% export the amplitudes to a series of parameter maps if requested
if saveAmps==1
for n = 1:N
map = cell(1, numScans(V));
map{scan} = mapVals(n,:);
mapUnits = ampType;
mapUnits(1) = upper(mapUnits(1));
mapName = sprintf('%s Condition %i', mapUnits, whichConds(n));
mapPath = fullfile(dataDir(V), [mapName '.mat']);
save(mapPath, 'map', 'mapName', 'mapUnits');
if prefsVerboseCheck >= 1
fprintf('Exported amplitudes to map %s.\n', mapPath);
end
end
end
%% return map values for the ROI if requested
if nargout > 1
if isempty(V.ROIs)
I = 1:size(mapVals, 2);
else
I = roiIndices(V, V.ROIs(end).coords, preserveCoords);
end
mapVals = mapVals(:,I);
end
return
% /----------------------------------------------------------------------/ %
% /----------------------------------------------------------------------/ %
function [params ok] = meshAmplitudeMapGUI(V);
% dialog to get parameters for meshAmplitudeMaps.
stim = er_concatParfiles(V);
dlg(1).fieldName = 'ampType';
dlg(end).style = 'popup';
dlg(end).list = {'z-score' 'subtracted-betas' 'raw-betas'};
dlg(end).value = 1;
dlg(end).string = 'Plot what type of amplitude metric?';
dlg(end+1).fieldName = 'whichConds';
dlg(end).style = 'number';
dlg(end).value = 1:length(stim.condNums)-1;
dlg(end).string = 'Plot which conditions?';
dlg(end+1).fieldName = 'whichMeshes';
dlg(end).style = 'listbox';
for n = 1:length(V.mesh)
meshList{n} = sprintf('%i: %s', V.mesh{n}.id, V.mesh{n}.name);
end
dlg(end).list = meshList;
dlg(end).value = V.meshNum3d;
dlg(end).string = 'Project data onto which meshes?';
dlg(end+1).fieldName = 'cropX';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Mesh X-axis image crop (empty for no crop)?';
dlg(end+1).fieldName = 'cropY';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Mesh Y-axis image crop (empty for no crop)?';
nConds = length(stim.condNums) - 1;
nRows = ceil( sqrt(nConds) );
nCols = ceil( nConds/nRows );
dlg(end+1).fieldName = 'montageSize';
dlg(end).style = 'number';
dlg(end).value = [nRows nCols];
dlg(end).string = 'Montage layout ([nrows ncolumns])?';
dlg(end+1).fieldName = 'cmap';
dlg(end).style = 'popup';
dlg(end).list = mrvColorMaps; % list of available cmaps
dlg(end).value = 'coolhot';
dlg(end).string = 'Color map for amplitudes?';
if length(V.ROIs) >= 1
dlg(end+1).fieldName = 'maskRoi';
dlg(end).style = 'popup';
dlg(end).list = [{'none'} {V.ROIs.name}];
dlg(end).value = 'none';
dlg(end).string = 'Mask activations within which ROI?';
end
dlg(end+1).fieldName = 'clim';
dlg(end).style = 'number';
dlg(end).value = [-2 2];
dlg(end).string = 'Color limits for amplitudes?';
dlg(end+1).fieldName = 'preserveCoords';
dlg(end).style = 'checkbox';
dlg(end).value = 0;
dlg(end).string = 'Preserve ROI coordinates in returned values?';
dlg(end+1).fieldName = 'saveAmps';
dlg(end).style = 'checkbox';
dlg(end).value = 0;
dlg(end).string = 'Save amplitudes as a set of parameter maps?';
dlg(end+1).fieldName = 'plotFlag';
dlg(end).style = 'checkbox';
dlg(end).value = 1;
dlg(end).string = 'Plot Results?';
dlg(end+1).fieldName = 'titleFlag';
dlg(end).style = 'checkbox';
dlg(end).value = 1;
dlg(end).string = 'If plotting results, show condition names?';
[params ok] = generalDialog(dlg, 'Mesh Amplitude Maps');
[ignore, params.whichMeshes] = intersect(meshList, params.whichMeshes);
return
|
github
|
andregouws/mrMeshPy-master
|
meshMovie.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshMovie.m
| 6,594 |
utf_8
|
e3b919c3ceea47b03a0b613e1ad149cc
|
function M = meshMovie(V, roiFlag, movieFileName, timeSteps, plotFlag)
%
% M = meshMovie([gray view], [roiFlag=-1], [movieFileName], [timeSteps=12], [plotFlag=1])
%
%Author: Wandell
%Purpose:
% Create a movie of the fundamental component of the time series based on
%
% the coherence and phase measurement.
% This is not the real time series, but just a signal-approximation.
% At some point, we should read in the time series and show it frame by
% frame. I am not quite sure how to do this. We don't normally get a
% time-slice over space. But I am guessing we could do it.
%
% roiFlag: flag indicating whether to illustrate a disc ROI during the
% movie. If this flag is set to zero, no ROI will be shown. If it is
% greater than 0, the value is taken to be the radius of the ROI disc
% around the mesh cursor (those 3-axes things you get when
% double-clicking on the mesh). If it is set to -1, all ROIs currently
% defined in the view will be shown.
%
% Example: To make a movie with 10 steps, write out an AVI file called scratch,
% and to return a Matlab movie structure, M, within the constraints of the
% cothresh and ROI parameters, use:
%
% M = meshMovie([], [], 'scratch', 10, 0);
%
% To get the last 3 arguments from a dialog, use:
% M = meshMovie('dialog');
% or
% M = meshMovie(gray, [], 'dialog');
%
% ras 04/2008: modularized this more. Added view as an inputtable argument,
% instead of that VOUME{selectedVOLUME} stuff, added the roiFlag so you
% don't always need an ROI, and had the code only throw up a dialog if you
% didn't already give it the parameters it needs.
% ras 07/2008: added plot flag, updated calling of parameters dialog.
if notDefined('V'), V = getSelectedGray; end
if notDefined('roiFlag'), roiFlag = -1; end
if notDefined('plotFlag'), plotFlag = 1; end
if notDefined('timeSteps'), timeSteps = 12; end
if isequal(timeSteps, 'dialog') | isequal(movieFileName, 'dialog') | ...
isequal(V, 'dialog')
[timeSteps, movieFileName, plotFlag] = readParameters(12, 'Movies/Scratch', 1);
end
% Make sure the cor anal data are loaded
if isempty(viewGet(V, 'co')), V=loadCorAnal(V); end
msh = viewGet(V, 'currentmesh');
if roiFlag==0
% hide ROIs
V.ui.showROIs = 0;
elseif roiFlag > 0
% mask in ROI
pos = meshCursor2Volume(V, msh);
if isempty(pos) | max(pos(:)) > 255,
myWarnDlg('Problem reading cursor position. Click and try again.');
return
end
% Build an ROI of the right size.
roiName = sprintf('mrm-%.0f-%.0f-%.0f', pos(1), pos(2), pos(3));
[V discROI] = makeROIdiskGray(V, roiFlag, roiName, [], [], pos, 0);
V.ROIs = discROI;
V.ui.showROIs = -1; % show only this, selected ROI
end
if roiFlag > 0
% Create a view with the ROI defined. It will sit in the window for a
% moment.
[V, roiMask, junk, roiAnatColors] = meshColorOverlay(V, 0);
if sum(roiMask) == 0, error('Bad roiMask'); end
msh = mrmSet(msh, 'colors', roiAnatColors');
end
% Set up the co or amp values for the movie. We replace the colors within
% the dataMask with the new colors generated here.
curScan = viewGet(V, 'currentscan');
realCO = viewGet(V, 'scanco', curScan);
ph = viewGet(V, 'scanph', curScan);
t = ([0:(timeSteps-1)]/timeSteps) * 2 * pi;
nFrame = length(t);
mrmSet(msh, 'hidecursor');
verbose = prefsVerboseCheck;
if verbose
str = sprintf('Creating %.0f frame movie', nFrame);
wbar = mrvWaitbar(0, str);
end
% change the view to display the coherence field, since we're actually
% displaying phase-projected coherence for each time point:
% I specificially make this change without calling setDisplayMode, because
% that accessor function will try to do concurrent GUI things like setting
% a colorbar and loading/clearing data fields. We don't want to do this,
% because we're treating the view V as a local variable; changes we make to
% V are not intended to propagate back to the GUI. So, if the user was e.g.
% looking at a coherence map before this, we don't want him/her to suddenly
% see the phase-projected data from the movie.
V.ui.displayMode = 'co';
for ii=1:nFrame
if verbose % udpate mrvWaitbar
str = sprintf('Creating frame %.0f of %.0f', ii, nFrame);
fname{ii} = sprintf('Movie%0.4d.tiff', ii);
mrvWaitbar(ii/nFrame, wbar, str);
end
% compute the projected coherence relative to this time point
data = realCO.*(1 + sin(t(ii) - ph))/2;
V = viewSet(V, 'scancoherence', data, curScan);
% update the mesh view with the colors for this time step
if roiFlag > 0
[V, roiMask, foo, newColors] = meshColorOverlay(V, 0);
msh = mrmSet(msh, 'colors', newColors');
roiAnatColors(1:3, logical(roiMask)) = newColors(1:3, logical(roiMask));
msh = mrmSet(msh, 'colors', roiAnatColors');
else
meshColorOverlay(V, 1);
end
M(:,:,:,ii) = mrmGet(msh, 'screenshot') / 255;
end
if verbose, mrvWaitbar(1, wbar); close(wbar); end
%% show the movie in a separate figure
if plotFlag==1
% show in MPLAY utility
mov = mplay(M, 3);
mov.loop;
mov.play;
elseif plotFlag==2
% show in figure (old way)
for ii = 1:size(M, 4)
mov(ii) = im2frame(M(:,:,:,ii));
end
h = figure('Color', 'w', 'UserData', M);
imagesc(img); axis image; axis off;
movie(mov, 5, 4)
end
if ~isempty(movieFileName)
% allow the movie path to specify directories that don't yet exist
% (like 'Movies/')
ensureDirExists( fileparts(fullpath(movieFileName)) );
fprintf('Saving movie as avi file: %s\n', [pwd, filesep, movieFileName]);
if(isunix)
aviSave(M, movieFileName, 3, 'compression', 'none');
else
aviSave(M, movieFileName, 3, 'QUALITY', 100, 'compression', 'Indeo5');
end
end
return;
%------------------------------------
function [timeSteps, movieFileName, plotFlag] = readParameters(timeSteps, movieFileName, plotFlag);
%
% read parameters for meshMovie
%
dlg(1).fieldName = 'timeSteps';
dlg(1).style = 'number';
dlg(1).string = 'Number of time frames for movie?';
dlg(1).value = num2str(timeSteps);
dlg(2).fieldName = 'movieFileName';
dlg(2).style = 'filenamew';
dlg(2).string = 'Name of AVI movie file? (Empty for no movie file)';
dlg(2).value = movieFileName;
dlg(3).fieldName = 'plotFlag';
dlg(3).style = 'popup';
dlg(3).list = {'Don''t plot' 'Use MPLAY movie player' 'Movie in figure'};
dlg(3).string = 'Show movie in a MATLAB figure?';
dlg(3).value = plotFlag+1;
[resp ok] = generalDialog(dlg, 'Mesh movie options');
if ~ok
error(sprintf('%s aborted.', mfilename));
end
timeSteps = resp.timeSteps;
movieFileName = resp.movieFileName;
plotFlag = cellfind(dlg(3).list, resp.plotFlag) - 1;
return;
|
github
|
andregouws/mrMeshPy-master
|
meshMultiAngle2.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshMultiAngle2.m
| 7,661 |
utf_8
|
271092ab39b79bd252b57cbb985160e0
|
function img = meshMultiAngle2(msh, settings, savePath, cbarFlag, msz);
% Takes a picture of a mesh at multiple camera settings, and saves as a
% .png in a directory or pastes in a PowerPoint file.
%
% img = meshMultiAngle2([mesh], [settings], [save directory or .ppt file],
% [cbarFlag], [montageSize]);
%
% mesh: mesh structure of which to take pictures. [Defaults to current
% mesh of selected mrVista gray view]
% settings: struct array specifying the camera settings for each picture.
% Each entry should have a 'cRot' field which specifies
% the camera settings (see meshAngle).
% Can also specify a vector of integers, with the indices into
% the saved settings struct (using meshAngle). E.g. [1 3 2 4]
% will display the 1st, 3rd, 2nd, and 4th settings, in that order.
% [If omitted, opens a dialog to select settings from the saved settings
% -- again, see meshAngle.]
% savePath: directory in which to save a .png file of the image, or
% else path to a powerpoint file to paste the image. (PowerPoint
% is Windows only). [If omitted, doesn't save the image.]
% cbarFlag: if 1, will display image in a separate figure and add
% a subplot with the colorbar leged at the bottom. [default 0]
% montageSize: specify the size of the image montage in [# rows # cols].
% [Defaults to being as close to square as possible, leaning
% towards having more rows]
%
% Returns a montage image of the mesh from all the specified settings.
%
%
% ras, 10/2005.
% ras, 05/2006: now uses mesh settings files instead of settings file.
% ras, 08/2006: mrVista2 version.
if notDefined('msh'), msh = viewGet(getSelectedGray,'mesh'); end
if notDefined('cbarFlag'), cbarFlag = 0; end
if notDefined('settings') | isequal(settings, 'dialog')
% put up a dialog
settingsFile = fullfile(fileparts(msh.path), 'MeshSettings.mat');
[settings savePath cbarFlag msz] = meshMultiAngleGUI(settingsFile);
if isempty(settings) % user aborted, exit quietly
return
end
end
if notDefined('msz')
ncols = ceil(sqrt(length(settings)));
nrows = ceil(length(settings)/ncols);
msz = [nrows ncols];
end
if ischar(settings), settings = {settings}; end % use cell parsing code below
% allow settings to be cell of names of settings
if iscell(settings)
selectedNames = settings; % will load over the 'settings' variable below
settingsFile = fullfile(fileparts(msh.path), 'MeshSettings.mat')
load(settingsFile, 'settings');
names = {settings.name};
for i = 1:length(selectedNames)
ind(i) = cellfind(lower(names), lower(selectedNames{i}));
end
settings = settings(ind);
end
% allow settings to be index vector into saved settings
if isnumeric(settings)
ind = settings; % will load over the 'settings' variable below...
settingsFile = fullfile(fileparts(msh.path), 'MeshSettings.mat');
load(settingsFile, 'settings');
settings = settings(ind);
end
%get the screenshots
for i = 1:length(settings)
msh = meshApplySettings(msh, settings(i));
images{i} = mrmGet(msh, 'screenshot') ./ 255;
pause(1); %empirically-needed wait, or screenshots get corrupted
end
% make the montage image
img = imageMontage(images, msz(1), msz(2));
% if specified, display img in a figure and add View's cbar
if cbarFlag
hfig = figure('Color', 'w');
image(img); axis image; axis off;
% get the cbar(s) from the current mrViewer
ui = mrViewGet;
isHidden = [ui.overlays.hide];
nColorBars = sum(~isHidden);
overlayList = find(~isHidden);
w = max( .25, 1/(nColorBars+2) ); % cbar width
h = .15; % cbar height
panel = mrVPanel('below', 100, hfig, 'pixels');
for ii = 1:nColorBars
o = overlayList(ii);
pos = [((ii-1) * 1.2*w + .1) .4 w h];
hax = axes('Parent', panel, 'Units', 'norm', 'Position', pos);
cbarDraw(ui.overlays(o).cbar, hax);
m = ui.overlays(o).mapNum;
title(ui.maps(m).name, 'FontSize', 12);
if ~isempty(ui.maps(m).dataUnits)
xlabel(ui.maps(m).dataUnits, 'FontSize', 10);
end
end
% let's go ahead and add an ROI legend
if ui.settings.roiViewMode > 1 & ~isempty(ui.rois)
legendPanel({ui.rois.name}, {ui.rois.color});
end
end
% save / export if a path is specified
if ~notDefined('savePath')
savePath = fullpath(savePath);
[p f ext] = fileparts(savePath);
if isequal(lower(ext),'.ppt')
% export to a powerpoint file
fig = figure; imshow(img);
[ppt, op] = pptOpen(savePath);
pptPaste(op,fig,'meta');
pptClose(op,ppt,savePath);
close(fig);
fprintf('Pasted image in %s.\n', fname);
else
% export to a .png or .tiff image in a directory
if isempty(f), f=sprintf('mrMesh-%s',datestr(clock)); end
if isempty(ext), ext = '.tiff'; end
fname = fullfile(p,[f ext]);
if cbarFlag
% export the figure w/ the cbar included
saveas(hfig, fname, ext(2:end));
% exportfig(hfig, fname, 'Format',ext(2:end), 'Color','cmyk', ...
% 'width',3.5, 'Resolution',450);
else
% write directly to the image
imwrite(img, fname, 'png');
end
fprintf('Saved montage as %s.\n', fname);
end
else % save to pwd
% % export to a pwd-mrMesh-date.png image in current directory
% pwdname=pwd;ll=length(pwdname)
% f=sprintf('%s-mrMesh-%s',pwdname(ll-4:ll),datestr(now,1));ext = '.png';
% fname = [f ext]
% udata.rgb = img;
% imwrite(udata.rgb, fname);
% fprintf('Saved montage as %s.\n', fname);
end
return
% /---------------------------------------------------------------------/ %
% /---------------------------------------------------------------------/ %
function [settings, savePath, cbarFlag, msz] = meshMultiAngleGUI(settingsFile);
% [settings, savePath, cbarFlag, msz] = meshMultiAngleGUI(settingsFile);
% put up a dialog to get the parameters for meshMultiAngle2.
settings = []; savePath = []; cbarFlag = []; msz = [];
if ~exist(settingsFile,'file')
myErrorDlg('Sorry, you need to save some mesh settings first. ');
end
load(settingsFile, 'settings');
% set up dialog
dlg(1).fieldName = 'whichSettings';
dlg(1).style = 'listbox';
dlg(1).string = 'Take a picture at which camera settings?';
dlg(1).list = {settings.name};
dlg(1).value = 1;
dlg(2).fieldName = 'order';
dlg(2).style = 'edit';
dlg(2).string = 'OPTIONAL: Order of settings (e.g. [1 2 3 4] vs. [4 3 2 1])?';
dlg(2).value = '';
dlg(3).fieldName = 'savePath';
dlg(3).style = 'filenamew';
dlg(3).string = 'Path to save image (.tiff, .png, .ppt slide)?';
nSnapshotFiles = length( dir('Images/meshSnapshot_*') );
dlg(3).value = sprintf('Images/Mesh Snapshot %i.png', nSnapshotFiles+1);
dlg(4).fieldName = 'cbarFlag';
dlg(4).style = 'checkbox';
dlg(4).string = 'Add Colorbar / ROI Legend?';
dlg(4).value = 1;
dlg(5).fieldName = 'montageSize';
dlg(5).style = 'edit';
dlg(5).string = 'OPTIONAL: Size of image montage [rows cols]?';
dlg(5).value = '';
% put up dialog and get response
resp = generalDialog(dlg, mfilename);
% parse response
if isempty(resp), settings = []; return; end % user canceled
for j = 1:length(resp.whichSettings)
sel(j) = cellfind(dlg(1).list, resp.whichSettings{j});
end
if ~isempty(resp.order), order = str2num(resp.order);
else, order = 1:length(sel);
end
settings = settings(sel(order));
savePath = resp.savePath;
cbarFlag = resp.cbarFlag;
msz = str2num(resp.montageSize);
return
|
github
|
andregouws/mrMeshPy-master
|
meshDrawROIs2.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshDrawROIs2.m
| 7,206 |
utf_8
|
bf2f73591282aa2e2af042d3e8b98fa6
|
function [colors, msh, roiMask] = meshDrawROIs2(msh, rois, nodes, colors, update, edges);
% 'Draw' ROIs on a mesh as colors over different nodes,
% returning the updated mesh colors. Version for mrVista2.
%
% colors = meshDrawROIs2(msh, rois, <oldColors=mesh curvature>, ...
% <perim=1>, <update=0>);
%
% INPUTS:
% msh: mesh structure on which to display ROIs.
%
% rois: struct array of ROI objects. NOTE: the .coords field of each ROI
% should be relative to the gray nodes (e.g., I|P|R space or
% VOLUME{1}.coords).
%
% If you provide an ROI with the name 'mask', rather than rendering the
% ROI, it will be used as a mask to show only part of the data on the mesh.
%
% nodes: gray nodes matrix (as in VOLUME{1}.nodes). These can be obtained
% from mrGray .gray graphs (and readGrayGraph) or using mrgGrowGray.
% Apparently the latter fixes an old bug in mapping nodes.
%
% colors: existing mesh colors over which to superimpose the ROIs. If
% omitted, gets from mesh.
%
%
% update: flag to update the mesh colors with the new colors. Default is
% 0, don't update, just return colors.
%
% OUTPUTS:
% colors: 4 x nVertices set of colors for the mesh, w/ ROI colors added.
%
% msh: updated mesh structure, including any vertexGrayMaps and
% connection matrices needed for the computation.
%
% roiMask: logical mask of size 1 x nVertices indicating where ROIs are.
%
% ras, 07/06.
if isempty(rois), return; end
if ~exist('colors','var') | isempty(colors), colors = meshGet(msh, 'colors'); end
if ~exist('update','var') | isempty(update), update = 0; end
% get the ROI mapping mode: may want to make this
% part of mrmPreferences, but maybe this is enough:
prefs = mrmPreferences;
if isequal(prefs.layerMapMode, 'layer1')
roiMapMode = 'layer1';
else
roiMapMode = 'any';
end
%%%%%params
nNodes = size(nodes, 2);
nVertices = size(msh.initVertices, 2);
v2g = msh.vertexGrayMap;
if isempty(v2g)
myErrorDlg('Need Vertex/Gray Map.');
elseif isequal(unique(v2g(:)), 0)
myErrorDlg('Mesh doesn''t map to any data.');
elseif isequal(roiMapMode, 'any') & size(v2g, 1)==1
% we only have the mapping to layer 1 -- we need the other layers
try, vs = msh.mmPerVox; end % voxel size
if length(vs) < 3, vs = [1 1 1]; end % back-compatibility
msh.vertexGrayMap = mrmMapVerticesToGray(msh.initVertices, nodes, vs, edges);
end
% We need the connection matrix to compute clustering and smoothing, below.
conMat = meshGet(msh,'connectionmatrix');
if isempty(conMat)
msh = meshSet(msh,'connectionmatrix',1);
conMat = meshGet(msh,'connectionmatrix');
end
% initialize ROI mask if it's requested as an output:
if nargout>=3
roiMask = logical(zeros(1, nVertices));
end
%%%%%%Main part:
% Substitute the ROI color for appropriate nearest neighbor vertices
for ii = 1:length(rois)
%% find indices of those mesh vertices belonging to this ROI:
roiVertInds = findROIVertices(rois(ii), nodes, v2g, roiMapMode);
%% adjust the set of ROI vertices to show perimeter / full ROI
roiVertInds = adjustPerimeter(roiVertInds, msh, prefs, rois(ii).fillMode);
% update the colors to reflect the ROIs
if(strcmp(rois(ii).name,'mask'))
% Don't show the ROI- just use it to mask the data.
oldColors = mrmGet(msh, 'colors');
tmp = logical(ones(size(dataMask)));
tmp(roiVertInds) = 0;
colors(1:3,tmp) = oldColors(1:3,tmp);
clear tmp;
else
if (ischar(rois(ii).color))
[stdColorValues, stdColorLabels] = meshStandardColors;
jj = findstr(stdColorLabels, rois(ii).color);
colVal = stdColorValues(:,jj);
else
% Check to see if we have a 3x1 vector.
colVal = rois(ii).color(:);
if (length(colVal)~=3)
error('Bad ROI color');
end
end
colors(roiVertInds,1:3) = repmat(colVal'*255, [length(roiVertInds) 1]);
% build ROI mask if requested
if nargout>=3
roiMask(roiVertInds) = true;
end
end
end
% round and clip
colors(colors>255) = 255;
colors(colors<0) = 0;
colors = round(colors);
return
% /--------------------------------------------------------------------/ %
% /--------------------------------------------------------------------/ %
function roiVertInds = findROIVertices(roi, nodes, v2g, roiMapMode);
% Returns a list of indices to each vertex belonging to the current ROI.
% find the nodes in the segmentation mapping to this ROI
[x nodeInds] = ismember(round(roi.coords'), nodes([2 1 3],:)', 'rows');
nodeInds = nodeInds(nodeInds>0);
switch lower(roiMapMode)
case 'layer1'
% The following will give us *a* vertex index for each gray node.
% However, the same gray node may map to multiple vertices, and we
% want them all. (Otherwise, the color overlay will have holes.)
% So, we loop until we've got them all.
[nodesToMap roiVertInds] = ismember(nodeInds, v2g(1,:));
roiVertInds = roiVertInds(roiVertInds>0);
while(any(nodesToMap))
v2g(1,roiVertInds) = 0;
[nodesToMap I] = ismember(nodeInds, v2g(1,:));
roiVertInds = [roiVertInds; I(I>0)];
end
case 'any'
% if any of the nodes mapping to a given vertex are in the
% ROI, include that vertex for drawing the ROI
[I vertInds] = ismember(v2g, nodeInds);
roiVertInds = find(sum(I)>0); % find columns w/ at least 1 member
case 'data'
% take ROI value from the same nodes as the data mapping,
% rounding up (e.g., for 'mean' data mapping, will behave
% like 'any'
otherwise
error('Invalid ROI Draw Mode preference.')
end
return
% /--------------------------------------------------------------------/ %
% /--------------------------------------------------------------------/ %
function roiVertInds = adjustPerimeter(roiVertInds, msh, prefs, fillMode);
% Sometimes we want to dilate the ROIs a bit. The following does this
% by finding all the neighboring vertices for all the ROI vertices (now
% stored in roiVertInds). The sparse connection matrix comes in handy
% once again, making this a very fast operation.
% We need the connection matrix
conMat = meshGet(msh,'connectionmatrix');
if isempty(conMat)
msh = meshSet(msh,'connectionmatrix',1);
conMat = meshGet(msh,'connectionmatrix');
end
%% draw perimeter or fill in the ROI?
if isequal(fillMode, 'perimeter')
% Draw a perimeter only
origROI = roiVertInds;
perimThickness = max(0, prefs.roiDilateIterations);
if perimThickness > 0
for t = 1:perimThickness
neighbors = conMat(:,roiVertInds);
[roiVertInds cols] = find([neighbors]);
roiVertInds = unique(roiVertInds);
end
% Subtract the original from the dilated version.
roiVertInds = setdiff(roiVertInds, origROI);
else % any way to make the perimeter thinner?
neighbors = conMat(:,roiVertInds);
[roiVertInds cols] = find([neighbors]);
roiVertInds = setdiff(unique(roiVertInds), origROI);
end
else
% We can dilate the area if we are not also rendering the perimeter...
for t = 1:prefs.roiDilateIterations
neighbors = conMat(:,roiVertInds);
[roiVertInds cols] = find([neighbors]);
roiVertInds = unique(roiVertInds);
end
end
return
|
github
|
andregouws/mrMeshPy-master
|
meshBuild.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshBuild.m
| 6,910 |
utf_8
|
98300007e74e9e1d8dcfc43a7ea8dc09
|
function [vw,newMeshNum] = meshBuild(vw,hemisphere)
% Build a 3D mesh for visualization and analysis
%
% [vw,newMeshNum] = meshBuild(vw,[hemisphere]);
%
% Using mrVista data, build a mesh, save it in a file in the anatomy
% directory, and add the mesh to the 3D Control Window pull down
% options.
%
% vw: A VISTASOFT view structure
% hemisphere: left, right or both. Default: left
%
% A mrMesh window is opened as well, showing the computed mesh.
%
% Example:
% [VOLUME{1},newMeshNum] = meshBuild(VOLUME{1},'left');
% VOLUME{1} = viewSet(VOLUME{1},'currentmeshn',newMeshNum);
%
% See also: meshBuildFromClass, meshBuildFromNiftiClass, meshSmooth,
% meshColor
%
% 11/05 ras: also saves mesh path.
%
% (c) Stanford VISTA Team 2008
% Programming TODO. Check this!
% We have (or had?) trouble for building 'both' meshes. We need a new
% procedure.
disp 'meshBuild called'
% Be sure anatomy is loaded (we need it for the mmPerVox field)
if isempty(vw.anat), vw = loadAnat(vw); end
if ieNotDefined('hemisphere'), hemisphere = 'left'; end
newMeshNum = viewGet(vw,'nmesh') + 1;
% Parameters we establish in this routine
[meshName,numGrayLayers,hemiNum] = readParams(newMeshNum,hemisphere);
if isempty(meshName), newMeshNum = newMeshNum - 1; return; end % User pressed cancel.
% mmPerVox = viewGet(vw,'mmPerVoxel');
wbar = mrvWaitbar(0.1, ...
sprintf('meshBuild: Combining white and gray matter...'));
% Load left, right, or both hemispheres.
if (hemiNum==1)
[voxels,vw] = meshGetWhite(vw, 'left', numGrayLayers);
elseif (hemiNum==2)
[voxels,vw] = meshGetWhite(vw, 'right', numGrayLayers);
elseif (hemiNum == 0)
[voxels,vw] = meshGetWhite(vw, 'left', numGrayLayers);
[voxels,vw] = meshGetWhite(vw, 'right', numGrayLayers,voxels);
end
% host = 'localhost';
% windowID = -1;
% We build a smoothed (mesh) and an unsmoothed mesh (tenseMesh) with these calls
mrvWaitbar(0.35,wbar,sprintf('Building mesh'));
[newMesh, tenseMesh] = mrmBuild(voxels,viewGet(vw,'mmPerVox'),1);
% Must have a name
newMesh = meshSet(newMesh,'name',meshName);
tenseMesh = meshSet(tenseMesh,'name',sprintf('%s-tense',meshName));
% mrvWaitbar(0.65,wbar,sprintf('meshBuild: Unsmoothed mesh vertex to gray mapping'));
initVertices = meshGet(tenseMesh,'vertices');
newMesh = meshSet(newMesh,'initialvertices',initVertices);
vertexGrayMap = mrmMapVerticesToGray(...
initVertices, ...
viewGet(vw,'nodes'), ...
viewGet(vw,'mmPerVox'),...
viewGet(vw,'edges'));
newMesh = meshSet(newMesh,'vertexGrayMap',vertexGrayMap);
newMesh = meshSet(newMesh,'name',meshName);
newMesh = meshSet(newMesh,'nGrayLayers',numGrayLayers);
mrvWaitbar(0.9,wbar,sprintf('meshBuild: Saving mesh file %s',meshGet(newMesh,'name')));
% Save mesh file
[newMesh newMesh.path] = mrmWriteMeshFile(newMesh);
mrvWaitbar(1,wbar,sprintf('meshBuild: Done'));
pause(0.5);
close(wbar);
% Now refresh the UI
vw = viewSet(vw,'add and select mesh',newMesh);
return;
%---------------------------------------
function classFile = verifyClassFile(vw,hemisphere)
classFile = viewGet(vw,'classFileName',hemisphere);
str = sprintf('Class %s',classFile);
r=questdlg(str);
if ~strcmp(r,'Yes')
switch hemisphere
case 'left'
vw = viewSet(vw,'leftClassFileName',[]);
case 'right'
vw = viewSet(vw,'rightClassFileName',[]);
end
classFile = viewGet(vw,'classFileName',hemisphere);
end
return;
%---------------------------------------
function voxels = classExtractWhite(voxels,data,voi,whiteValue)
%
% ras 05/07: the indexing of data seems off to me -- is this correct?
voxels(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) = ...
voxels(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) ...
| (data(voi(1):voi(2), voi(3):voi(4), voi(5):voi(6)) == whiteValue);
return;
%----------------------------------------
function [meshName,numGrayLayers,hemiNum,alpha,restrictVOI,relaxIterations] = ...
readParams(newMeshNum,hemisphere)
%
% readParams
%
% Internal routine to read the parameters for meshBuild
%
meshName = sprintf('%sSmooth',hemisphere);
numGrayLayers = 0;
switch hemisphere
case 'left'
hemiNum = 1;
case 'right'
hemiNum = 2;
case 'both'
hemiNum = 0;
end
% transparency level (transparency is off by default, but if it gets turned
% on, this alpha parameter will have an effect).
alpha = 200;
restrictVOI = 1;
relaxIterations = 0.2;
prompt = {'Mesh Name:',...
'Number of Gray Layers (0-4):',...
'Hemisphere (0=both, 1=left, 2=right):',...
% 'Default alpha (0-255):',...
% 'Inflation (0=none, 1=lots):',...
% 'Restrict to class VOI (0|1):'};
};
defAns = {meshName,...
num2str(numGrayLayers),...
num2str(hemiNum),...
% num2str(alpha),...
% num2str(relaxIterations),...
% num2str(restrictVOI)};
};
resp = inputdlg(prompt, 'meshBuild Parameters', 1, defAns);
if(~isempty(resp))
meshName = resp{1};
numGrayLayers = str2num(resp{2});
hemiNum = str2num(resp{3});
% alpha = str2num(resp{4});
% relaxIterations = round(str2num(resp{5})*160); % Arbitrary choice, scales iters [0,160]
% restrictVOI = str2num(resp{6});
else
meshName = [];
numGrayLayers = [];
hemiNum = [];
% alpha = [];
% relaxIterations = []; % Arbitrary choice, scales iters [0,160]
% restrictVOI = [];
end
return;
%---------------------------------
function [voxels,vw] = meshGetWhite(vw, hemiName, numGrayLayers, voxels)
%
%
%
if ieNotDefined('vw'), error('You must send in a volume vw'); end
if ieNotDefined('hemiName'), error('You must define right,left or both'); end
if ieNotDefined('numGrayLayers'), numGrayLayers = 0; end
classFile = verifyClassFile(vw,hemiName);
if isempty(classFile),
close(wbar); newMeshNum = -1;
voxels = [];
return;
end
classFileParam = [hemiName,'ClassFile'];
vw = viewSet(vw,classFileParam,classFile);
classData = viewGet(vw,'classdata',hemiName);
if ieNotDefined('voxels'),
voxelsOld = uint8(zeros(classData.header.xsize, ...
classData.header.ysize, ...
classData.header.zsize));
else
voxelsOld = voxels;
end
voxels = zeros(classData.header.xsize, ...
classData.header.ysize, ...
classData.header.zsize);
% Restrict the white matter volume to a size equal to the ROI in which it
% was selected
voxels = classExtractWhite(voxels,...
classData.data,classData.header.voi,classData.type.white);
% msh = meshColor(meshSmooth(meshBuildFromClass(voxels,[1 1 1])));
% meshVisualize(msh);
% Add the gray matter
if(numGrayLayers>0)
[nodes,edges,classData] = mrgGrowGray(classData,numGrayLayers);
voxels = ...
uint8( (classData.data == classData.type.white) | ...
(classData.data == classData.type.gray));
end
voxels = uint8(voxels | voxelsOld);
return;
|
github
|
andregouws/mrMeshPy-master
|
meshGrowROI.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshGrowROI.m
| 5,510 |
utf_8
|
0ac103a1d2853114720625acaa6a451e
|
function view = meshGrowROI(view, name, startCoord, mask);
% Grow an ROI along the cortical surface, starting at the mesh cursor
% position and extending along a contiguous patch defined by the data in
% mask.
%
% view = meshGrowROI([view], [name], [startCoord=cursor position], [mask=data overlay mask]);
%
% INPUTS:
% view: mrVista gray view. [Defaults to selected gray.]
%
% name: name of the new ROI. [Default is to call it 'Mesh ROI' with the
% start coord appended.]
%
% startCoord: coordinate of starting gray matter node. [Defaults to
% position of cursor in currently-selected mesh.]
%
% mask: binary data mask, size 1 x nNodes, indicating whether a given
% node is acceptable to be included in the ROI. nNodes is the size of
% view.coords and view.nodes. If the start node is not 1, will warn the
% user and exit without making an ROI. Will grow the ROI along the
% view.edges field until there are no neighboring nodes for which mask is
% 1. [default: makes this mask based on the current mesh overlay and view
% settings: if there is data shown on the overlay, the mask is 1; if not,
% it's 0.]
%
% OUTPUTS:
% view with a new ROI added (if one could be created).
%
% NOTE: This function uses iteration, and so if the data mask is mostly
% ones (the ROI has to grow a lot), the function can be memory
% intensive / may fail to finish due to the MATLAB iteration limit. Also,
% growing along the cortical surface is different from growing in the
% volume space. It is sensitive to the alignment/segmentation, so those
% should be in good order before this can be trusted.
%
% Finally, if you move the mesh (Ctrl + moving the mouse), this can mess up
% the correspondence between the mesh cursor position and the volume nodes.
% So, you can''t do that and have this keep working. (If you do this by
% accident, but you've saved some view settings, you can restore those
% settings and things should work again.)
%
% ras, 10/17/2008.
if notDefined('view'), view = getSelectedGray; end
%% data / mesh checks
if ~ismember(view.viewType, {'Gray' 'Volume'})
error('Only works on Gray / Volume views.');
end
if ~isfield(view, 'mesh') | isempty(view.mesh)
error('Need a mesh loaded.')
end
m = view.meshNum3d;
if m==0
error('Need a selected mesh.')
end
if notDefined('startCoord'),
startCoord = meshCursor2Volume(view, view.mesh{m});
end
if notDefined('name'),
name = ['Mesh ROI ' num2str(startCoord)];
end
if notDefined('mask')
% [view mask] = meshColorOverlay(view, 0);
mask = logical( ones(1, size(view.coords, 2)) );
if length(view.co) >= view.curScan & ~isempty(view.co{view.curScan})
co = view.co{view.curScan};
mask = mask & (co > getCothresh(view));
end
if length(view.ph) >= view.curScan & ~isempty(view.ph{view.curScan})
ph = view.ph{view.curScan};
phWin = getPhWindow(view);
mask = mask & (ph >= phWin(1)) & (ph <= phWin(2));
end
if length(view.map) >= view.curScan & ~isempty(view.map{view.curScan})
map = view.map{view.curScan};
mapWin = getMapWindow(view);
mask = mask & (map >= mapWin(1)) & (map <= mapWin(2));
end
end
% get gray matter node corresponding to the start coord
startNode = roiIndices(view, startCoord(:));
% does the start node pass the criterion? If not, we shouldn't make an ROI
% with it:
if mask(startNode)==0
myWarnDlg('The selected start point doesn''t pass the threshold.');
return
end
%% initialize an empty ROI
ROI = roiCreate1;
ROI.name = name;
ROI.comments = sprintf(['Created by %s grown from seed %s'], mfilename, ...
num2str(startCoord));
%% main part: "grow" coords in ROI (recursive)
h = msgbox('Growing Mesh ROI', mfilename);
nodes = growMeshROICoords(startNode, view, mask);
close(h);
ROI.coords = view.coords(:,nodes);
%% add ROI to view
view = addROI(view, ROI);
return
% /-----------------------------------------------------------------/ %
% /-----------------------------------------------------------------/ %
function nodes = growMeshROICoords(nodes, view, mask);
% recursive function designed to grow mesh ROI coordinates.
% The logic here is: the nodes passed in are all voxels that will
% definitely be included in the mesh ROI. The code looks at neighboring
% voxels (according to the gray matter nodes/edges), evalautes them for
% inclusion (mask==1), and selects those which pass the test.
% If there are any of these neighbors, the function is called again, now
% looking at the neighbors of these neighbors.
%% find neighbors of the input nodes
neighbors = [];
for n = nodes
nEdges = view.nodes(4,n);
startEdge = view.nodes(5,n);
neighbors = [neighbors view.edges(startEdge:startEdge+nEdges-1)];
end
%% which neighbors are contained in the mask?
neighbors = neighbors(mask(neighbors)==1);
% prevent the recursion from bouncing back and forth:
% some of these neighbors may already be included in nodes. Remove them;
% they're obviously okay.
% (If I didn't do this, then if A points to B, and B points to A, and both
% satisfy the criteria, the function would keep getting called, first with
% A as the neigbor, then B, then A, etc...)
neighbors = setdiff(neighbors, nodes);
%% do any neighbors pass the test?
% if no, we're done. If yes, we recurse: call this function on the existing
% nodes plus the neighbors:
if ~isempty(neighbors)
nodes = growMeshROICoords([nodes neighbors], view, mask);
end
return
|
github
|
andregouws/mrMeshPy-master
|
meshMontageMovie.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshMontageMovie.m
| 6,503 |
utf_8
|
5bd24d78c37a9d01aee79e87c3a06f69
|
function M = meshMontageMovie(V, whichMeshes, movieFileName, timeSteps, plotFlag, stimImages)
%
% M = meshMontageMovie([gray view], [whichMeshes], [movieFileName], [timeSteps=12], [plotFlag=1], [stimImages])
%
%Author: Wandell
%Purpose:
% Create a movie consisting of a montage of mesh images, each showing
% the fundamental component of the time series based on the coherence
% and phase measurement ('corAnal').
%
% This is not the real time series, but just a signal-approximation.
% At some point, we should read in the time series and show it frame by
% frame. I am not quite sure how to do this. We don't normally get a
% time-slice over space. But I am guessing we could do it.
%
% roiFlag: flag indicating whether to illustrate a disc ROI during the
% movie. If this flag is set to zero, no ROI will be shown. If it is
% greater than 0, the value is taken to be the radius of the ROI disc
% around the mesh cursor (those 3-axes things you get when
% double-clicking on the mesh). If it is set to -1, all ROIs currently
% defined in the view will be shown.
%
% Example: To make a movie with 10 steps, write out an AVI file called scratch,
% and to return a Matlab movie structure, M, within the constraints of the
% cothresh and ROI parameters, use:
%
% M = meshMovie([], [], 'scratch', 10, 0);
%
% To get the last 3 arguments from a dialog, use:
% M = meshMovie('dialog');
% or
% M = meshMovie(gray, [], 'dialog');
%
% ras 04/2008: modularized this more. Added view as an inputtable argument,
% instead of that VOUME{selectedVOLUME} stuff, added the roiFlag so you
% don't always need an ROI, and had the code only throw up a dialog if you
% didn't already give it the parameters it needs.
% ras 07/2008: added plot flag, updated calling of parameters dialog.
if notDefined('V'), V = getSelectedGray; end
if notDefined('plotFlag'), plotFlag = 1; end
if notDefined('timeSteps'), timeSteps = 12; end
if notDefined('movieFileName'), movieFileName = ''; end
if notDefined('stimImages'), stimImages = []; end
% check that meshes are loaded
if ~checkfields(V, 'mesh')
error('View must have a mesh loaded.')
end
if isequal(timeSteps, 'dialog') | isequal(movieFileName, 'dialog') | ...
isequal(V, 'dialog') | notDefined('whichMeshes')
whichMeshes = 1;
[whichMeshes, timeSteps, movieFileName, plotFlag] = ...
readParameters(V, whichMeshes, timeSteps, movieFileName, plotFlag);
end
% Make sure the cor anal data are loaded
if isempty(viewGet(V, 'co')), V=loadCorAnal(V); end
msh = viewGet(V, 'currentmesh');
%% params
roiFlag = -1;
if roiFlag==0
% hide ROIs
V.ui.showROIs = 0;
end
% Set up the co or amp values for the movie. We replace the colors within
% the dataMask with the new colors generated here.
curScan = viewGet(V, 'currentscan');
realCO = viewGet(V, 'scanco', curScan);
ph = viewGet(V, 'scanph', curScan);
t = ([0:(timeSteps-1)]/timeSteps) * 2 * pi;
nFrame = length(t);
clear M;
mrmSet(msh, 'hidecursor');
verbose = prefsVerboseCheck;
if verbose
str = sprintf('Creating %.0f frame movie', nFrame);
wbar = mrvWaitbar(0, str);
end
% change the view to display the coherence field, since we're actually
% displaying phase-projected coherence for each time point:
% I specificially make this change without calling setDisplayMode, because
% that accessor function will try to do concurrent GUI things like setting
% a colorbar and loading/clearing data fields. We don't want to do this,
% because we're treating the view V as a local variable; changes we make to
% V are not intended to propagate back to the GUI. So, if the user was e.g.
% looking at a coherence map before this, we don't want him/her to suddenly
% see the phase-projected data from the movie.
V.ui.displayMode = 'co';
%% loop across frames
for ii=1:nFrame
if verbose % udpate mrvWaitbar
str = sprintf('Creating frame %.0f of %.0f', ii, nFrame);
fname{ii} = sprintf('Movie%0.4d.tiff', ii);
mrvWaitbar(ii/nFrame, wbar, str);
end
% compute the projected coherence relative to this time point
data = realCO.*(1 + sin(t(ii) - ph))/2;
V = viewSet(V, 'scancoherence', data, curScan);
%% loop across meshes
for n = 1:length(whichMeshes)
% select the current mesh
V.meshNum3d = whichMeshes(n);
% update the mesh view with the colors for this time step
meshColorOverlay(V, 1);
meshImg{n} = mrmGet(V.mesh{whichMeshes(n)}, 'screenshot') / 255;
end
% add a stimulus image if it's provided
if ~isempty(stimImages)
meshImg{length(whichMeshes)+1} = stimImages(:,:,:,ii);
end
% grab the montage image (across meshes) for this frame
M(:,:,:,ii) = imageMontage(meshImg, 1, 3);
end
if verbose, mrvWaitbar(1, wbar); close(wbar); end
%% show the movie in a separate figure
if plotFlag==1
mov = mplay(M, 4);
mov.loop
mov.play
end
if ~isempty(movieFileName)
% allow the movie path to specify directories that don't yet exist
% (like 'Movies/')
ensureDirExists( fileparts(fullpath(movieFileName)) );
try
if(isunix)
aviSave(M, movieFileName, 'FPS', 3, 'compression', 'none');
else
aviSave(M, movieFileName, 'FPS', 3, 'QUALITY', 100, ...
'compression', 'Indeo5');
end
fprintf('Saved movie as avi file: %s\n', [pwd, filesep, movieFileName]);
catch
disp('Couldn''t save AVI file: last error: ')
disp(lasterr);
end
end
return;
%------------------------------------
function [whichMeshes, timeSteps, movieFileName, plotFlag] = ...
readParameters(V, whichMeshes, timeSteps, movieFileName, plotFlag);
%
% read parameters for meshMontageMovie
%
for n = 1:length(V.mesh)
meshList{n} = V.mesh{n}.name;
end
dlg(1).fieldName = 'whichMeshes';
dlg(1).style = 'listbox';
dlg(1).list = meshList;
dlg(1).string = 'Use which meshes for movie?';
dlg(1).value = whichMeshes;
dlg(2).fieldName = 'timeSteps';
dlg(2).style = 'number';
dlg(2).string = 'Number of time frames for movie?';
dlg(2).value = num2str(timeSteps);
dlg(3).fieldName = 'movieFileName';
dlg(3).style = 'filenamew';
dlg(3).string = 'Name of AVI movie file? (Empty for no movie file)';
dlg(3).value = movieFileName;
dlg(4).fieldName = 'plotFlag';
dlg(4).style = 'checkbox';
dlg(4).string = 'Show movie in a MATLAB figure?';
dlg(4).value = plotFlag;
[resp ok] = generalDialog(dlg, 'Mesh movie options');
if ~ok
error(sprintf('%s aborted.', mfilename));
end
timeSteps = resp.timeSteps;
movieFileName = resp.movieFileName;
plotFlag = resp.plotFlag;
[meshNames whichMeshes] = intersectCols(meshList, resp.whichMeshes);
return;
|
github
|
andregouws/mrMeshPy-master
|
meshParameterMaps.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshParameterMaps.m
| 10,149 |
utf_8
|
a013f41388613da4c5349a825895ff4c
|
function [images mapVals] = meshParameterMaps(V, dialogFlag, varargin);
% Produce images of parameter maps on a mesh.
%
% NOTE: this will modify the 'map' field of the view.
%
% USAGE:
% [images mapVals] = meshAmplitudeMaps(grayView, [dialogFlag], [options]);
%
% INPUTS:
% grayView: mrVista gray view, with a mesh open. Will show maps on the
% currently-selected mesh, if there are more than one.
%
% useDialog: 1 to put up a dialog to set the parameters, 0 otherwise.
%
% options: options can be specified as 'optionName', [value], ...
% pairs. Options are below:
%
% mapFiles: name or path to parameter map file. [Default: use file
% loaded for the map's current parameter map.]
%
% plotFlag: flag to show the set of images returned in a montage. If 0,
% will not plot; if 1 will plot. You can also specify a size for the
% montage, as in plotFlag = [nRows, nCols]; otherwise the rows and
% columns will be approximately square.
%
% nRows, nCols: alternate method for specifying the montage size
% (rather than using the 'plotFlag' option described above).
%
% cropX, cropY: specify zoom ranges in the X and Y dimensions for each
% mesh image. If omitted, will show the entire mesh.
%
% whichScans: select the scans in the current data type for which to show
% the map. [Default: view's current scan].
%
% preserveCoords: flag to return mapVals with exactly the same number
% of columns as the ROI coordinates. If this is set to 1, and certain
% ROI coordinates don't have data, mapVals will have NaN for that
% column. If 0 [default], these columns are automatically removed
% from the matrix.
%
% OUTPUTS:
% images: nRows x nCols cell array containing mesh images for each
% condition in the GLM.
%
% mapVals: conditions x voxels matrix containing the amplitude values
% used in the map images for the selected ROI.
%
% ras, 03/2008.
if notDefined('V'), V = getSelectedGray; end
if notDefined('dialogFlag'), dialogFlag = (length(varargin)<=1); end
%% checks
% check that a mesh is loaded
if isempty( viewGet(V, 'curMesh') )
error('Need to load a mesh.')
end
images = {};
mapVals = [];
%% params
% default params
preserveCoords = 0;
mapFiles = { fullfile(dataDir(V), [V.mapName '.mat']) };
mapOrder = [];
cmap = 'coolhot';
clim = [-2 2];
cropX = [];
cropY = [];
cmap = mrvColorMaps('coolhot', 128);
clim = [-2 2];
plotFlag = 1;
whichScans = V.curScan;
whichMeshes = 1:length(V.mesh);
maskRoi = '';
nRows = []; nCols = [];
% grab the current map mode (which contains the color map and
% color limits) -- we'll assume these settings are the ones you want to
% apply to each map (loadParameterMap below may over-ride these in the view,
% so we restore them later):
mapMode = V.ui.mapMode;
mapWin = getMapWindow(V);
% get params from dialog if needed
if dialogFlag==1
[params ok] = meshParameterMapGUI(V);
if ~ok, disp('User Aborted.'); return; end
mapFiles = params.mapFiles;
mapOrder = params.mapOrder;
whichMeshes = params.whichMeshes;
plotFlag = params.plotFlag;
cropX = params.cropX;
cropY = params.cropY;
cmap = params.cmap;
clim = params.clim;
preserveCoords = params.preserveCoords;
whichScans = params.whichScans;
if length(params.montageSize) >= 2
nRows = params.montageSize(1);
nCols = params.montageSize(2);
else
nRows = [];
nCols = [];
end
maskRoi = params.maskRoi;
if isequal(maskRoi, 'none')
maskRoi = '';
end
if checkfields(V, 'ui', 'mapMode')
V.ui.mapMode = mapMode;
end
end
% set the map mode settings to reflect the request color map and limits
if ischar(cmap)
mapMode.cmap = [gray(128); mrvColorMaps(cmap, 128)];
else
mapMode.cmap = [gray(128); cmap];
end
mapMode.clipMode = clim;
% parse options (these will override the dialog values)
for ii = 1:2:length(varargin)
val = varargin{ii+1};
eval( sprintf('%s = val;', varargin{ii}) );
end
if ischar(mapFiles), mapFiles = {mapFiles}; end
if ischar(cmap)
mapMode.cmap = [gray(128); mrvColorMaps(cmap, 128)];
else
mapMode.cmap = [gray(128); cmap];
end
mapMode.clipMode = clim;
%% set the ROI mask, if requested
if length(V.ROIs) >= 1 & ~isempty(maskRoi);
% we modify the view's ROIs here, but don't return the modified
% view:
oldROIs = V.ROIs;
oldSelROI = V.selectedROI;
roiNum = findROI(V, params.maskRoi);
V.ROIs = V.ROIs(roiNum);
V.ROIs.name = 'mask';
V.selectedROI = 1;
end
nScans = length(whichScans);
%% if requesting the map values, mark which data nodes to take
if nargout > 1
% I is the indices from which to extract values
if isempty(maskRoi)
% take all nodes
I = 1:size(V.coords, 2);
else
I = roiIndices(V, V.ROIs(1).coords, preserveCoords);
end
end
% compute the default # of rows/columns if it's left empty
if isempty(nRows) | isempty(nCols)
nRows = ceil( sqrt(length(mapFiles)) );
nCols = ceil( length(mapFiles) / nRows );
end
%% main loop: get pictures of each set of maps
% first, re-order the map files to the user's specification
if isempty(mapOrder),
mapOrder = 1:length(mapFiles);
end
mapFiles = mapFiles(mapOrder);
% now, get the values
for m = 1:length(mapFiles)
% load the parameter map
V = loadParameterMap(V, mapFiles{m});
% get images for each scan
for n = 1:length(whichScans)
% set the scan
V.curScan = whichScans(n);
% set the color map and color limits
% (the saved param map may have over-set this):
V.ui.mapMode = mapMode;
for h = 1:length(whichMeshes)
% update the mesh
V.meshNum3d = whichMeshes(h);
meshColorOverlay(V);
% grab the image
img{h} = mrmGet(V.mesh{whichMeshes(h)}, 'screenshot') ./ 255;
% crop the image if requested
if ~isempty(cropX) & ~isempty(cropY)
img{h} = img{h}(cropY,cropX,:);
end
end
% add image to list of images
% (make montage if taking a shot of multiple meshes)
if length(whichMeshes)==1
img = img{1};
else
img = imageMontage(img, 1, length(whichMeshes));
end
images{(m-1)*nScans + n} = img;
clear img
%% grab map values for the ROI if requested
if nargout > 1
% extract the values for the selected ROI
mapVals((m-1)*nScans + n,:) = V.map{V.curScan}(I);
end
end
end
%% restore the ROIs if we were masking
if exist('oldROIs', 'var')
V.ROIs = oldROIs;
V.selectedROI = oldSelROI;
updateGlobal(V);
if checkfields(V, 'ui', 'windowHandle')
refreshScreen(V);
end
end
%% display the images if selected
if ~isequal(plotFlag, 0)
% we'll manually specify subplot sizes -- large:
width = 1 / nCols;
height = 1 / nRows;
% open the figure
figure('Units', 'norm', 'Position', [0.2 0 .7 .35], 'Name', 'Mesh Images');
% plot each mesh image in a subplot:
% allow for some images to be omitted if the user specified
% a montage size that is smaller than the # of images
% (e.g., an extra 'scrambled' condition)
for n = 1:min(length(images), nRows*nCols);
row = ceil(n / nCols);
col = mod(n-1, nCols) + 1;
subplot('Position', [(col-1)*width, 1 - row*height, width, height]);
imagesc(images{n}); axis image; axis off;
end
% add a colorbar
if check4File(mapFiles{1})
tmp = load(mapFiles{1});
if isfield(tmp, 'mapUnits') & ~isempty(tmp.mapUnits)
cbarTitle = sprintf('%s (%s)', tmp.mapName, tmp.mapUnits)
else
cbarTitle = tmp.mapName;
end
else
[par cbarTitle] = fileparts(mapFiles{1});
end
cmap = viewGet(V, 'OverlayColormap');
clim = viewGet(V, 'MapClim');
cbar = cbarCreate(cmap, cbarTitle, 'Clim', clim);
hPanel = mrvPanel('below', .2);
hAxes = axes('Parent', hPanel, 'Units', 'norm', 'Position', [.3 .5 .4 .2]);
cbarDraw(cbar, hAxes);
end
return
% /----------------------------------------------------------------------/ %
% /----------------------------------------------------------------------/ %
function [params ok] = meshParameterMapGUI(V);
% dialog to get parameters for meshAmplitudeMaps.
dlg(1).fieldName = 'mapFiles';
dlg(end).style = 'listbox';
w = what(dataDir(V));
if isempty(w.mat)
warning('No maps found in current data type: %s', getDataTypeName(V));
ok = 0;
params = [];
return
end
dlg(end).list = w.mat;
if ~isempty( cellfind(V.map) ) & ~isempty(V.mapName)
dlg(end).value = V.mapName;
else
dlg(end).value = '';
end
dlg(end).string = 'Parameter map file(s)?';
dlg(end+1).fieldName = 'mapOrder';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Order of maps?';
dlg(end+1).fieldName = 'whichMeshes';
dlg(end).style = 'listbox';
for n = 1:length(V.mesh)
meshList{n} = sprintf('%i: %s', V.mesh{n}.id, V.mesh{n}.name);
end
dlg(end).list = meshList;
dlg(end).value = V.meshNum3d;
dlg(end).string = 'Project data onto which meshes?';
dlg(end+1).fieldName = 'whichScans';
dlg(end).style = 'number';
dlg(end).value = V.curScan;
dlg(end).string = 'Plot data from which scans?';
dlg(end+1).fieldName = 'cropX';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Mesh X-axis image crop (empty for no crop)?';
dlg(end+1).fieldName = 'cropY';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Mesh Y-axis image crop (empty for no crop)?';
dlg(end+1).fieldName = 'montageSize';
dlg(end).style = 'number';
dlg(end).value = [];
dlg(end).string = 'Montage layout ([nrows ncolumns])?';
dlg(end+1).fieldName = 'cmap';
dlg(end).style = 'popup';
dlg(end).list = mrvColorMaps; % list of available cmaps
dlg(end).value = 'coolhot';
dlg(end).string = 'Color map for amplitudes?';
if length(V.ROIs) >= 1
dlg(end+1).fieldName = 'maskRoi';
dlg(end).style = 'popup';
dlg(end).list = [{'none'} {V.ROIs.name}];
dlg(end).value = 'none';
dlg(end).string = 'Mask activations within which ROI?';
end
dlg(end+1).fieldName = 'clim';
dlg(end).style = 'number';
dlg(end).value = [-2 2];
dlg(end).string = 'Color limits for amplitudes?';
dlg(end+1).fieldName = 'preserveCoords';
dlg(end).style = 'checkbox';
dlg(end).value = 0;
dlg(end).string = 'Preserve ROI coordinates in returned values?';
dlg(end+1).fieldName = 'plotFlag';
dlg(end).style = 'checkbox';
dlg(end).value = 1;
dlg(end).string = 'Plot Results?';
[params ok] = generalDialog(dlg, 'Mesh Parameter Maps');
[ignore, params.whichMeshes] = intersect(meshList, params.whichMeshes);
return
|
github
|
andregouws/mrMeshPy-master
|
meshCreate.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshCreate.m
| 2,381 |
utf_8
|
3347f53de70bc2acf5d665b899d4a65c
|
function msh = meshCreate(mshType)
% mrMesh creation routine
%
% msh = meshCreate(mshType);
%
% We only create a vistaMesh type. In the future we may design additional
% mesh structures. See notes below about the properties of the msh fields.
%
% See also: meshSet/Get and mrmSet/Get
%
% Example:
% msh = meshCreate;
% msh = meshCreate('vista mesh');
%
% Stanford VISTA team
if ieNotDefined('mshType'), mshType = 'vistaMesh'; end
mshType = mrvParamFormat(mshType);
switch lower(mshType)
case 'vistamesh'
msh = vistaMeshCreate;
otherwise
error('Unknown mesh type %s\n',mshType);
end
return;
%------------------------------
function msh = vistaMeshCreate
%Default settings for a mrVista mesh
%
% msh = vistaMeshCreate;
%
% * The triangles are triplets of vertices.
% * The vertices are numbered from [0,n-1], consistent with C numbering,
% but not Matlab numbering. This is necessary to work with mrMeshSrv.
%
%
% fields = {'name', 'host', 'id', 'actor', 'mmPerVox', 'lights', 'origin', ...
% 'initialvertices', 'vertices', 'triangles', 'colors', 'normals', 'curvature',...
% 'ngraylayers', 'vertexGrayMap', 'fibers',...
% 'smooth_sinc_method', 'smooth_relaxation', 'smooth_iterations', 'mod_depth'};
%
% (c) Stanford VISTA Team
msh.name = '';
msh.type = 'vistaMesh';
msh.host = 'localhost';
msh.id = -1; % Figure this out as soon as possible.
msh.filename = [];
msh.path = [];
msh.actor = 33; % This is default. But we should be able to change.
msh.mmPerVox = [1 1 1];
msh.lights = {};
msh.origin = [];
msh.initVertices = []; % Initial vertices, without smoothing.
msh.vertices = [];
msh.triangles = [];
% Surface shading typically for pseudo-color or for showing curvature
msh.colors = [];
msh.mod_depth = 0.25;
msh.normals = []; % Normals to the patches. Can be computed using Matlab
msh.curvature = []; % Not sure how we compute this. Uh oh.
% Not sure why these are here. They relate the vertices to gray map.
% Probably essential for VISTASOFT/mrBOLD
msh.grayLayers = [];
msh.vertexGrayMap =[];
% Not sure why these are here too, but probably related to mrDiffusion
msh.fibers = [];
% Mesh smoothing related
msh.smooth_sinc_method = 0;
msh.smooth_relaxation = 0.5;
msh.smooth_iterations = 32;
return;
|
github
|
andregouws/mrMeshPy-master
|
meshCompareScans.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshCompareScans.m
| 9,112 |
utf_8
|
51777b74f032d5d0b3596a22d29f830e
|
function [images pics] = meshCompareScans(V, scans, dts, settings, savePath, leg);
%
% Create mosaic images showing data from different scans / data
% types superimposed on the same mesh and view angles.
%
% [images pics] = meshCompareScans(<view, scans, dts, settings, savePath, leg>);
%
% This code requires that you have saved some view angles using the
% function meshAngles. The code will set the input view (which should
% have an open mesh attached) to each of the specified input scans,
% display the current data (which depends on the display mode: co, amp,
% ph, map) on the mesh, set the mesh to the specified angles, and
% take a snapshot. For each angle provided, the code will produce an
% output image which is a mosaic of the maps across all the scans and data
% types.
%
% INPUT ARGUMENTS:
% view: gray view w/ open mesh attached. <Default: selected gray.>
%
% scans: vector of scan numbers from which to take the data.
% <default: all scans in cur data type>
%
% dts: cell array of data type names / vector of data type numbers.
% if only one provided, and multiple scans, will assume all the
% scans come from the current data type. <default: cur dt>
%
% angles: struct array of angles. See meshAngles. Can also be a numeric
% vector specifying which of the saved angles to show, or a cell of
% names of angles. <default: all saved mesh angles>
%
% savePath: if provided, will either save the *.png files to this
% directory (if dir) or append images to a power point file (if
% using Windows and savePath ends in *.ppt).
%
% leg: flag: if set to 1, will put the image in a figure, and add
% a copy of the color bar for the view. <default: no legend>
%
%
%
% OUTPUT ARGUMENT:
% images: cell of images, one for each input angle specified. Each image
% is a montage of the same view angle across scans
%
% pics: nested cell of images containing the source screenshots for the
% 'images' output. pics{i}{j} contains the screenshot for view angle i,
% scan j.
%
% ras, 02/02/06. I've been writing this code for 50 years, but it's still
% always the same day!
% ras, 11/08/06. Converted to use settings rather than angles.
if notDefined('V'), V = getSelectedGray; end
if notDefined('scans'), scans = 1:numScans(V); end
if notDefined('dts'), dts = V.curDataType; end
if notDefined('savePath'), savePath = 'Images'; end
if notDefined('leg'), leg = 0; end
if notDefined('settings') | notDefined('scans')
params = meshCompareScansParams(V, dts(1), savePath, leg);
settings = params.settings;
scans = params.scans;
savePath = params.savePath;
leg = params.leg;
end
% get the current mesh
msh = viewGet(V, 'currentMesh');
% make sure the dts list is a numeric array
if iscell(dts)
for i = 1:length(dts), tmp(i) = existDataType(dts{i}); end
dts = tmp;
elseif ischar(dts), dts = existDataType(dts);
end
for i = length(dts)+1:length(scans), dts(i) = dts(i-1); end
% allow settings to be cell of names of settings
if iscell(settings)
selectedNames = settings; % will load over the 'settings' variable below
settingsFile = fullfile(fileparts(msh.path), 'MeshSettings.mat');
load(settingsFile, 'settings');
names = {settings.name};
for i = 1:length(selectedNames)
ind(i) = cellfind(names, selectedNames{i});
end
settings = settings(ind);
elseif isnumeric(settings)
ind = settings;
settingsFile = fullfile(fileparts(msh.path), 'MeshSettings.mat');
load(settingsFile, 'settings');
settings = settings(ind);
end
%%%%%initialize cell arrays for each image (corresponding to each
%%%%%angle) for the main loop
for i = 1:length(settings), pics{i} = {}; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main loop: go through each scan, put up the map, grab the image %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:length(scans)
if dts(i)~=V.curDataType, V = selectDataType(V, dts(i)); end
V = viewSet(V, 'curScan', scans(i));
meshColorOverlay(V);
% take a picture of the mesh, with this map, at each angle
for j = 1:length(settings)
msh = meshApplySettings(msh, settings(j));
pics{j}{i} = mrmGet(msh, 'screenshot') ./ 255;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Process the screenshot pics into montage images %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:length(pics)
images{i} = imageMontage(pics{i});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if legend requested, put the image up in a figure w/ the %
% view's color bar %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if leg==1
for i = 1:length(images)
h(i) = figure('Name', mfilename, 'Color', 'w', ...
'Units', 'normalized', 'Position', [.1 .2 .7 .7]);
nRows = ceil( sqrt( length(scans) ) );
nCols = ceil( length(scans) / nRows );
for j = 1:length(scans)
hAx(j) = subplot(nRows, nCols, j);
image(pics{i}{j}); axis image; axis off;
title( annotation(V, scans(j)) );
set(gca, 'Position', get(gca, 'OuterPosition') - [0 0 0 .08]);
end
% add a color bar
hPanel = addCbarLegend(V, h(i), .15);
end
end
%%%%%%%%%%%%%%%%%%%%%
% save if specified %
%%%%%%%%%%%%%%%%%%%%%
if ~isempty(savePath)
ensureDirExists( fileparts(savePath) );
for i = 1:length(images)
[p f ext] = fileparts(savePath);
if isequal(lower(ext), '.ppt') & ispc
% paste into powerpoint presentation
fig = figure; imshow(img);
[ppt, op] = pptOpen(savePath);
pptPaste(op,fig,'meta');
pptClose(op,ppt,savePath);
close(fig);
fprintf('Pasted image in %s.\n', fname);
else
if isequal(lower(ext), '.ppt'),
q = ['Sorry, can only export to PowerPoint files on ' ...
'Windows machines right now. Save images as ' ...
'*.png files instead?'];
resp = questdlg(q, mfilename);
if ~isequal(resp, 'Yes'), return; end
end
mapName = V.mapName;
if checkfields(V, 'ui', 'displayMode')
switch V.ui.displayMode
case 'ph', mapName = 'Phase';
case 'amp', mapName = 'Amplitude';
case 'co', mapName = 'Coherence';
case 'map', mapName = V.mapName;
end
end
fname = sprintf('%s_%s.png', mapName, settings(i).name);
imgPath = fullfile(savePath, fname);
if leg==1 % save the figure w/ the image + colorbar
% export the figure w/ the cbar included
% (try to use exportfig, which is not always available)
if exist('exportfig', 'file')
exportfig(h(1), imgPath, 'Format', 'png', 'Color', 'cmyk', ...
'width', 3.5, 'Resolution', 450);
else
saveas(h(1), imgPath, 'png');
end
else % just write out the image
imwrite(images{i}, imgPath, 'png');
end
fprintf('Saved image %s.\n', imgPath);
end
end
end
return
% /---------------------------------------------------------------------/ %
% /---------------------------------------------------------------------/ %
function params = meshCompareScansParams(V, dt, savePath, leg);
% put up a dialog to get the scans and settings for meshCompareScans.
mrGlobals;
msh = viewGet(V, 'currentMesh');
% first check that there are saved settings:
settingsFile = fullfile(fileparts(msh.path),'MeshSettings.mat');
if ~exist(settingsFile,'file')
myErrorDlg(['Sorry, you need to save some mesh settings first. ' ...
'Use the menu Edit | Save Camer Angles | Save in ' ...
'the 3D Window, or the meshAngle function.']);
end
load(settingsFile, 'settings');
% build dialog
scanList = {dataTYPES(dt).scanParams.annotation};
for i = 1:length(scanList)
scanList{i} = sprintf('(%i) %s', i, scanList{i});
end
dlg(1).fieldName = 'scans';
dlg(1).style = 'listbox';
dlg(1).string = 'Take images of which scans?';
dlg(1).list = scanList;
dlg(1).value = 1;
dlg(2).fieldName = 'settings';
dlg(2).style = 'listbox';
dlg(2).string = 'Take a picture at which camera settings?';
dlg(2).list = {settings.name};
dlg(2).value = 1;
dlg(3).fieldName = 'savePath';
dlg(3).style = 'filenamew';
dlg(3).string = 'Save Image as? (Empty=no save)';
dlg(3).value = savePath;
dlg(4).fieldName = 'leg';
dlg(4).style = 'checkbox';
dlg(4).string = 'Include Colorbar';
dlg(4).value = leg;
% put up dialog
params = generalDialog(dlg, 'Mesh Multi-Angle');
if isempty(params)
error('User aborted.')
end
% parse params
for s = 1:length(params.scans)
tmp(s) = cellfind(dlg(1).list, params.scans{s});
end
params.scans = tmp;
return
|
github
|
andregouws/mrMeshPy-master
|
meshMatchSettings.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/meshviewer/meshMatchSettings.m
| 4,335 |
utf_8
|
009f6a9398b567be79bc3cb4d8f6c0b9
|
function settings = meshMatchSettings(src, tgt, varargin);
% Adjust the view settings on one or more target meshes to match that on
% the source mesh.
%
% settings = meshMatchSettings([sourceMesh=current mesh], [targetMeshes], [gray/volume view]);
%
% INPUTS:
% sourceMesh: mesh whose view settings you want to replicate on other
% meshes. You can provide a mesh structure, the number of a mesh in the
% current gray view, or the number of the mesh window as a character (e.g.,
% use '1' for a mesh window named 'mrMesh 1', but use 1 for the
% first mesh in the view). [Default: selected mesh in gray view].
%
% targetMeshes: specification of one or more meshes whose view settings
% will match that of the source mesh. Can be specified in the same way as
% sourceMesh. If you want to specify multiple target meshes, you can
% specify them as a cell array (or, in the case of numeric mesh indexes,
% a numeric array, or a struct array in the case of full mesh strucures).
% [Default: prompt user to select meshes].
%
% [gray/volume view]: a gray or volume view structure which has the
% relevant meshes loaded. This isn't needed if you're providing the full
% mesh structures as inputs. [Default: use selected gray view]
%
% RETURNS:
% settings: settings structure from the source mesh.
%
% SEE ALSO: meshSettings, meshStoreSettings, meshRetrieveSettings.
%
% ras, 08/2009.
% I allow several target meshes to be input as varargin (allowing me to type the
% IDs as strings): the view G is always the last of these, if it's specified.
if ~isempty(varargin)
if isstruct(varargin{end})
G = varargin{end};
else
G = [];
end
tgt = [{tgt} varargin];
end
if notDefined('G')
% don't call getSelectedGray if both src and target are provided as
% structures -- we don't want to force this code to depend on the
% mrVista data structure if we don't need to.
if ( isstruct(src) | (iscell(src) & isstruct(src{1})) ) & ...
( isstruct(tgt) | (iscell(tgt) & isstruct(tgt{1})) )
G = [];
else
G = getSelectedGray;
end
end
if notDefined('src'),
src = G.mesh{G.meshNum3d};
end
% parse the source mesh structure
if ~isstruct(src)
src = parseMeshStructure(src, G);
end
% get the source mesh settings
settings = meshSettings(src);
if notDefined('tgt'),
% user dialog
dlg.fieldName = 'whichMeshes';
dlg.style = 'listbox';
dlg.string = sprintf(['Apply Mesh Settings from Mesh %i to which ' ...
'other meshes?'], src.id);
for n = 1:length(G.mesh)
dlg.list{n} = [num2str(G.mesh{n}.id) '. ' G.mesh{n}.name];
end
dlg.value = 1;
[resp ok] = generalDialog(dlg, mfilename);
if ~ok, fprintf('[%s]: User aborted.\n', mfilename); return; end
for n = 1:length(resp.whichMeshes)
tgt(n) = cellfind(dlg.list, resp.whichMeshes{n});
end
end
% parse the target mesh specification
if ~ischar(tgt) & length(tgt) > 1
% iteratively apply to several meshes
for n = 1:length(tgt)
if iscell(tgt)
currTarget = parseMeshStructure(tgt{n}, G);
else
currTarget = parseMeshStructure(tgt(n), G);
end
meshApplySettings(currTarget, settings);
end
else
tgt = parseMeshStructure(tgt, G);
meshApplySettings(tgt, settings);
end
return
% /--------------------------------------------------------------------/ %
% /--------------------------------------------------------------------/ %
function msh = parseMeshStructure(msh, G);
% given a mesh specification (which could be one of many things) and a view
% with meshes, return a mesh structure.
if isstruct(msh),
% we're good...
return;
end
if iscell(msh)
for n = 1:length(msh)
msh(n) = parseMeshStructure(msh{n}, G);
end
return
end
if ischar(msh)
% id of mesh window ... find it in this view:
targetID = str2num(msh);
for n = 1:length(G.mesh)
ids(n) = G.mesh{n}.id;
end
msh = find(ids==targetID);
if isempty(msh)
error('Couldn''t find mesh id %i in view.', targetID);
end
% now it's numeric, so it should go through the indexing code below...
end
if isnumeric(msh)
% numeric index into G's meshes
whichMeshes = msh; clear msh
for n = 1:length(whichMeshes)
msh(n) = G.mesh{whichMeshes(n)};
end
end
if isempty(msh)
error('Empty mesh specification.')
end
return
|
github
|
andregouws/mrMeshPy-master
|
mrmSet.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmSet.m
| 21,644 |
utf_8
|
cc937f4caa7c19408dfdea0353f9ab69
|
function [msh, ret] = mrmSet(msh,param,varargin)
% General interface for communicating with mrMesh parameters.
%
% [msh, ret] = mrmSet(msh,param,varargin)
%
% This routine keeps track of what we need to do to adjust different types
% of visual properties of the image.
%
% The routine tries to update the msh structure to keep it in synch with
% the display. There may be bugs therein.
%
% The mesh structure contains parameters that include various important
% parameters. These include the
% * identity of the host computer running the mrMesh server (usually 'localhost')
% * the number of the mrMesh window (id)
% * the Actor (i.e., object) within the window
%
% Actor values [0,31] are reserved with camera (0), cursor (1).
% Meshes are assigned an actor value of 32 and above.
%
% The values in the mesh structure are accessed through the meshGet
% routine. The same mesh structure is used by mrMesh, mrGray and
% mrFlatMesh.
%
% Some parameters require additional specification. These can be passed
% as additional arguments that are parsed by the varargin mechanism in
% Matlab.
%
% See also: mrmSet, mrMesh, meshGet, meshSet
%
% Examples:
% mrmSet(msh,'background',[.3,.3,.3,1]);
% mrmSet(msh,'addlight',ambient,diffuse,origin);
%
% Programming Notes: (TODO List)
% * Query for the names and number of open mrMesh windows.
% * Get the vertex number from a click (not just the XYZ position of the surface.
% * Remove an actor from the window. Add a new actor at a distinct position.
% * Get various types of build_mesh working, not just smooth and decimate.
% * Hide the lights
%
% HISTORY:
%
% 2004.06.11 RFD: fixed hideCursor. We also now need to use 'showcursor' to
% turn it back on, as it no longer comes on when you click the mesh. I've
% added a 'toggleCursor' command to make the GUI changes minimal (still
% uses just one button).
%
% Started by Wandell many years ago
%
% Default parameters
if ieNotDefined('msh'), error('You must specify a mesh.'); end
% Sometimes we pass in the whole array of meshes. Mostly, just one,
% though.
if iscell(msh)
host = meshGet(msh{1},'host');
windowID = meshGet(msh{1},'windowid');
else
host = meshGet(msh, 'host');
windowID = meshGet(msh, 'windowid');
end
% Confirm that we have a host and windowID ready to go
if isempty(host), host = 'localhost'; end
if isempty(windowID), error('Mesh must specify a window'); end
% Lower case and remove spaces
param = mrvParamFormat(param);
switch param
case {'close','closeone','closecurrent'}
mrMesh(host,windowID,'close');
msh = meshSet(msh,'id',-1);
case {'closeall','allclose'}
% mrmSet(msh(),'closeall');
for ii=1:length(msh), msh{ii} = mrmSet(msh{ii},'close'); end
ret = msh;
case {'actor','addactor','meshactor'}
% msh = mrmSet(msh,'addactor');
% Add an actor to an existing window, or if no window is open
% open one, set open an actor, and set its windowID.
p.class = 'mesh';
[~, ~, val] = mrMesh(host, windowID, 'add_actor', p);
if checkfields(val,'actor'),
msh = meshSet(msh,'actor',val.actor);
msh = meshSet(msh,'windowid',windowID);
else
error('Problem adding mesh actor to window.');
end
case {'lightorigin'}
% mrmSet(msh,'lightorigin',lightActor,origin);
light.class = 'light';
if length(varargin) < 2 || isempty(varargin{2}),
error('Require lightActor and origin');
else
light.actor = varargin{1};
light.origin = varargin{2};
end
mrMesh(host, windowID, 'set', light);
case {'showlight'}
% Sets up a light defined by the three parameters in window of the
% msh.
% mrmSet(msh,'addlight',ambient,diffuse,origin);
l.class = 'light';
[~,stat,res] = mrMesh(host, windowID, 'add_actor', l);
if stat < 0, error('Error adding light actor.'); end
light.actor = res.actor;
if length(varargin) < 1 || isempty(varargin{1}), ambient = [0 0 0]; %[.3,.3,.3];
else ambient = varargin{1}; end
if length(varargin) < 2 || isempty(varargin{2}), diffuse = [1 1 1]; % [0.5, 0.5, 0.6];
else diffuse = varargin{2}; end
if length(varargin) < 3 || isempty(varargin{3}), origin = [500,0,300];
else origin = varargin{3}; end
light.ambient = ambient;
light.diffuse = diffuse;
light.origin = origin;
mrMesh(host, windowID, 'set', light);
% Should we add this light to the mesh structure? Probably. For
% now, we return light if requested.
if nargout > 1, ret = light; end
case {'addlight'}
if length(varargin) < 1 || isempty(varargin{1}), ambient = [.3,.3,.3];
else ambient = varargin{1}; end
if length(varargin) < 2 || isempty(varargin{2}), diffuse = [0.5, 0.5, 0.6];
else diffuse = varargin{2}; end
if length(varargin) < 3 || isempty(varargin{3}), origin = [500,0,300];
else origin = varargin{3}; end
[msh,ret] = mrmSet(msh,'showlight',ambient,diffuse,origin);
msh = meshSet(msh,'addlight',ret);
case {'addimage','addimageactor'}
% imgParameters.img = ieScale(rand(64,64),0,1);
% imgParameters.actor = 38;
% imgParameters.origin = [50,0,50];
%
% mrmSet(msh,'addimage',imgParameters)
% imgParameters should contain
% .img ( values between 0,1; image size is a power of 2 though we will pad if needed)
% .origin (default = [0,0,0])
% .rotation
% This code is an initial draft. It needs more work and better
% understanding. But, it does put up an image in the window.
%
% The image must be a power of 2 in size because of openGL
% considerations.
% The image appears as a texture in a plane specified within the
% parameters
im.class = 'image';
% Set up the parameters
imgParameters = varargin{1};
if checkfields(imgParameters,'rotation'), im.rotation = imgParameters.rotation;
else im.rotation = [0 0 1; 0 1 0; 1 0 0]; end
if checkfields(imgParameters,'origin'), im.origin = imgParameters.origin;
else im.origin = [0 0 0]; end
if checkfields(imgParameters,'actor'), im.actor = imgParameters.actor;
else
[~,~,r] = mrMesh(imageMesh.host, imageMesh.id, 'add_actor', im);
im.actor = r.actor;
end
imgData = imgParameters.img;
% Check the parameters
if max(imgData(:)) > 1 || min(imgData(:)) < 0, error('Image data must be between 0 and 1'); end
if size(imgData,3) ~= 1, error('We are expecting a gray scale image.'); end
% Set up size parameters, making sure the array is a power of 2.
% padarray(img,1,padsize(1));
% padarray(img,2,padsize(2));
imSize = 2.^ceil(log2(size(imgData)));
im.width = imSize(1);
im.height = imSize(2);
im.tex_width = imSize(2);
im.tex_height = imSize(1);
% Copy the data into the center of the image that has the proper
% size. Presumably, there is a way to do this with padarray().
sz = size(imgData');
pos = floor((imSize-sz)./2)+1;
newData = zeros(imSize);
newData(pos(1):pos(1)+sz(1)-1, pos(2):pos(2)+sz(2)-1) = imgData';
im.texture = repmat(newData(:)', 3,1);
% Set alpha to 0 if transparency is enabled (erode/dilate to smooth)
% mask = imdilate(imerode(imData>0.1,strel('disk',4)),strel('disk',4));
% im.texture(4,:) = double(mask(:));
% No transparency
im.texture(4,:) = ones(size(im.texture(1,:)));
% Add the image data to the actor
[~,~,~] = mrMesh(host, windowID, 'set', im);
case {'removeactor','deleteactor','removeactors','deleteactors','removelistofactors','deletelistofactors'}
% mrmSet(msh,'deleteActor',33)
% Do we need to specify the class, such as light/mesh/image?
if ~isempty(varargin{1}), deleteList = varargin{1};
else warning('mrmSet: No actors to delete.'); return;
end
deleteList = deleteList(deleteList);
for ii=1:length(deleteList)
p.actor = deleteList(ii);
mrMesh(host, windowID, 'remove_actor', p);
end
case {'builddecimatesmooth','buildmeshanddecimateandsmooth'}
% mrmSet(msh,'buildMeshAndDecimateAndSmooth',voxels);
if length(varargin) < 1; error('Must pass in voxels.'); end
p.voxels = varargin{1};
% It is possible that scale should be scale = scale([2,1,3]) -- BW
p.scale = meshGet(msh,'mmPerVox');
p = setSmooth(p,msh,1);
p = setDecimate(p,msh,1);
p.actor = meshGet(msh,'actor');
mrMesh(host, windowID, 'build_mesh', p);
case {'buildnosmooth'}
% mrmSet(msh,'buildMeshAndDecimateAndSmooth',voxels);
if length(varargin) < 1; error('Must pass in voxels.'); end
p.voxels = varargin{1};
% It is possible that scale should be scale = scale([2,1,3]) -- BW
p.scale = meshGet(msh,'mmPerVox');
p = setSmooth(p,msh,0);
p = setDecimate(p,msh,1);
p.actor = meshGet(msh,'actor');
mrMesh(host, windowID, 'build_mesh', p);
case {'setmesh','setdata','data'}
% mrmSet(msh,'setdata')
p = meshGet(msh,'data');
p.actor = actorCheck(msh);
mrMesh(host, windowID, 'set_mesh', p);
case {'meshvertices','vertices'}
% mrmSet(msh,'vertices');
p.actor = actorCheck(msh);
p.vertices = meshGet(msh,'vertices');
mrMesh(host, windowID, 'modify_mesh', p);
case 'camerarotation'
if isempty(varargin); error('Must pass in rotation matrix.'); end
p.actor = 0;
if ~isequal(size(varargin{1}),[3,3]), error('Rotation matrix is not 3x3');
else p.rotation = varargin{1};
end
mrMesh(host,windowID,'set',p);
case 'cameraorigin'
if isempty(varargin); error('Must pass in origin.'); end
if length(varargin{1}) ~= 3, error('Origin must be 3d vector');
else p.origin = varargin{1};
end
p.actor = 0;
mrMesh(host,windowID,'set',p);
case 'cameraspace'
p.actor = 0;
p.camera_space = varargin{1}; % ?? val;
mrMesh(host,windowID,'set',p);
case 'background'
% Set the RGB color of the background.
c = varargin{1};
if length(c) == 3, c(4) = 1;
elseif length(c) == 4
else error('color must be RGB or RGBalpha');
end
p.color = c;
mrMesh(host,windowID,'background',p);
case 'transparency'
% mrmSet(mesh,'transparency',1/0);
if ~isempty(varargin), p.enable = double(varargin{1});
else p.enable = 1; end
mrMesh(host, windowID, 'transparency', p);
case {'windowsize','meshwindowsize','displaysize'}
% mrmSet(msh,'windowSize',256,256);
if length(varargin) < 2, error('Window size requires width and height'); end
p.height = varargin{1};
p.width = varargin{2};
mrMesh(host,windowID,'set_size',p);
case {'refresh','windowrefresh'}
[~,ret] = mrMesh(host,windowID,'refresh');
case 'actorrotation'
% mrmSet(msh,'actorrotation',rMatrix);
% Not debugged thoroughly!
if isempty(varargin), error('Rotation matrix required.'); end
p.rotation = varargin{1};
p.actor = meshGet(msh,'Actor');
mrMesh(host, windowID, 'set', p);
msh = meshSet(msh,'rotation',p.rotation);
case {'actororigin','origin'}
% mrmSet(msh,'origin',origin);
if isempty(varargin), error('Origin argument.'); end
p.origin = varargin{1};
p.actor = meshGet(msh,'Actor');
mrMesh(host, windowID, 'set', p);
msh = meshSet(msh,'origin',p.origin);
case {'applysmooth','applysmoothing'}
% mrmSet(msh,'applysmooth');
warning('Use meshSmooth, not mrmSet(msh,''applysmooth'') to smooth meshes')
return;
% p.smooth_iterations = msh.smooth_iterations;
% p.smooth_relaxation = msh.smooth_relaxation;
% p.smooth_sinc_method = msh.smooth_sinc_method;
% p.actor = meshGet(msh,'actor');
% [id,stat] = mrMesh(host, windowID, 'smooth', p);
case {'smooth','smoothmesh','meshsmooth'}
% mrmSet(msh,'smooth');
warning('Use meshSmooth, not mrmSet(msh,''smoothlarge'') to smooth meshes')
return;
% p.smooth_iterations = meshGet(msh,'relaxIter');
% p.smooth_relaxation = meshGet(msh,'relaxFactor');
% p.smooth_sinc_method = meshGet(msh,'smoothMethod');
% p.actor = meshGet(msh,'actor');
% [id,stat] = mrMesh(host, windowID, 'smooth', p);
case {'smoothlarge','smoothmeshlarge','meshsmoothlarge'}
% mrmSet(msh,'smoothlarge',[smoothFactor = 3]);
% RFD- we now fix the smoothing relaxation value and let the user
% specify the number of iterations.
warning('Use smoothpatch, not mrmSet(msh,''smoothlarge'') to smooth meshes')
return;
% if isempty(varargin), sFactor = 3; else sFactor = varargin{1}; end
% p.smooth_iterations = sFactor;
% p.smooth_sinc_method = meshGet(msh,'smoothMethod');
% if(p.smooth_sinc_method)
% p.smooth_relaxation = 0.0001;
% else
% p.smooth_relaxation = 1.0;
% end
% p.actor = meshGet(msh,'actor');
% [id,stat] = mrMesh(host, windowID, 'smooth', p);
%
case {'decimate','decimatemesh'}
% mrmSet(msh,'decimate_mesh');
warning('Use reducepatch, not mrmSet(msh,''smoothlarge'') to smooth meshes')
return;
% p.decimate_reduction = meshGet(msh,'decimate_reduction');
% p.actor = meshGet(msh,'actor');
% [id,stat,res] = mrMesh(host, windowID, 'decimate', p);
%
case {'curvature','curvatures'}
% mrmSet(mesh,'curvature')
% Shows the curvature shading and also attaches the values to the
% mesh data structure
% Hunh? This routine looks like it gets the curvature values from
% the window and puts them into msh rather than setting them.
% warning('Use meshColor, to color the mesh with its curvature')
% return;
p.actor = meshGet(msh,'actor');
p.modulate_color = meshGet(msh,'curvaturecolor');
p.mod_depth = meshGet(msh,'curvaturemodulationdepth');
p.get_values = 1;
[~, ~, v] = mrMesh(host, windowID, 'curvatures', p);
msh = meshSet(msh,'curvature',v.values);
case {'originlines'}
%mrmSet(mesh,'originlines',0) (Turn off)
%mrmSet(mesh,'originlines',1) (Turn on)
if ~isempty(varargin), p.enable = varargin{1};
else p.enable=0; end
p.actor = meshGet(msh,'Actor');
mrMesh(host, windowID, 'enable_origin_arrows', p);
case {'cursorposition','cursor'}
% msh = viewGet(VOLUME{1},'currentmesh');
% mrmSet(msh,'cursorPosition',meshGet(msh,'origin'));
% mrmSet(msh,'cursorPosition',[-100,-100,-100]);
if ~isempty(varargin), val = varargin{1};
else error('Must provide a coordinate.'); end
val = val(:)';
if length(val) ~= 3, error('Cursor coordinates must be 3D'); end
mmPerVox = meshGet(msh,'mmpervox');
origin = meshGet(msh,'origin');
p.actor = 1;
%p.origin = val([2,1,3]) .* mmPerVox + origin;
%[id,stat,res] = mrMesh(msh.host,msh.id, 'set', p);
p.position = (val([2,1,3]) .* mmPerVox + origin)';
[~,~,res] = mrMesh(host,windowID, 'set_selection', p);
if(isfield(res,'error'))
disp([mfilename ': mrMesh error "' res.error '"']);
end
mrmSet(msh,'refresh');
case {'cursorvertex'}
if ~isempty(varargin), val = varargin{1};
else error('Must provide a vertex.'); end
vert = meshGet(msh,'vertices');
origin = meshGet(msh,'origin');
p.position = vert(:,val) + origin';
p.actor = 1;
[~,~,~] = mrMesh(host, windowID, 'set_selection', p);
case {'cursorraw'}
if(length(varargin)==1 && numel(varargin{1})==3), val = varargin{1};
else error('Must provide a 1x3 coordinate.'); end
p.position = val(:);
p.actor = 1;
mrMesh(host, windowID, 'set_selection', p);
%if(stat~=0) disp(res); end
case {'hidecursor','cursoroff'}
% mrmSet(msh,'hidecursor');
p.enable = 0;
mrMesh(host,windowID, 'enable_3d_cursor', p);
case {'showcursor','cursoron'}
% mrmSet(msh,'showcursor');
p.enable = 1;
mrMesh(host,windowID, 'enable_3d_cursor', p);
case {'colors','overlaycolors','overlay'}
% mrmSet(mesh,'colors',rgbAlpha);
if isempty(varargin), error('rgbAlpha data required.'); end
c = varargin{1};
% If it is a 1D variable, make it a gray scale color map.
if min(size(c)) == 1, c = c(:); c = repmat(c,1,3); end
% If the data are 3D, add the alpha channel now
if size(c,2) == 3, c(:,4) = 255*ones(size(c,1),1); end
if size(c,2) ~= 4, error('Bad color data.'); end
p.actor = meshGet(msh,'actor');
p.colors = uint8(c');
mrMesh(host, windowID, 'modify_mesh', p);
msh = meshSet(msh,'colors',p.colors);
case {'alpha','alphachannel'}
% mrmSet(mesh,'alpha',alpha);
if isempty(varargin), error('alpha data required.'); end
c = varargin{1};
c = c(:);
if(length(c)>1 && length(c)~=length(msh.data.colors(4,:)))
error('Bad alpha data.');
end
p.actor = meshGet(msh,'actor');
p.colors = uint8(msh.data.colors);
if isa(c, 'uint8')
p.colors(4,:) = c;
else
p.colors(4,:) = uint8(round(c*255));
end
mrMesh(host, windowID, 'modify_mesh', p);
msh = meshSet(msh,'colors',p.colors);
case {'windowtitle','title'}
% mrmSet(msh,'windowtitle','title goes here');
if isempty(varargin), error('Title required.'); end
p.title = varargin{1};
mrMesh(host, windowID, 'set_window_title',p);
otherwise
error('Unknown mrmMesh parameter');
end
return;
%----------------------
function actor = actorCheck(msh)
%
% We need this a lot, so I wrote this routine rather than repeating it
% throughout.
%
actor = meshGet(msh,'actor');
if isempty(actor)
error('This meshGet call requires an actor in the mesh structure.');
end
return;
%---------------------------------------
function p = setSmooth(p,msh,val)
if val && meshGet(msh,'smoothiterations')>0
p.do_smooth = 1;
p.smooth_iterations = meshGet(msh,'smoothiterations');
p.smooth_relaxation = meshGet(msh,'smoothrelaxation');
p.smooth_sinc_method = meshGet(msh,'smoothmethod');
p.do_smooth_pre = meshGet(msh,'smooth_pre');
else
p.do_smooth = 0;
p.do_smooth_pre = 0;
end
return;
%----------------------------
function p = setDecimate(p,msh,val)
if val && meshGet(msh,'decimateiterations')>0
p.do_decimate = 1;
p.decimate_reduction = meshGet(msh,'decimatereduction');
p.decimate_iterations = meshGet(msh,'decimateiterations');
else
p.do_decimate = 0;
end
return;
% These don't seem to be much needed and could be eliminated. They
% are left around just in case we go on a building spree and decide
% we need these
% case {'builddecimate','buildmeshanddecimate','buildanddecimate'}
% % mrmSet(mesh,'buildMeshAndDecimate',voxels);
% if length(varargin) < 1; error('Must pass in voxels.'); end
% p.voxels = varargin{1};
% p.scale = meshGet(mesh,'mmPerVox');
% p = setSmooth(p,mesh,0);
% p = setDecimate(p,mesh,1);
% p.actor = actorCheck(mesh);
% [id, stat, res] = mrMesh(host, windowID, 'build_mesh', p);
% case {'buildsmooth','buildandsmooth'}
% % mrmSet(mesh,'buildSmooth',voxels);
% if length(varargin) < 1; error('Must pass in voxels.'); end
% p.voxels = varargin{1};
% p.scale = meshGet(mesh,'mmPerVox');
% p = setSmooth(p,mesh,1);
% p = setDecimate(p,mesh,0);
% p.actor = actorCheck(mesh);
% [id, stat, res] = mrMesh(host, windowID, 'build_mesh', p);
% case {'build','buildonly','buildmesh','buildmeshonly'}
% % mrmSet(mesh,'buildMesh',voxels);
% if length(varargin) < 1; error('Must pass in voxels.'); end
% p.voxels = varargin{1};
% p.scale = meshGet(mesh,'mmPerVox');
% p = setDecimate(p,mesh,0);
% p = setSmooth(p,mesh,0);
% p.actor = actorCheck(mesh);
% [id, stat, res] = mrMesh(host, windowID, 'build_mesh', p);
|
github
|
andregouws/mrMeshPy-master
|
mrmLoadOffFile.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmLoadOffFile.m
| 2,197 |
utf_8
|
8921617d9bfdc2f7e17d3aef4bf2fae0
|
function msh = mrmLoadOffFile(offFile, origin)
% Buils a basic mrm structure given an OFF format mesh file.
% mrm = mrmLoadOffFile(offFile, origin)
%
% 2007.06.08 RFD wrote it.
if(~exist('offFile','var')||isempty(offFile))
[f,p] = uigetfile({'*.off';'*.*'},'Select the OFF file...');
if(isnumeric(f)); disp('user canceled.'); return; end
offFile = fullfile(p,f);
end
if(~exist('origin','var')||isempty(origin))
msh.origin = [0 0 0];
else
msh.origin = origin;
end
% Read new vertex locations
fid = fopen(offFile, 'r', 'ieee-be');
if fid == -1,
delete(inFile);
delete(outFile);
error('Could not open file');
end
%--- read .off output file
% Header
hdr = fgetl(fid);
% First see if we have a SurfRelax patch header
if(strcmp(hdr,'#PATCH'))
% header information from SURFRelax. Becuase this file has a subset of
% vertices from a parent mesh
msh.parentInds = getSRHeader(fid);
hdr = fgetl(fid);
end
% Now we can read the mesh data
if(strcmp(hdr,'OFF BINARY'))
% binary format
n = fread(fid, 3, 'int32');
% Read the vertices
msh.vertices = fread(fid, [3 n(1)], 'float32');
msh.triangles = fread(fid, [5 n(2)], 'int32');
elseif(strcmp(hdr,'OFF'))
% text format, probably from FSL's bet
n = fscanf(fid, '%d', 3);
% Read the vertices
msh.vertices = fscanf(fid, '%f', [3 n(1)]);
msh.triangles = fscanf(fid, '%d', [4 n(2)]);
end
fclose(fid);
if(any(msh.origin~=0))
for ii=1:3
msh.vertices(ii,:) = msh.vertices(ii,:) - msh.origin(ii);
end
end
msh.triangles = msh.triangles(2:4,:);
msh.lights = [];
msh.id = -1;
return;
function [parentInds] = getSRHeader(fid)
% This header contains the map from a patch mesh to the parent mesh
foundInds=0;
while ~foundInds
line = fgetl(fid);
delI = strfind(line,'=');
if strcmp(line(1:delI-1),'#patch_dimensions')
foundInds=1;
patchInds = sscanf(line(delI+1:end),'%d');
patchInds = patchInds(1);
end
end
% Skip a text line
fgetl(fid);
% Get the parent indices for each patch vertex
parentInds = zeros(1,patchInds);
for ii=1:patchInds
line = fgetl(fid);
n = sscanf(line,'#%d %d');
parentInds(ii) = n(2);
end
return;
|
github
|
andregouws/mrMeshPy-master
|
mrmConvertEMSEMesh.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmConvertEMSEMesh.m
| 7,409 |
utf_8
|
b1b775d767cc4e8aed9c6e10bf5ac683
|
function [msh,lights,tenseMsh] = mrmConvertEMSEMesh(fileName,mmPerVox, host, id, varargin);
%
% [msh,lights,tenseMsh] = mrmConvertEMSEMesh(fileName,mmPerVox, host, id, varargin);
%
%
% Author: ARW (based on RFD's mrmBuildMesh)
% Purpose:
% Take a mesh in EMSE's .wfr format and convert it into a mrLoadRet /
% mrMesh-type mesh. Allows you to do the usual mrMesh type things like
% relaxation...
% Additional processing options can be set as well. These
% options include:
% * 'RelaxIterations'- the next value specifies how many extra smoothing iterations.
% * 'SavetenseMsh'- if you specify any RelaxIterations and add this option, then
% you will get two meshes- the relaxed mesh and the unrelaxed (tense) mesh.
%
% Returns:
% The mesh structure and a lights structure.
% You can also get the unrelaxed mesh out (tenseMsh).
%
% See Also
% mrmMapVerticesToGray
%
% Examples:
% mrmConvertEMSEMesh('x:\anatomy\norcia\EMSE\test.wfr', view.mmPerVox, 'Background', [0.3,0.4,0.5]);
% mrmBuildMesh('x:\anatomy\norcia\EMSE\test.wfr', view.mmPerVox, 'localhost', -1);
% mrmBuildMesh('x:\anatomy\norcia\EMSE\test.wfr', view.mmPerVox, 'localhost', -1, ...
% 'RelaxIterations', relaxIterations, 'SavetenseMsh');
%
% Notes:
% 2003.09.17 RFD: vertex-to-volume mapping is now done in a separate
% function (mrmMapVerticesToGray), and we don't call it. So, the calling
% function will need to compute that mapping and add the appropriate
% fields to the mesh struct.
% transparency is off by default because it is slow.
mrGlobals;
summaryParams = 1;
meshName = '';
QueryFlag = 1;
relaxIter = 1;
saveTense = 0;
backColor = [0.2 0 0]; % CHanged from Gray - partly just to keep track of EMSE meshes...
if ieNotDefined('fileName'), error('EMSE format file is required.'); end
if ieNotDefined('mmPerVox'), error('mmPerVox is required.'); end
if ieNotDefined('host'), host = 'localhost'; end
if ieNotDefined('id'), id = 1; end
if(nargout>2), saveTense = 1; end
% Parse the varargin values
for(ii=1:length(varargin))
if (strcmpi(varargin{ii}, 'RelaxIterations')), relaxIter = varargin{ii+1};
elseif(strcmpi(varargin{ii}, 'QueryFlag')), QueryFlag = varargin{ii+1};
elseif(strcmpi(varargin{ii}, 'MeshName')), meshName = varargin{ii+1};
elseif (strcmpi(varargin{ii},'Background')), backColor = varargin{ii+1};
end
end
% Set initial parameters for the mesh.
msh = meshDefault(host,id,mmPerVox,relaxIter,meshName);
if QueryFlag, msh = meshQuery(msh,summaryParams); end
% If the window is already open, no harm is done.
msh = mrmInitHostWindow(msh)
[msh, lights] = mrmInitMesh(msh,backColor);
disp('Importing mesh data from EMSE')
%
% ***************************************************************
% We need to construct a basic msh structure from the file data.
[vertex,face,edge,mesh]=mesh_emse2matlab2(fileName);
% Vertices come back rotated in an odd way. The entire cortex is rotated 90
% degrees about the L/R axis (i.e. the sag view is rotated 90degrees
% anticlockwise).
v=vertex(1:2,:);
v=v-128;
rotMat=[0 -1;1 0];
v=v'*rotMat;
vertex(1:2,:)=v'+128;
LR=vertex(3,:);
LR=(256-LR);
vertex(3,:)=LR;
face=face([3 2 1],:);
nVerts=length(vertex);
%vertex=vertex*10000;
p.vertices=(vertex);
p.triangles=face;
p.triangles = p.triangles - 1
p.class='mesh';
% Sometimes we pass in the whole array of meshes. Mostly, just one,
% though.
host = meshGet(msh,'host');
windowID = meshGet(msh,'windowid');
if isempty(host), host = 'localhost'; end
if isempty(windowID), error('Mesh must specify a window'); end
%[id, status, result] = mrMesh ('localhost', windowID, 'add_actor', p)
p.scale = meshGet(msh,'mmPerVox');
p = setSmooth(p,msh,1);
p = setDecimate(p,msh,1);
p.actor = meshGet(msh,'actor');
p.colors=ones(4,length(p.vertices))*255;
[a,b,c]=mrmesh('localhost',id,'set_mesh',p)
p.scale = meshGet(msh,'mmPerVox');
p = setSmooth(p,msh,1);
p = setDecimate(p,msh,1);
%p.actor = meshGet(msh,'actor');
p.normals=mrmGet(msh,'normals');
p.actor = meshGet(msh,'actor');
%disp('Building smoothed and decimated mesh for display...');
%mrmSet(msh,'buildMeshAndDecimateAndSmooth',voxels);
%[msh] = mrmSet(msh,'smooth')
% This is a little 'center object' routine. We could put this into mrmSet,
% really.
vertices = mrmGet(msh,'vertices');
mrmSet(msh,'origin',-mean(vertices'));
% Save these unsmoothed data.
unSmoothedData = mrmGet(msh,'data');
msh.initVertices=vertices;
msh.grayLayers=3;
view=getSelectedVolume;
disp('Finding vertex to gray map');
% You have to do this before smoothing...
v2gMap = mrmMapVerticesToGray(vertices,view.nodes,[1 1 1]);
msh.vertexGrayMap=v2gMap;
msh.grayToVertexMap = mrmMapGrayToVertices(view.nodes,vertices, [1 1 1]);
% Now also try to find the other mapping: the mapping from the mesh to all
% the gray nodes: So that we can ask: for any arbitray gray node, which
% mesh point is it closest to?
% If we smooth, the mesh, it is done here.
if(relaxIter>0)
mrmSet(msh,'smooth');
% We get the curvature colors from the uninflated mesh
% We should figure out the correct value to use as our threshold. The mean
% isn't ideal, since it is moved around by the large areas with arbitrary
% curvature (eg. corpus callosum). What we really want is the value that
% corresponds to zero curvature.
% maybe make the specific curvature map colors adjustable?
% We now use the actual curvature values, so we know that zero is zeros
% curvature.
disp('Setting up the curvature colors');
% Attach curvature data to the mesh. We turn on the color later, I think.
msh=mrmSet(msh,'curvature');
p.colors=[repmat(msh.curvature,3,1); ones(1,length(msh.curvature))]*255;
%[a,b,c]=mrmesh('localhost',id,'set_mesh',p)
curvColorIntensity = 128*meshGet(msh,'curvatureModDepth'); % mesh.curvature_mod_depth;
monochrome = uint8(round((double(msh.curvature>0)*2-1)*curvColorIntensity+127.5));
msh = mrmSet(msh,'colors',monochrome);
disp('Storing the smoothed mesh data computed by mrMesh...');
data = mrmGet(msh,'data');
msh = meshSet(msh,'data',data);
msh = meshSet(msh,'connectionMatrix',1);
else
% We don't smooth the data with mrMesh. We just assign it.
msh = meshSet(msh,'data',unSmoothedData);
msh = meshSet(msh,'connectionMatrix',1);
end
% In either case, we return a version of the data without smoothing. This
% mesh is used to register with the gray coordinates. This is a little
% disorganized. If we don't smooth, tenseMesh is identically msh.
tenseMsh = msh;
tenseMsh = meshSet(tenseMsh,'data',unSmoothedData);
return;
%---------------------------------------
function p = setSmooth(p,mesh,val)
if val
p.do_smooth = 1;
p.smooth_iterations = meshGet(mesh,'smoothiterations');
p.smooth_relaxation = meshGet(mesh,'smoothrelaxation');
p.smooth_sinc_method = meshGet(mesh,'smoothmethod');
p.do_smooth_pre = meshGet(mesh,'smooth_pre');
else
p.do_smooth = 0;
p.do_smooth_pre = 0;
end
return;
%----------------------------
function p = setDecimate(p,mesh,val)
if val
p.do_decimate = 1;
p.decimate_reduction = meshGet(mesh,'decimatereduction');
p.decimate_iterations = meshGet(mesh,'decimateiterations');
else
p.do_decimate = 0;
end
return;
|
github
|
andregouws/mrMeshPy-master
|
mrmViewer.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmViewer.m
| 9,185 |
utf_8
|
d0d0d67ec4da80e3dea9f568c4cdae55
|
function varargout = mrmViewer(varargin)
% MRMVIEWER M-file for mrmViewer.fig
% MRMVIEWER, by itself, creates a new MRMVIEWER or raises the existing
% singleton*.
%
% H = MRMVIEWER returns the handle to a new MRMVIEWER or the handle to
% the existing singleton*.
%
% MRMVIEWER('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MRMVIEWER.M with the given input arguments.
%
% MRMVIEWER('Property','Value',...) creates a new MRMVIEWER or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before mrmViewer_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to mrmViewer_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help mrmViewer
% Last Modified by GUIDE v2.5 13-Jul-2011 13:55:22
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mrmViewer_OpeningFcn, ...
'gui_OutputFcn', @mrmViewer_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
return;
% --- Executes just before mrmViewer is made visible.
function mrmViewer_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to mrmViewer (see VARARGIN)
% Choose default command line output for mrmViewer
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
set(hObject,'Position',[0.8706 0.8308 0.1263 0.1250]);
% UIWAIT makes mrmViewer wait for user response (see UIRESUME)
% uiwait(handles.figure1);
return;
% --- Outputs from this function are returned to the command line.
function varargout = mrmViewer_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
return;
% --------------------------------------------------------------------
function menuFile_Callback(hObject, eventdata, handles)
return;
% --------------------------------------------------------------------
function menuLoad_Callback(hObject, eventdata, handles)
%
% Load a mesh file saved by mrVista/mrTools
%
uData = get(hObject,'userdata');
% It would be best to be able to read the list of currently open windows
% and assign a number based on that.
if ~checkfields(uData,'windowID'),
nextWindow = 500;
uData.windowID = nextWindow;
else
nextWindow = max(uData.windowID(:))+1;
uData.windowID(end+1) = nextWindow;
end
% Read a mesh starting in the Matlab working directory.
msh = mrmReadMeshFile(pwd);
if isempty(msh), return; end
msh = meshSet(msh,'windowid',nextWindow);
% Display the mesh. Turn off the origin lines.
msh = mrmInitMesh(msh);
mrmSet(msh,'hidecursor');
name = meshGet(msh,'name');
if isempty(name), [p,name] = fileparts(filename); end
mrmSet(msh,'title',name);
% Save the file information in the window object's user data. We should be
% doing this for mrDiffusion, too. And we should use this saved
% information when we ask about Editing windows.
set(hObject,'userdata',uData);
% Added in ability to open associated movie maker - RFB 06/2010
if (get(handles.OpenMovieMakerCheckbox, 'Value'))
mrmMakeMovieGUI(nextWindow);
end
return;
% --------------------------------------------------------------------
function menuFileLoadMRD_Callback(hObject, eventdata, handles)
% Read a Matlab file containing a mrDiffusion mrMesh data set. Then
% display the data.
% This should contain information about previously loaded data. Here we
% store the new file information in uData. --- Or we should ... not yet
% implemented.
uData = get(hObject,'userdata');
% Locate the file
persistent mrdPath;
persistent lastMshID;
curPath = pwd;
if(isempty(mrdPath) || isequal(mrdPath,0)), mrdPath = curPath; end
chdir(mrdPath);
[f, mrdPath] = uigetfile({'*.mat'}, 'Load MRD mesh...');
chdir(curPath);
if(isnumeric(f)), disp('Load Mesh (MRD) cancelled.'); return; end
fname = fullfile(mrdPath, f);
% Load the Mesh File.
d = load(fname);
msh = d.handles.mrMesh;
if isempty(lastMshID), lastMshID = msh.id;
else
if msh.id == lastMshID
lastMshID = lastMshID + 1;
msh.id = lastMshID+1;
end
end
% Make sure the mrMesh server is running
if ~mrmCheckServer('localhost'), mrmStart(msh.id,msh.host); end
mrmSet(msh,'refresh');
% Create the window and insert the data
msh = dtiInitMrMeshWindow(msh);
dtiMrMeshAddROIs(d.handles,msh);
dtiMrMeshAddFGs(d.handles,msh);
dtiMrMeshAddImages(d.handles,msh,d.origin,d.xIm,d.yIm,d.zIm);
% Make sure the window number is part of the title. This way we can change the
% title later if we by an Edt | Set Window Title pull down. Probably we
% should keep track of all the loaded meshes and the window numbers.
[p,fname,e] = fileparts(f);
str = mrmSet(msh,'windowtitle',sprintf('%.0f %s',meshGet(msh,'id'),fname));
% Added in ability to open associated movie maker - RFB 06/2010
if (get(handles.OpenMovieMakerCheckbox, 'Value'))
mrmMakeMovieGUI(msh.id);
end
return;
% --------------------------------------------------------------------
function menuClose_Callback(hObject, eventdata, handles)
closereq;
return;
% --------------------------------------------------------------------
function menuQuit_Callback(hObject, eventdata, handles)
closereq;
return;
% --------------------------------------------------------------------
function menuEdit_Callback(hObject, eventdata, handles)
return;
% --------------------------------------------------------------------
function menuDelete_Callback(hObject, eventdata, handles)
return;
% --------------------------------------------------------------------
function menuHelp_Callback(hObject, eventdata, handles)
return;
% --------------------------------------------------------------------
function menuHelpGeneral_Callback(hObject, eventdata, handles)
% hObject handle to menuHelpGeneral (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
helpMessage = 'Use mrmViewer to view Mesh Files. Ordinarily these have been saved by mrVista''s 3D window viewer or mrDiffusion.';
hdl = mrMessage(helpMessage,'left',[0.7,0.85,0.15, 0.1]);
return
% --------------------------------------------------------------------
function menuHelpMovie_Callback(hObject, eventdata, handles)
% hObject handle to menuHelpMovie (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
doc('mrmMakeMovieGUI');
return
% --- Executes on button press in btnLoad.
function btnLoad_Callback(hObject, eventdata, handles)
menuLoad_Callback(hObject, eventdata, handles)
return;
% --- Executes on button press in btnLoadMRD.
function btnLoadMRD_Callback(hObject, eventdata, handles)
menuFileLoadMRD_Callback(hObject, eventdata, handles)
return;
% --------------------------------------------------------------------
function menuOriginOff_Callback(hObject, eventdata, handles)
msh.host = 'localhost';
msh.id = whichMeshWindow;
msh.actor = 32;
mrmSet(msh,'hidecursor')
return;
% --------------------------------------------------------------------
function id = whichMeshWindow
%
% This should be a check on uData values or something.
prompt={'Enter mesh window'};
def={'1'};
dlgTitle='Select mesh window';
lineNo=1;
answer=inputdlg(prompt,dlgTitle,lineNo,def);
if isempty(answer), id = [];
else id = str2num(answer{1});
end
return;
% --------------------------------------------------------------------
function menuEditWindowTitle_Callback(hObject, eventdata, handles)
% hObject handle to menuEditWindowTitle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
msh.host = 'localhost';
msh.id = whichMeshWindow;
dlgTitle='mrmViewer Edit|Title';
prompt={'Enter window title'};
lineNo=1;
def = {'Title'};
answer=inputdlg(prompt,dlgTitle,lineNo,def);
if isempty(answer), disp('User canceled.'); return;
else mrmSet(msh,'title',answer{1}); end
return;
|
github
|
andregouws/mrMeshPy-master
|
mrmGet.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmGet.m
| 9,887 |
utf_8
|
e8dd0d99fd2d7c23b47d0386a3f73bb4
|
function val = mrmGet(msh,param,varargin)
% Communicate parameter values with a mrMesh window.
%
% val = mrmGet(msh,param,varargin)
%
% The general object mesh, typically a brain surface, contains various
% important parameters. These include the identity of the host computer
% running the mrMesh server (usually 'localhost') the number of the mrMesh
% window the Actor (i.e., object) within the window
%
% Actor values [0,31] are reserved with camera (0), cursor (1). New meshes
% and lights are assigned an actor value of 32 and above.
%
% The values in the mesh structure are accessed through the meshGet routine.
% The same mesh structure is used by mrMesh, mrGray and mrFlatMesh. Hence,
% the mesh interface routines are kept in mrLoadRet-3.0\mrMesh\.
%
% Some parameters require additional specification. These can be passed as
% additional arguments that are parsed by the varargin mechanism.
%
% See also: mrmSet, mrMesh, meshGet, meshSet
%
% Examples:
% l = mrmGet(msh,'listOfActors');
% cRot = mrmGet(msh,'camerarotation');
% bColor = mrmGet(msh,'background');
% d = mrmGet(msh,'data');
%
% BW (c) Copyright Stanford VISTASOFT Team
% Programming Notes
% * See mrmSet TODO List.
% * Because mesh is a Matlab command, use the variable
% name msh for the mesh parameter.
%
%% Default parameters
if ieNotDefined('msh'), error('You must specify a mesh.'); end
val = [];
host = meshGet(msh,'host');
if isempty(host), host = 'localhost'; end
windowID = meshGet(msh,'window id');
if isempty(windowID)|| windowID == -1, error('Mesh must specify a window'); end
%%
param = mrvParamFormat(param);
switch lower(param)
case 'help'
% Help command doesn't seem to return anything into val
% [tmp,foo,val] = mrMesh(host,windowID,'help');
help mrMesh
case {'actordata','data','meshdata','alldata'}
% If actorID is specified we only need msh.host and msh.windowID specified.
% val = mrmGet(msh,'meshdata',actorID)
% val = mrmGet(msh,'meshdata')
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_all = 1;
% p.actor = actorCheck(msh);
[tmp,status,val] = mrMesh(host,windowID,'get',p); %#ok<*ASGLU>
if status < 0, val = []; end
case {'meshvertices','vertices'}
% val = mrmGet(msh,'meshvertices',actorID)
% val = mrmGet(msh,'meshvertices')
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_vertices = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
if isempty(v)
warning('No vertices returned');
else
val = v.vertices;
end
case {'meshtriangles','triangles'}
% val = mrmGet(msh,'meshtriangles',actorID)
% val = mrmGet(msh,'meshtriangles')
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_triangles = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
val = v.triangles;
case {'normals','meshnormals'}
% val = mrmGet(msh,'mesh normals',actorID)
% val = mrmGet(msh,'mesh normals');
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_normals = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
val = v.normals;
case {'actorrotation','rotation'}
% val = mrmGet(msh,'actorrotation',actorID)
% val = mrmGet(msh,'actorrotation')
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_rotation = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
val = v.rotation;
case {'actororigin','origin'}
% val = mrmGet(msh,'actororigin',actorID)
% val = mrmGet(msh,'actororigin')
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_origin = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
val = v.origin;
case {'actorcolors','colors','coloroverlay'}
% val = mrmGet(msh,'actorcolors',actorID)
% coloroverlay = mrmGet(msh,'actorcolors');
if isempty(varargin), p.actor = actorCheck(msh);
else p.actor = varargin{1}; end
p.get_colors = 1;
[tmp,foo,v] = mrMesh(host,windowID,'get',p);
% Should we return RGBalpha, or RGB?
val = v.colors;
case {'getactorproperties','getall'}
% val = mrmGet(msh,param,actorNumber)
if length(varargin) < 1, error('Actor number required.'); end
p.actor = varargin{1};
p.get_all = 1;
[tmp,foo,val] = mrMesh(host,windowID,'get',p);
case {'allactors','actorlist','listofactors'}
% val = mrmGet(msh,'actor list');
%
% The camera is always actor 0. We don't returning that in this
% list. The cursor appears to be 2-4?
% We assume lights and objects are in the actors range 32-64
% We should probably have a different range for images, say 16-31?
% Or 65-96? We can also decode which is which by the returned
% values. So, mesh parameters have
%
% We test using the origin because lights and objects have an origin
% and it is a small transfer.
%
p.get_origin = 1;
for ii=1:10;
p.actor = ii;
[s,s(ii)] = mrMesh('localhost',windowID,'get',p);
end
systemList = find(s == 1);
for ii=1:32;
p.actor = ii+31;
[s,o(ii)] = mrMesh('localhost',windowID,'get',p);
end
objectList = find(o == 1); objectList = objectList + 31;
val.objectList = objectList; % Lights and Meshes are here
val.systemList = systemList; % Camera and origin lines are here (I think).
case {'camera','camera_all','cameraall'}
p.actor = 0;
p.get_all = 1;
[tmp,foo,res] = mrMesh(host,windowID,'get',p);
val = res;
case 'camerarotation'
p.get_rotation = 1;
p.actor = 0;
[tmp,foo,res] = mrMesh(host,windowID,'get',p);
val = res.rotation;
case 'cameraorigin'
% val = mrmGet(msh,'cameraorigin');
p.actor = 0;
p.get_origin = 1;
[tmp,foo,res] = mrMesh(host,windowID,'get',p);
val = res.origin;
case 'cameraspace'
% val = mrmGet(msh,'cameraspace');
p.actor = 0;
p.get_camera_space = 1;
[tmp,foo,res] = mrMesh(host,windowID,'get',p);
val = res.camera_space;
case 'background' % doesn't seem to work?
[tmp,foo,val] = mrMesh(host,windowID,'get_background');
case 'screenshot'
% ras 05/2007: somehow, I get the back-buffer which is not
% updated (a previous mesh image, not the current screenshot).
% I'm trying to insert a dummy command to update this buffer; hope
% it doesn't make this unwieldy. I will try to resolve the issue
% then come back and simplify this again.
mrMesh(host,windowID,'refresh');
p.filename = 'nosave';
[tmp,foo,v] = mrMesh(host,windowID,'screenshot',p);
val = permute(v.rgb, [2,1,3]);
case {'cursorposition','cursor'}
% val = mrmGet(msh,'cursor')
p.actor = 1;
% 2004.05.12 RFD: we now use new 'get_selection' command. This
% returns the vertex number and the actor number rather than 3d
% coords. In the end, this is the more appropriate thing to do.
%tmp.get_origin = 1;
%[id,stat,res] = mrMesh(host, windowID, 'get', tmp);
%val = res.origin - meshGet(msh,'origin');
%val = val([2,1,3]) ./ meshGet(msh,'mmPerVox');
%val = val([2,1,3]);
[id,stat,res] = mrMesh(host, windowID, 'get_selection', p);
% This is more 0,1 differences between C and Matlab
res.vertex = res.vertex+1;
if(res.actor == meshGet(msh,'actor'))
vert = meshGet(msh,'unsmoothedVertices');
val = vert(:,res.vertex)';
val = val([2,1,3]);
val = val ./ meshGet(msh,'mmPerVox');
else
val = res.position - meshGet(msh,'origin');
val = val([2,1,3]);
val = val ./ meshGet(msh,'mmPerVox');
end
case {'cursorvertex'}
p.actor = 1;
[id,stat,res] = mrMesh(host, windowID, 'get_selection', p);
if(res.actor == meshGet(msh,'actor'))
% The vertex numbering in mrMesh runs from [0,N-1]. In Matlab
% the vertices run from [1,N].
val = res.vertex + 1;
else
% not assigned to a vector, return -1
val = -1;
end
case {'cursorraw','cursorinvolume'}
% Warning: Remember that the vertex number returned by Dima is not
% the same vertex number (it is one less) than the one we use to
% list our vertices. We start from 1. He starts from 0.
p.actor = 1;
[id,stat,res] = mrMesh(host, windowID, 'get_selection', p);
val = res;
case {'curroi','roi'}
[id,stat,val] = mrMesh(host, windowID, 'get_cur_roi');
if(isfield(val,'vertices'))
val.vertices = val.vertices+1;
end
case {'meshsettings','settings','viewsettings','viewprefs'}
val = meshSettings(msh); % ras 03/06
otherwise
error('Unknown mrmMesh parameter');
end
return;
%----------------------
function actor = actorCheck(msh)
% We need to know which actor corresponds to this mesh. I wrote this
% routine rather than repeating the test throughout the code.
%
actor = meshGet(msh,'actor');
if isempty(actor)
error('meshGet(msh,''get'') requires an actor in the mesh structure.');
end
return;
|
github
|
andregouws/mrMeshPy-master
|
mrmMakeMovie.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmMakeMovie.m
| 2,415 |
utf_8
|
6a016c342fcc99acc4d928e88c9c3074
|
function mrmMakeMovie(id,rotBegin,rotEnd)
%
%
% Function to make a movie of brain rotating left to ventral view. This
% should really be a more general function, but this is a start.
%
% written by amr Jun 2010
%
if ~exist('id','var'), id = 500; end
if ~exist('rotBegin','var')
mrmRotateCamera(id,'left')
[rotBegin,zoom1] = mrmGetRotation(id);
end
if ~exist('rotEnd','var')
mrmRotateCamera(id,'bottom')
[rotEnd,zoom2] = mrmGetRotation(id);
end
%keyboard
% Set the background color
p.color=[0,0,0,1];
%p.color=[.3,.3,.3,1];
host = 'localhost';
%id = 174;
mrMesh(host, id, 'background', p);
% % rotate left to bottom
rotY = [rotBegin(2):-pi/128:rotEnd(2)];
rotZ = [rotBegin(3):pi/128:rotEnd(3)];
rotX = ones(1,length(rotY))*pi;
% rotate bottom to left
% rotY = [rotEnd(2):pi/64:rotBegin(2)];
% rotZ = [rotEnd(3):-pi/64:rotBegin(3)];
% rotX = ones(1,length(rotY))*pi;
n = length(rotX);
%pitch = linspace(.5*pi, 1.5*pi, n);
%pitch = -pi/2.5;
%zoom = 1;
movDir = '/biac3/wandell7/data/Words/Meshes/';
movFile = 'mrmRotateVentralToLeft.avi';
%mkdir('/tmp', 'mrmMovie');
clear M;
%for(ii=1:length(pitch))
f.filename = 'nosave';
for(ii=1:length(rotX))
mrmRotateCamera(id, [rotX(ii) rotY(ii) rotZ(ii)], zoom1);
[id,stat,res] = mrMesh(host, id, 'screenshot', f);
M((1-1)*length(rotX)+ii) = im2frame(permute(res.rgb, [2,1,3])./255);
%fname = sprintf('%c%0.2d.png', ltr(ii), jj);
%fname = fullfile(movDir, fname);
%imwrite(permute(res.rgb,[2,1,3])./255, fname);
end
%end
%figure; movie(M,-3)
movie2avi(M,fullfile(movDir,movFile)); %'/tmp/mrmMovieAllFrames.avi');
return
function [rot,zoom] = mrmGetRotation(id)
% Get rotation and zoom
p.actor=0; p.get_all=1;
[id,stat,r] = mrMesh('localhost', id, 'get', p);
zoom = diag(chol(r.rotation'*r.rotation))';
rotMat = r.rotation/diag(zoom);
% Note- there may be slight rounding errors allowing the inputs to
% asin/atan go outside of the range (-1,1). May want to clip those.
rot(2) = asin(rotMat(1,3));
if (abs(rot(2))-pi/2).^2 < 1e-9,
rot(1) = 0;
rot(3) = atan2(-rotMat(2,1), -rotMat(3,1)/rotMat(1,3));
else
c = cos(rot(2));
rot(1) = atan2(rotMat(2,3)/c, rotMat(3,3)/c);
rot(3) = atan2(rotMat(1,2)/c, rotMat(1,1)/c);
end
rot(1) = -rot(1); % flipped OpenGL Y-axis.
rot(3) = -rot(3);
fprintf('rot=[%0.6f %0.6f %0.6f];\nzoom=[%0.3f %0.3f %0.3f];\nfrustum=[%0.6f %0.6f %0.6f %0.6f];\n',rot,zoom,r.frustum);
return
|
github
|
andregouws/mrMeshPy-master
|
mrmMakeMovieGUI_Waypoint.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmMakeMovieGUI/mrmMakeMovieGUI_Waypoint.m
| 4,744 |
utf_8
|
29d4ffefd0edeea9b598da7c883a409a
|
function varargout = mrmMakeMovieGUI_Waypoint(varargin)
% MRMMAKEMOVIEGUI_WAYPOINT M-file for mrmMakeMovieGUI_Waypoint.fig
% MRMMAKEMOVIEGUI_WAYPOINT, by itself, creates a new MRMMAKEMOVIEGUI_WAYPOINT or raises the existing
% singleton*.
%
% H = MRMMAKEMOVIEGUI_WAYPOINT returns the handle to a new MRMMAKEMOVIEGUI_WAYPOINT or the handle to
% the existing singleton*.
%
% MRMMAKEMOVIEGUI_WAYPOINT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MRMMAKEMOVIEGUI_WAYPOINT.M with the given input arguments.
%
% MRMMAKEMOVIEGUI_WAYPOINT('Property','Value',...) creates a new MRMMAKEMOVIEGUI_WAYPOINT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before mrmMakeMovieGUI_Waypoint_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to mrmMakeMovieGUI_Waypoint_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help mrmMakeMovieGUI_Waypoint
% Last Modified by GUIDE v2.5 29-Jun-2010 23:05:44
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mrmMakeMovieGUI_Waypoint_OpeningFcn, ...
'gui_OutputFcn', @mrmMakeMovieGUI_Waypoint_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
end
function mrmMakeMovieGUI_Waypoint_OpeningFcn(hObject, eventdata, handles, parentFigure, meshID, editData)
% Choose default command line output for mrmMakeMovieGUI_Waypoint
if (~exist('editData', 'var')), editData = []; end
handles.output = hObject;
handles.parent = parentFigure;
handles.meshID = meshID;
handles.editData = editData;
% Update handles structure
guidata(hObject, handles);
Waypoint_InitFcn(hObject, handles);
end
function Waypoint_InitFcn(hObject, handles)
set(handles.ViewJumpMenu, 'String', {'Front','Back','Left','Right','Bottom','Top'});
if (~isempty(handles.editData))
editData = handles.editData;
set(handles.WaypointAddButton, 'String', 'Update');
set(handles.WaypointLabelTextField, 'String', editData.label);
end
guidata(hObject, handles);
end
function varargout = mrmMakeMovieGUI_Waypoint_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
end
function WaypointAddButton_Callback(hObject, eventdata, handles)
[rotation frustum origin] = mrmGetRotation(handles.meshID);
waypoint.eventType = 'waypoint';
waypoint.rotation = rotation;
waypoint.frustum = frustum;
waypoint.origin = origin;
waypoint.label = get(handles.WaypointLabelTextField, 'String');
set(handles.parent, 'UserData', waypoint);
close(handles.figure1);
end
function ViewJumpMenu_Callback(hObject, eventdata, handles)
strings = get(handles.ViewJumpMenu, 'String');
index = get(handles.ViewJumpMenu, 'Value');
mrmRotateCamera(handles.meshID,strings{index})
end
function mrmMakeMovieGUI_Waypoint_DeleteFcn(hObject, eventdata, handles)
set(handles.parent, 'UserData', []);
end
function [rot, frustum, origin] = mrmGetRotation(id)
% Written by RFD? Copied from original mrmMakeMovieGUI
% Get rotation and zoom
p.actor=0; p.get_all=1;
[id,stat,r] = mrMesh('localhost', id, 'get', p);
zoom = diag(chol(r.rotation'*r.rotation))';
rotMat = r.rotation/diag(zoom);
% Note- there may be slight rounding errors allowing the inputs to
% asin/atan go outside of the range (-1,1). May want to clip those.
rot(2) = asin(rotMat(1,3));
if (abs(rot(2))-pi/2).^2 < 1e-9,
rot(1) = 0;
rot(3) = atan2(-rotMat(2,1), -rotMat(3,1)/rotMat(1,3));
else
c = cos(rot(2));
rot(1) = atan2(rotMat(2,3)/c, rotMat(3,3)/c);
rot(3) = atan2(rotMat(1,2)/c, rotMat(1,1)/c);
end
rot(1) = -rot(1); % flipped OpenGL Y-axis.
rot(3) = -rot(3); % ??? don't know why it's necessary
frustum = r.frustum;
origin = r.origin;
end
|
github
|
andregouws/mrMeshPy-master
|
mrmMakeMovieGUI_Transition.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmMakeMovieGUI/mrmMakeMovieGUI_Transition.m
| 4,452 |
utf_8
|
40a785eea9283100dd17a89bc98eac89
|
function varargout = mrmMakeMovieGUI_Transition(varargin)
% MRMMAKEMOVIEGUI_TRANSITION M-file for mrmMakeMovieGUI_Transition.fig
% MRMMAKEMOVIEGUI_TRANSITION, by itself, creates a new MRMMAKEMOVIEGUI_TRANSITION or raises the existing
% singleton*.
%
% H = MRMMAKEMOVIEGUI_TRANSITION returns the handle to a new MRMMAKEMOVIEGUI_TRANSITION or the handle to
% the existing singleton*.
%
% MRMMAKEMOVIEGUI_TRANSITION('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MRMMAKEMOVIEGUI_TRANSITION.M with the given input arguments.
%
% MRMMAKEMOVIEGUI_TRANSITION('Property','Value',...) creates a new MRMMAKEMOVIEGUI_TRANSITION or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before mrmMakeMovieGUI_Transition_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to mrmMakeMovieGUI_Transition_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help mrmMakeMovieGUI_Transition
% Last Modified by GUIDE v2.5 29-Jun-2010 23:04:34
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mrmMakeMovieGUI_Transition_OpeningFcn, ...
'gui_OutputFcn', @mrmMakeMovieGUI_Transition_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
end
function mrmMakeMovieGUI_Transition_OpeningFcn(hObject, eventdata, handles, parentFigure, editData)
% Choose default command line output for mrmMakeMovieGUI_Transition
if (~exist('editData', 'var')), editData = []; end
handles.output = hObject;
handles.parent = parentFigure;
handles.editData = editData;
% Update handles structure
guidata(hObject, handles);
Transition_InitFcn(hObject, handles);
end
function Transition_InitFcn(hObject, handles)
strings = {'+', 'FIX', '-'};
set(handles.RotateXMenu, 'String', strings);
set(handles.RotateYMenu, 'String', strings);
set(handles.RotateZMenu, 'String', strings);
if (~isempty(handles.editData))
editData = handles.editData;
set(handles.TransitionAddButton, 'String', 'Update');
ind = cellfind(strings, editData.rotate{1});
set(handles.RotateXMenu, 'Value', ind);
ind = cellfind(strings, editData.rotate{2});
set(handles.RotateYMenu, 'Value', ind);
ind = cellfind(strings, editData.rotate{3});
set(handles.RotateZMenu, 'Value', ind);
set(handles.FrameCountTextField, 'String', num2str(editData.frames));
set(handles.TransitionLabelTextField, 'String', editData.label);
end
guidata(hObject, handles);
end
function varargout = mrmMakeMovieGUI_Transition_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
end
function TransitionAddButton_Callback(hObject, eventdata, handles)
frames = get(handles.FrameCountTextField, 'String');
if (isempty(frames))
errordlg('Please specify a frame count.');
return;
end
strings = {'+', 'FIX', '-'};
transition.eventType = 'transition';
transition.rotate = cell(1,3);
transition.rotate{1} = strings{get(handles.RotateXMenu, 'Value')};
transition.rotate{2} = strings{get(handles.RotateYMenu, 'Value')};
transition.rotate{3} = strings{get(handles.RotateZMenu, 'Value')};
transition.frames = str2num(frames);
transition.label = get(handles.TransitionLabelTextField, 'String');
set(handles.parent, 'UserData', transition);
close(handles.figure1);
end
function mrmMakeMovieGUI_Transition_DeleteFcn(hObject, eventdata, handles)
set(handles.parent, 'UserData', []);
end
|
github
|
andregouws/mrMeshPy-master
|
mrmMakeMovieGUI.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmMakeMovieGUI/mrmMakeMovieGUI.m
| 22,903 |
utf_8
|
fc4be7c7cb86bd358de9c6648a54e8e7
|
function varargout = mrmMakeMovieGUI(varargin)
% mrmMakeMovieGUI(meshID)
% Given a mesh ID #, opens a GUI allowing you to set up a series of
% events to be displayed in a .avi file.
%
% Events consist of waypoints, transitions, and pauses. All pauses must
% follow waypoints. Transitions must appear with waypoints on either
% side. Move the mesh manually to find the desired waypoint location, or
% use the presets.
%
% Usage:
% mrmMakeMovieGUI(meshID);
%
% Known issues:
% Jump to view isn't accurate with diffusion meshes for whatever reason.
% Probably need to edit mrmRotateCamera and add a conditional for when
% we're rotating such meshes, providing different coordinates (should
% they be consistent across diffusion meshes).
%
% [[email protected] 2010]
%
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mrmMakeMovieGUI_OpeningFcn, ...
'gui_OutputFcn', @mrmMakeMovieGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
end
function mrmMakeMovieGUI_OpeningFcn(hObject, eventdata, handles, meshID)
if (~exist('meshID', 'var')), meshID = []; end
% Choose default command line output for mrmMakeMovieGUI
handles.output = hObject;
handles.meshID = meshID;
handles.events = {};
handles.isSaved = true;
handles.filename = [];
handles.filedir = [];
handles.clipboard = [];
handles.index = 0;
set(handles.EventTypeMenu, 'String', {'Waypoint', 'Transition', 'Pause'});
% Update handles structure
handles = UpdateFileStatus(handles, true);
guidata(hObject, handles);
end
function varargout = mrmMakeMovieGUI_OutputFcn(hObject, eventdata, handles)
if (isempty(handles.meshID))
fprintf(1, 'No mesh ID # specified - closing GUI.\n');
close(handles.MakeMovieGUI);
end
end
function handles = TurnOffInvalidButtons(handles)
if (isempty(handles.clipboard))
enablePaste = 'off';
else
enablePaste = 'on';
end
if (length(handles.events) < 1)
enableEventDependent = 'off';
else
enableEventDependent = 'on';
end
% Paste buttons
set(handles.EventMenu_Paste, 'Enable', enablePaste);
set(handles.EventContextMenu_Paste, 'Enable', enablePaste);
% Buttons dependent on existence of events
set(handles.ExportButton, 'Enable', enableEventDependent);
set(handles.EditEventButton, 'Enable', enableEventDependent);
set(handles.PreviewButton, 'Enable', enableEventDependent);
set(handles.DeleteEventButton, 'Enable', enableEventDependent);
set(handles.MoveDownButton, 'Enable', enableEventDependent);
set(handles.MoveUpButton, 'Enable', enableEventDependent);
set(handles.MovieMenu_Export, 'Enable', enableEventDependent);
set(handles.MovieMenu_Preview, 'Enable', enableEventDependent);
set(handles.EventMenu_Delete, 'Enable', enableEventDependent);
set(handles.EventMenu_Edit, 'Enable', enableEventDependent);
set(handles.EventMenu_Copy, 'Enable', enableEventDependent);
set(handles.EventMenu_Cut, 'Enable', enableEventDependent);
set(handles.EventContextMenu_Delete, 'Enable', enableEventDependent);
set(handles.EventContextMenu_Edit, 'Enable', enableEventDependent);
set(handles.EventContextMenu_Copy, 'Enable', enableEventDependent);
set(handles.EventContextMenu_Cut, 'Enable', enableEventDependent);
set(handles.FileMenu_SaveAs, 'Enable', enableEventDependent);
set(handles.FileMenu_Save, 'Enable', enableEventDependent);
end
function handles = UpdateFileStatus(handles, saving)
if (~isempty(handles.filename))
if (saving)
handles.isSaved = true;
set(handles.FilenameText, 'String', handles.filename);
else
handles.isSaved = false;
set(handles.FilenameText, 'String', [handles.filename '*']);
end
else
if (saving)
handles.isSaved = true;
else
handles.isSaved = false;
end
set(handles.FilenameText, 'String', 'No save file.');
end
handles = TurnOffInvalidButtons(handles);
end
function EventList_Callback(hObject, eventdata, handles)
if (length(handles.events) < 1), return; end
index = get(handles.EventList, 'Value');
event = handles.events{index};
if (strcmp(event.eventType,'waypoint'))
mrmRotateCamera(handles.meshID, event.rotation, [], event.frustum, [], event.origin);
end
end
function MoveUpButton_Callback(hObject, eventdata, handles)
index = get(handles.EventList, 'Value');
ExchangeEvents(hObject, handles, index, index - 1);
end
function MoveDownButton_Callback(hObject, eventdata, handles)
index = get(handles.EventList, 'Value');
ExchangeEvents(hObject, handles, index, index + 1);
end
function ExchangeEvents(hObject, handles, selected, exchanged)
strings = get(handles.EventList, 'String');
if ((exchanged > length(strings)) || exchanged < 1), return; end
tmpString = strings{exchanged};
strings{exchanged} = strings{selected};
strings{selected} = tmpString;
tmpEvent = handles.events{exchanged};
handles.events{exchanged} = handles.events{selected};
handles.events{selected} = tmpEvent;
selected = exchanged;
set(handles.EventList, 'String', strings);
set(handles.EventList, 'Value', selected);
handles = UpdateFileStatus(handles, false);
guidata(hObject, handles);
end
function AddEvent_Callback(hObject, eventdata, handles, eventType, doInsert)
% Navigating around a godawful bug with single selection GUIs
if (length(handles.events) < 1), set(handles.EventList, 'Value', 1); end
% Get event type from drop down if it's not specified
if (~exist('eventType', 'var') || isempty(eventType))
eventTypes = get(handles.EventTypeMenu, 'String');
eventType = eventTypes{get(handles.EventTypeMenu, 'Value')};
end
% Ship off task of getting parameters about event to smaller GUIs
switch lower(eventType)
case 'waypoint'
waitfor(mrmMakeMovieGUI_Waypoint(handles.MakeMovieGUI, handles.meshID));
case 'transition'
waitfor(mrmMakeMovieGUI_Transition(handles.MakeMovieGUI));
case 'pause'
waitfor(mrmMakeMovieGUI_Pause(handles.MakeMovieGUI));
otherwise
fprintf(1, 'Unrecognized radio button selected.\n');
end
% Get data back from the GUIs, if any
data = get(handles.MakeMovieGUI, 'UserData'); % Get the data back from the pop up
if (isempty(data)), return; end % We're done if there are no params
% If we're not inserting, tack it after current selection
numEvents = length(handles.events);
if (~exist('doInsert', 'var') || isempty(doInsert) || (numEvents < 1))
index = numEvents + 1;
else
index = get(handles.EventList, 'Value') + 1;
end
handles = InsertEvent(hObject, handles, data, index);
set(handles.MakeMovieGUI, 'UserData', []); % Done with the GUI data, clear it
guidata(hObject, handles);
end
function handles = InsertEvent(hObject, handles, event, position)
% Insert event into visible list and storage array at specified position
handles.events = CellInsert(handles.events, event, position);
strings = get(handles.EventList, 'String');
strings = CellInsert(strings, GetListString(event), position);
set(handles.EventList, 'Value', position);
set(handles.EventList, 'String', strings);
handles = UpdateFileStatus(handles, false);
end
function cells = CellInsert(cells, value, index)
% Insert a value into a cell, shifting over the values in its place if
% necessary
numCells = length(cells);
if (numCells >= index)
for i = numCells:-1:index
cells{i+1} = cells{i};
end
end
cells{index} = value;
end
function listString = GetListString(data)
switch (data.eventType)
case 'waypoint'
string = '[WAYPOINT]';
case 'transition'
string = '[TRANSITION]';
case 'pause'
string = '[PAUSE]';
otherwise
fprintf(1, 'Unrecognized event type ''%s''', data.eventType);
listString = [];
return;
end
listString = sprintf('%s %s', string, data.label);
end
function DeleteEvent_Callback(hObject, eventdata, handles)
index = get(handles.EventList, 'Value');
strings = get(handles.EventList, 'String');
strings{index} = [];
handles.events{index} = [];
strings = cellRemoveEmpty(strings);
handles.events = cellRemoveEmpty(handles.events);
set(handles.EventList, 'String', strings);
numEvents = length(handles.events);
if (numEvents == 0)
index = 1;
else
if (index > numEvents)
index = numEvents;
end
end
set(handles.EventList, 'Value', index);
handles = UpdateFileStatus(handles, false);
guidata(hObject, handles);
end
function frames = CountFrames(events)
frames = 0;
numEvents = length(events);
for i = 1:numEvents
event = events{i};
if (isfield(event, 'frames'))
frames = frames + event.frames;
end
end
end
function RenderMovie_Callback(hObject, eventdata, handles, preview)
if (AreEventsWellFormed(handles))
frames = CountFrames(handles.events);
framesPerSec = str2num(get(handles.FPSTextField, 'String'));
events = handles.events;
nEvents = length(events);
lastWaypoint = [];
if (~preview) % Set up for saving out movie
[movFile, movDir] = uiputfile('brainMovie.avi');
if (movFile == 0), return; end
host = 'localhost';
f.filename = 'nosave';
frame = 1;
ShowProgress(handles, movFile, 0);
% Skipping preallocation of M, will do so if it's too slow
end
for i = 1:nEvents
event = handles.events{i};
switch (event.eventType)
case 'transition'
[rotation frustum origin] = BuildTransition(event, lastWaypoint, GetNextWaypoint(events, i));
for j = 1:event.frames
mrmRotateCamera(handles.meshID, rotation(j, :), [], frustum(j, :), [], origin(j, :));
if (~preview)
[id,stat,res] = mrMesh(host, handles.meshID, 'screenshot', f);
ShowProgress(handles, movFile, frame/frames * 100);
M(frame) = im2frame(permute(res.rgb, [2,1,3])./255);
frame = frame + 1;
end
end
case 'waypoint'
lastWaypoint = event;
mrmRotateCamera(handles.meshID, event.rotation, [], event.frustum, [], event.origin);
case 'pause'
if (preview)
pause(event.frames/framesPerSec);
else
[id,stat,res] = mrMesh(host, handles.meshID, 'screenshot', f);
for j = 1:event.frames
ShowProgress(handles, movFile, frame/frames * 100);
M(frame) = im2frame(permute(res.rgb, [2,1,3])./255);
frame = frame + 1;
end
end
otherwise
fprintf(1, 'Unrecognized event type ''%s''', data.eventType);
return;
end
end
if (~preview)
if ispc
% Compressors for Windows are annoying. None works. Not
% sure if the others in doc movie2avi work.
movie2avi(M, fullfile(movDir,movFile), ...
'FPS', framesPerSec, ...
'Compression','RLE');
else
% Unix/Mac
movie2avi(M, fullfile(movDir,movFile), ...
'FPS', framesPerSec, ...
'Compression','None');
end
set(handles.ProgressText, 'String', []);
end
else
errordlg('Invalid events list. See wiki for guidelines.');
end
end
function ShowProgress(handles, filename, percent)
set(handles.ProgressText, 'String', sprintf('Exporting %s... %2.0f%%', filename, percent));
end
function [rotation frustum origin] = BuildTransition(transition, waypointStart, waypointEnd)
nFrames = transition.frames;
rotation = zeros(nFrames, 3);
rotStart = waypointStart.rotation;
rotEnd = waypointEnd.rotation;
for i = 1:3
if (rotEnd(i) == rotStart(i))
rotation(:, i) = rotStart(i);
continue;
end
switch (transition.rotate{i})
case '+'
if (rotEnd(i) < rotStart(i))
rotEnd(i) = pi + (pi + rotEnd(i));
end
case '-'
if (rotEnd(i) > rotStart(i))
rotEnd(i) = -pi - (pi - rotEnd(i));
end
case 'FIX'
rotation(:,i) = rotStart(i);
continue;
otherwise
fprintf(1, 'Unrecognized rotation direction ''%s''', transition.rotate{i});
end
if (rotEnd(i) == rotStart(i))
rotation(:, i) = rotStart(i);
continue;
end
delta = rotEnd(i) - rotStart(i);
rotation(:, i) = rotStart(i):(delta/(nFrames - 1)):rotEnd(i);
end
frustum = InterpolateFrames(waypointStart.frustum, waypointEnd.frustum, nFrames);
origin = InterpolateFrames(waypointStart.origin, waypointEnd.origin, nFrames);
end
function vector = InterpolateFrames(start, finish, nFrames)
nEntries = length(start);
vector = zeros(nFrames, nEntries);
for i = 1:nEntries
if (start(i) == finish(i))
vector(:,i) = start(i);
continue;
end
delta = finish(i) - start(i);
vector(:,i) = start(i):(delta/(nFrames - 1)):finish(i);
end
end
function waypoint = GetNextWaypoint(events, startInd)
waypoint = [];
for i = startInd:length(events)
if (strcmp(events{i}.eventType, 'waypoint'))
waypoint = events{i};
return;
end
end
end
function bool = AreEventsWellFormed(handles)
events = handles.events;
nEvents = length(events);
if (nEvents < 2) % Need at least 2 events (waypoint + pause) to proceed
bool = false;
return;
end
event = events{1};
if (~(strcmp(event.eventType, 'waypoint'))) % First event needs to be a waypoint
bool = false;
return;
end
balanceCounter = 0;
hasFrames = 0;
for i = 2:nEvents
event = events{i};
if (~hasFrames && (strcmp(event.eventType, 'pause') || strcmp(event.eventType, 'transition')))
hasFrames = 1;
end
if (strcmp(event.eventType, 'transition'))
if (balanceCounter), bool = false; return; end
balanceCounter = balanceCounter + 1;
elseif (strcmp(event.eventType, 'waypoint'))
if (~balanceCounter), continue; end
balanceCounter = balanceCounter - 1;
elseif (strcmp(event.eventType, 'pause'))
if (balanceCounter), bool = false; return; end
end
end
if (~hasFrames || balanceCounter), bool = false; return; end
bool = true;
end
function EditEvent_Callback(hObject, eventdata, handles)
events = handles.events;
nEvents = length(events);
if (nEvents < 1), return; end
selected = get(handles.EventList, 'Value');
editData = events{selected};
switch (editData.eventType)
case 'waypoint'
waitfor(mrmMakeMovieGUI_Waypoint(handles.MakeMovieGUI, handles.meshID, editData));
case 'transition'
waitfor(mrmMakeMovieGUI_Transition(handles.MakeMovieGUI, editData));
case 'pause'
waitfor(mrmMakeMovieGUI_Pause(handles.MakeMovieGUI, editData));
otherwise
fprintf(1, 'Unrecognized radio button selected.\n');
end
editData = get(handles.MakeMovieGUI, 'UserData');
if (isempty(editData)), return; end
handles.events{selected} = editData;
strings = get(handles.EventList, 'String');
strings{selected} = GetListString(editData);
set(handles.EventList, 'String', strings);
handles = UpdateFileStatus(handles, false);
set(handles.MakeMovieGUI, 'UserData', []); % Clear it out to not muck up future use of this var
guidata(hObject, handles);
end
function SaveData(handles)
if (~isempty(handles.filename))
fileID = 'EventsList';
version = 1;
events = handles.events;
save(fullfile(handles.filedir,handles.filename), 'fileID', 'version', 'events');
end
end
function SaveCheck(hObject, eventdata, handles)
if (~handles.isSaved)
buttonChosen = questdlg('Save changes?', 'MakeMovieGUI', 'Yes', 'No', 'Yes');
if (strcmp(buttonChosen,'Yes'))
Save_Callback(hObject, eventdata, handles);
end
end
end
function New_Callback(hObject, eventdata, handles)
SaveCheck(hObject, eventdata, handles);
handles.events = [];
set(handles.EventList, 'String', []);
set(handles.EventList, 'Value', 1);
handles.filename = [];
handles.filedir = [];
handles = UpdateFileStatus(handles, true);
guidata(hObject, handles);
end
function Open_Callback(hObject, eventdata, handles)
[filename filedir] = uigetfile('*.mat');
if (filename == 0), return; end
file = load(fullfile(filedir,filename));
if (strcmp(file.fileID, 'EventsList'))
if (file.version <= 1)
handles.filename = filename;
handles.filedir = filedir;
handles.events = {};
set(handles.EventList, 'String', []);
set(handles.EventList, 'Value', 1);
for i = 1:length(file.events)
handles = InsertEvent(hObject, handles, file.events{i}, i);
end
handles = UpdateFileStatus(handles, true);
guidata(hObject, handles);
else
errordlg('Incompatible eventsList file.');
end
else
errordlg('Corrupt/invalid eventsList file.');
end
end
function Save_Callback(hObject, eventdata, handles)
if (isempty(handles.filename))
SaveAs_Callback(hObject, eventdata, handles);
else
handles = UpdateFileStatus(handles, true);
SaveData(handles);
guidata(hObject, handles);
end
end
function SaveAs_Callback(hObject, eventdata, handles)
[filename, filedir] = uiputfile('brainMovie.mat');
if (filename == 0), return; end
handles.filename = filename;
handles.filedir = filedir;
handles = UpdateFileStatus(handles, true);
SaveData(handles);
guidata(hObject, handles);
end
function Quit_Callback(hObject, eventdata, handles)
SaveCheck(hObject, eventdata, handles);
close(handles.MakeMovieGUI);
end
function EventList_KeyPressFcn(hObject, eventdata, handles)
if (~isempty(cellfind(eventdata.Modifier, 'control')) || ...
~isempty(cellfind(eventdata.Modifier, 'command'))) % done to support mac as well as linux
switch (eventdata.Key)
case 'x'
CutEvent_Callback(hObject, eventdata, handles);
case 'c'
CopyEvent_Callback(hObject, eventdata, handles);
case 'v'
PasteEvent_Callback(hObject, eventdata, handles);
case 'm'
EditEvent_Callback(hObject, eventdata, handles);
case 'd'
DeleteEvent_Callback(hObject, eventdata, handles);
case 'n'
New_Callback(hObject, eventdata, handles);
case 'o'
Open_Callback(hObject, eventdata, handles);
case 's'
Save_Callback(hObject, eventdata, handles);
case 'q'
Quit_Callback(hObject, eventdata, handles);
case 'p'
RenderMovie_Callback(hObject, eventdata, handles, 1);
case 'e'
RenderMovie_Callback(hObject, eventdata, handles, 0);
otherwise
end
else
switch (eventdata.Key)
case 'a'
MoveUpButton_Callback(hObject, eventdata, handles);
case 'z'
MoveDownButton_Callback(hObject, eventdata, handles);
case 'delete'
DeleteEvent_Callback(hObject, eventdata, handles);
otherwise
end
end
end
function CutEvent_Callback(hObject, eventdata, handles)
if (length(handles.events) < 1), return; end
selected = get(handles.EventList, 'Value');
handles.clipboard = handles.events{selected};
DeleteEvent_Callback(hObject, eventdata, handles);
end
function CopyEvent_Callback(hObject, eventdata, handles)
if (length(handles.events) < 1), return; end
selected = get(handles.EventList, 'Value');
handles.clipboard = handles.events{selected};
handles = TurnOffInvalidButtons(handles);
guidata(hObject, handles);
end
function PasteEvent_Callback(hObject, eventdata, handles)
if (~isempty(handles.clipboard))
if (length(handles.events) < 1)
handles = InsertEvent(hObject, handles, handles.clipboard, 1);
else
selected = get(handles.EventList, 'Value');
handles = InsertEvent(hObject, handles, handles.clipboard, selected + 1);
end
guidata(hObject, handles);
end
end
|
github
|
andregouws/mrMeshPy-master
|
mrmMakeMovieGUI_Pause.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrm/mrmMakeMovieGUI/mrmMakeMovieGUI_Pause.m
| 3,455 |
utf_8
|
2bb67f063f553fbaefb2021090109889
|
function varargout = mrmMakeMovieGUI_Pause(varargin)
% MRMMAKEMOVIEGUI_PAUSE M-file for mrmMakeMovieGUI_Pause.fig
% MRMMAKEMOVIEGUI_PAUSE, by itself, creates a new MRMMAKEMOVIEGUI_PAUSE or raises the existing
% singleton*.
%
% H = MRMMAKEMOVIEGUI_PAUSE returns the handle to a new MRMMAKEMOVIEGUI_PAUSE or the handle to
% the existing singleton*.
%
% MRMMAKEMOVIEGUI_PAUSE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MRMMAKEMOVIEGUI_PAUSE.M with the given input arguments.
%
% MRMMAKEMOVIEGUI_PAUSE('Property','Value',...) creates a new MRMMAKEMOVIEGUI_PAUSE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before mrmMakeMovieGUI_Pause_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to mrmMakeMovieGUI_Pause_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help mrmMakeMovieGUI_Pause
% Last Modified by GUIDE v2.5 18-Jun-2010 20:12:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @mrmMakeMovieGUI_Pause_OpeningFcn, ...
'gui_OutputFcn', @mrmMakeMovieGUI_Pause_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
end
function mrmMakeMovieGUI_Pause_OpeningFcn(hObject, eventdata, handles, parentFigure, editData)
% Choose default command line output for mrmMakeMovieGUI_Pause
if (~exist('editData', 'var')), editData = []; end
handles.output = hObject;
handles.parent = parentFigure;
handles.editData = editData;
% Update handles structure
guidata(hObject, handles);
Pause_InitFcn(hObject, handles);
end
function Pause_InitFcn(hObject, handles)
if (~isempty(handles.editData))
editData = handles.editData;
set(handles.PauseAddButton, 'String', 'Update');
set(handles.FrameCountTextField, 'String', num2str(editData.frames));
set(handles.PauseLabelTextField, 'String', editData.label);
end
end
function varargout = mrmMakeMovieGUI_Pause_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
end
function PauseAddButton_Callback(hObject, eventdata, handles)
frames = get(handles.FrameCountTextField, 'String');
if (isempty(frames))
errordlg('Please specify a frame count.');
return;
end
pause.eventType = 'pause';
pause.frames = str2num(frames);
pause.label = get(handles.PauseLabelTextField, 'String');
set(handles.parent, 'UserData', pause);
close(handles.figure1);
end
function mrmMakeMovieGUI_Pause_DeleteFcn(hObject, eventdata, handles)
set(handles.parent, 'UserData', []);
end
|
github
|
andregouws/mrMeshPy-master
|
dtiSplitFourImages.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrDiffusion/dtiSplitFourImages.m
| 4,601 |
utf_8
|
aa0b90778b09e27998fda42d59bfe848
|
function [images,imOrigin] = dtiSplitFourImages(handles,xIm,yIm,zIm)
%
% [images,imOrigin1,imOrigin2,imOrigin3,imOrigin4] = ...
% dtiSplitFourImages(handles,xIm,yIm,zIm,imOrigin)
%
% Splits each of the images xIm, yIm, and zIm into four images stored in
% the images structure. This is done so that transparency could be
% correctly computed in mrMesh. The center point where the images are cut
% is the current position in dtiFiberUI.
%
% Inputs:
% - handles : current handles
% - xIm : image on the x plane
% - yIm : image on the y plane
% - zIm : image on the z plane
%
% Output:
% - images : structure containing the 12 images(xIm1,xIm2...)
% - imOrigin1,2,3,4 : origins of the new images. It is in a format that
% facilitates the call of dtiAddImages
%
% Written by : gb 10/24/2005 (Guillaume B.?)
%
% Stanford VISTA Team
% xform = dtiGet(handles,'curacpc2imgxform');
images = struct('xIm',[],'yIm',[],'zIm',[]);
imOrigin = cell(1,4);
imOrigin{1} = struct('x',[],'y',[],'z',[]);
imOrigin{2} = struct('x',[],'y',[],'z',[]);
imOrigin{3} = struct('x',[],'y',[],'z',[]);
imOrigin{4} = struct('x',[],'y',[],'z',[]);
sz = [size(zIm'); size(yIm); size(xIm')];
imSize = 2^ceil(log2(max(sz(:))));
imDims = dtiGet(1, 'defaultBoundingBox');
realCenter = dtiGet(handles, 'acpcpos');
center = floor(realCenter - imDims(1,:)) + 1;
center(center<1) = 1;
%center(center>
if ~isempty(xIm)
images.xIm{1} = dtiImagePad(xIm(1:floor(center(2)),1:floor(center(3))),0,imSize);
images.xIm{2} = dtiImagePad(xIm(1:floor(center(2)),floor(center(3)):end),1,imSize);
images.xIm{3} = dtiImagePad(xIm(floor(center(2)):end,floor(center(3)):end),2,imSize);
images.xIm{4} = dtiImagePad(xIm(floor(center(2)):end,1:floor(center(3))),3,imSize);
xOffset = [0 size(images.xIm{1})]/2;
imOrigin{1}.x = realCenter + [0 -xOffset(2) -xOffset(3)];
imOrigin{2}.x = realCenter + [0 -xOffset(2) +xOffset(3)];
imOrigin{3}.x = realCenter + [0 +xOffset(2) +xOffset(3)];
imOrigin{4}.x = realCenter + [0 +xOffset(2) -xOffset(3)];
end
if ~isempty(yIm)
images.yIm{1} = dtiImagePad(yIm(1:floor(center(1)),1:floor(center(3))),0,imSize);
images.yIm{2} = dtiImagePad(yIm(1:floor(center(1)),floor(center(3)):end),1,imSize);
images.yIm{3} = dtiImagePad(yIm(floor(center(1)):end,floor(center(3)):end),2,imSize);
images.yIm{4} = dtiImagePad(yIm(floor(center(1)):end,1:floor(center(3))),3,imSize);
yOffset = [size(images.yIm{1},1) 0 size(images.yIm{1},2)]/2;
imOrigin{1}.y = realCenter + [-yOffset(1) 0 -yOffset(3)];
imOrigin{2}.y = realCenter + [-yOffset(1) 0 +yOffset(3)];
imOrigin{3}.y = realCenter + [+yOffset(1) 0 +yOffset(3)];
imOrigin{4}.y = realCenter + [+yOffset(1) 0 -yOffset(3)];
end
if ~isempty(zIm)
images.zIm{1} = dtiImagePad(zIm(1:floor(center(2)),1:floor(center(1))),0,imSize);
images.zIm{2} = dtiImagePad(zIm(1:floor(center(2)),floor(center(1)):end),1,imSize);
images.zIm{3} = dtiImagePad(zIm(floor(center(2)):end,floor(center(1)):end),2,imSize);
images.zIm{4} = dtiImagePad(zIm(floor(center(2)):end,1:floor(center(1))),3,imSize);
zOffset = [size(images.zIm{1}) 0]/2;
imOrigin{1}.z = realCenter + [-zOffset(1) -zOffset(2) 0];
imOrigin{2}.z = realCenter - [-zOffset(1) +zOffset(2) 0];
imOrigin{3}.z = realCenter + [+zOffset(1) +zOffset(2) 0];
imOrigin{4}.z = realCenter - [+zOffset(1) -zOffset(2) 0];
end
if(0)% isunix
for(ii=1:4)
if(~isempty(images.xIm))
images.xIm{ii}(1,:)=0; images.xIm{ii}(end,:)=0; images.xIm{ii}(:,1)=0; images.xIm{ii}(:,end)=0;
end
if(~isempty(images.yIm))
images.yIm{ii}(1,:)=0; images.yIm{ii}(end,:)=0; images.yIm{ii}(:,1)=0; images.yIm{ii}(:,end)=0;
end
if(~isempty(images.zIm))
images.zIm{ii}(1,:)=0; images.zIm{ii}(end,:)=0; images.zIm{ii}(:,1)=0; images.zIm{ii}(:,end)=0;
end
end
end
return
% ---------------------------------------------------------------------- %
function [newImage] = dtiImagePad(image,nbCorner,imSize)
%
% function used to add a pad to the splitted images
%
sz = size(image);
newImage = zeros(imSize,imSize);
switch(nbCorner)
case 0
newImage(end - sz(1) + 1:end, end - sz(2) + 1:end) = image;
case 1
newImage(end - sz(1) + 1:end, 1:sz(2)) = image;
case 2
newImage(1:sz(1), 1:sz(2)) = image;
case 3
newImage(1:sz(1), end - sz(2) + 1:end) = image;
end
return
|
github
|
andregouws/mrMeshPy-master
|
dtiMrMeshOrigin.m
|
.m
|
mrMeshPy-master/legacy/mrMesh/mrDiffusion/dtiMrMeshOrigin.m
| 2,730 |
utf_8
|
f21f253f859590893778a3ad4ea15e07
|
function origin = dtiMrMeshOrigin(handles)
% Computes the (x,y,z) origin of the image plane data
%
% origin = dtiMrMeshOrigin(handles)
%
% NOTE: This routine was extracted from dtiMrMesh3AxisImage so we could
% build independent mrMesh outputs. I think it may be computing the origin
% of the quarter images from dtiSplit... routine.
%
% Authors: Wandell, Dougherty
%
% Stanford VISTA Team
curPosition = dtiGet(handles,'curpos');
[xImX,xImY,xImZ] = dtiMrMeshImageCoords(handles,1,curPosition(1));
[yImX,yImY,yImZ] = dtiMrMeshImageCoords(handles,2,curPosition(2));
[zImX,zImY,zImZ] = dtiMrMeshImageCoords(handles,3,curPosition(3));
% For x,y,z you place the current position into the relevant location and
% then for the other two you find the value that is zero (which is the
% mid-point of the coordinates and substract off half of the number
% coordinates. I don't understand why (BW).
origin.x = -[-curPosition(1), ...
find(xImY(:,1)==0) - length(xImY(:,1))/2, ...
find(xImZ(1,:)==0) - length(xImZ(1,:))/2];
origin.y = -[find(yImX(:,1)==0) - length(yImX(:,1))/2, ...
-curPosition(2), ...
find(yImZ(1,:)==0) - length(yImZ(1,:))/2];
origin.z = -[find(zImX(1,:)==0) - length(zImX(1,:))/2, ...
find(zImY(:,1)==0) - length(zImY(:,1))/2, ...
-curPosition(3)];
return;
%------------------------------------
function [x,y,z] = dtiMrMeshImageCoords(handles,sliceThisDim,sliceNum)
%
% [x,y,z] = dtiMrMeshImageCoords(handles,sliceThisDim,sliceNum);
%
% Produces an array of grid points that can be transformed in dtiGetSlice
% to image coords. They are used for interpolating values in dtGetSlice.
%
% This routine should be extracted and then called from dtGetSlice instead
% of the code that is there.
%
% Stanford VISTA Team
imDims = dtiGet(1, 'defaultBoundingBox');
nvals = max(imDims) - min(imDims) + 1;
% Computes a single integer for the desired slice, and two vectors showing
% the support of the other two. So, if you are in the x-slice, you get
% that number of the x-slide and two vectors showing the y and z
% coordinates.
if(sliceThisDim == 1), x = sliceNum;
else x = linspace(imDims(1,1),imDims(2,1),nvals(1));
end;
if(sliceThisDim == 2), y = sliceNum;
else y = linspace(imDims(1,2),imDims(2,2),nvals(2));
end;
if(sliceThisDim == 3), z = sliceNum;
else z = linspace(imDims(1,3),imDims(2,3),nvals(3));
end;
% Convert the single number and the two linear dimensions into 3 3D
% matrices that define the x,y,z coordinates at each anatomical point.
% The singleton dimension is all one value, and the other two 3D
% matrices combine
[x,y,z] = meshgrid(x,y,z);
% Squeeze out the singleton dimension.
x = squeeze(x);
y = squeeze(y);
z = squeeze(z);
return
|
github
|
winswang/comp_holo_video-master
|
TwIST.m
|
.m
|
comp_holo_video-master/3D/TwIST.m
| 22,842 |
utf_8
|
64ee75349f89f520998ec0d7afd15ac0
|
function [x,x_debias,objective,times,debias_start,mses,max_svd] = ...
TwIST(y,A,tau,varargin)
%
% Usage:
% [x,x_debias,objective,times,debias_start,mses] = TwIST(y,A,tau,varargin)
%
% This function solves the regularization problem
%
% arg min_x = 0.5*|| y - A x ||_2^2 + tau phi( x ),
%
% where A is a generic matrix and phi(.) is a regularizarion
% function such that the solution of the denoising problem
%
% Psi_tau(y) = arg min_x = 0.5*|| y - x ||_2^2 + tau \phi( x ),
%
% is known.
%
% For further details about the TwIST algorithm, see the paper:
%
% J. Bioucas-Dias and M. Figueiredo, "A New TwIST: Two-Step
% Iterative Shrinkage/Thresholding Algorithms for Image
% Restoration", IEEE Transactions on Image processing, 2007.
%
% and
%
% J. Bioucas-Dias and M. Figueiredo, "A Monotonic Two-Step
% Algorithm for Compressive Sensing and Other Ill-Posed
% Inverse Problems", submitted, 2007.
%
% Authors: Jose Bioucas-Dias and Mario Figueiredo, October, 2007.
%
% Please check for the latest version of the code and papers at
% www.lx.it.pt/~bioucas/TwIST
%
% -----------------------------------------------------------------------
% Copyright (2007): Jose Bioucas-Dias and Mario Figueiredo
%
% TwIST is distributed under the terms of
% the GNU General Public License 2.0.
%
% Permission to use, copy, modify, and distribute this software for
% any purpose without fee is hereby granted, provided that this entire
% notice is included in all copies of any software which is or includes
% a copy or modification of this software and in all copies of the
% supporting documentation for such software.
% This software is being provided "as is", without any express or
% implied warranty. In particular, the authors do not make any
% representation or warranty of any kind concerning the merchantability
% of this software or its fitness for any particular purpose."
% ----------------------------------------------------------------------
%
% ===== Required inputs =============
%
% y: 1D vector or 2D array (image) of observations
%
% A: if y and x are both 1D vectors, A can be a
% k*n (where k is the size of y and n the size of x)
% matrix or a handle to a function that computes
% products of the form A*v, for some vector v.
% In any other case (if y and/or x are 2D arrays),
% A has to be passed as a handle to a function which computes
% products of the form A*x; another handle to a function
% AT which computes products of the form A'*x is also required
% in this case. The size of x is determined as the size
% of the result of applying AT.
%
% tau: regularization parameter, usually a non-negative real
% parameter of the objective function (see above).
%
%
% ===== Optional inputs =============
%
% 'Psi' = denoising function handle; handle to denoising function
% Default = soft threshold.
%
% 'Phi' = function handle to regularizer needed to compute the objective
% function.
% Default = ||x||_1
%
% 'lambda' = lam1 parameters of the TwIST algorithm:
% Optimal choice: lam1 = min eigenvalue of A'*A.
% If min eigenvalue of A'*A == 0, or unknwon,
% set lam1 to a value much smaller than 1.
%
% Rule of Thumb:
% lam1=1e-4 for severyly ill-conditioned problems
% lam1=1e-2 for mildly ill-conditioned problems
% lam1=1 for A unitary direct operators
%
% Default: lam1 = 0.04.
%
% Important Note: If (max eigenvalue of A'*A) > 1,
% the algorithm may diverge. This is be avoided
% by taking one of the follwoing measures:
%
% 1) Set 'Monontone' = 1 (default)
%
% 2) Solve the equivalenve minimization problem
%
% min_x = 0.5*|| (y/c) - (A/c) x ||_2^2 + (tau/c^2) \phi( x ),
%
% where c > 0 ensures that max eigenvalue of (A'A/c^2) <= 1.
%
% 'alpha' = parameter alpha of TwIST (see ex. (22) of the paper)
% Default alpha = alpha(lamN=1, lam1)
%
% 'beta' = parameter beta of twist (see ex. (23) of the paper)
% Default beta = beta(lamN=1, lam1)
%
% 'AT' = function handle for the function that implements
% the multiplication by the conjugate of A, when A
% is a function handle.
% If A is an array, AT is ignored.
%
% 'StopCriterion' = type of stopping criterion to use
% 0 = algorithm stops when the relative
% change in the number of non-zero
% components of the estimate falls
% below 'ToleranceA'
% 1 = stop when the relative
% change in the objective function
% falls below 'ToleranceA'
% 2 = stop when the relative norm of the difference between
% two consecutive estimates falls below toleranceA
% 3 = stop when the objective function
% becomes equal or less than toleranceA.
% Default = 1.
%
% 'ToleranceA' = stopping threshold; Default = 0.01
%
% 'Debias' = debiasing option: 1 = yes, 0 = no.
% Default = 0.
%
% Note: Debiasing is an operation aimed at the
% computing the solution of the LS problem
%
% arg min_x = 0.5*|| y - A' x' ||_2^2
%
% where A' is the submatrix of A obatained by
% deleting the columns of A corresponding of components
% of x set to zero by the TwIST algorithm
%
%
% 'ToleranceD' = stopping threshold for the debiasing phase:
% Default = 0.0001.
% If no debiasing takes place, this parameter,
% if present, is ignored.
%
% 'MaxiterA' = maximum number of iterations allowed in the
% main phase of the algorithm.
% Default = 1000
%
% 'MiniterA' = minimum number of iterations performed in the
% main phase of the algorithm.
% Default = 5
%
% 'MaxiterD' = maximum number of iterations allowed in the
% debising phase of the algorithm.
% Default = 200
%
% 'MiniterD' = minimum number of iterations to perform in the
% debiasing phase of the algorithm.
% Default = 5
%
% 'Initialization' must be one of {0,1,2,array}
% 0 -> Initialization at zero.
% 1 -> Random initialization.
% 2 -> initialization with A'*y.
% array -> initialization provided by the user.
% Default = 0;
%
% 'Monotone' = enforce monotonic decrease in f.
% any nonzero -> enforce monotonicity
% 0 -> don't enforce monotonicity.
% Default = 1;
%
% 'Sparse' = {0,1} accelarates the convergence rate when the regularizer
% Phi(x) is sparse inducing, such as ||x||_1.
% Default = 1
%
%
% 'True_x' = if the true underlying x is passed in
% this argument, MSE evolution is computed
%
%
% 'Verbose' = work silently (0) or verbosely (1)
%
% ===================================================
% ============ Outputs ==============================
% x = solution of the main algorithm
%
% x_debias = solution after the debiasing phase;
% if no debiasing phase took place, this
% variable is empty, x_debias = [].
%
% objective = sequence of values of the objective function
%
% times = CPU time after each iteration
%
% debias_start = iteration number at which the debiasing
% phase started. If no debiasing took place,
% this variable is returned as zero.
%
% mses = sequence of MSE values, with respect to True_x,
% if it was given; if it was not given, mses is empty,
% mses = [].
%
% max_svd = inverse of the scaling factor, determined by TwIST,
% applied to the direct operator (A/max_svd) such that
% every IST step is increasing.
% ========================================================
%--------------------------------------------------------------
% test for number of required parametres
%--------------------------------------------------------------
if (nargin-length(varargin)) ~= 3
error('Wrong number of required parameters');
end
%--------------------------------------------------------------
% Set the defaults for the optional parameters
%--------------------------------------------------------------
stopCriterion = 1;
tolA = 0.01;
debias = 0;
maxiter = 1000;
maxiter_debias = 200;
miniter = 5;
miniter_debias = 5;
init = 0;
enforceMonotone = 1;
compute_mse = 0;
plot_ISNR = 0;
AT = 0;
verbose = 1;
alpha = 0;
beta = 0;
sparse = 1;
tolD = 0.001;
phi_l1 = 0;
psi_ok = 0;
% default eigenvalues
lam1=1e-4; lamN=1;
%
% constants ans internal variables
for_ever = 1;
% maj_max_sv: majorizer for the maximum singular value of operator A
max_svd = 1;
% Set the defaults for outputs that may not be computed
debias_start = 0;
x_debias = [];
mses = [];
%--------------------------------------------------------------
% Read the optional parameters
%--------------------------------------------------------------
if (rem(length(varargin),2)==1)
error('Optional parameters should always go by pairs');
else
for i=1:2:(length(varargin)-1)
switch upper(varargin{i})
case 'LAMBDA'
lam1 = varargin{i+1};
case 'ALPHA'
alpha = varargin{i+1};
case 'BETA'
beta = varargin{i+1};
case 'PSI'
psi_function = varargin{i+1};
case 'PHI'
phi_function = varargin{i+1};
case 'STOPCRITERION'
stopCriterion = varargin{i+1};
case 'TOLERANCEA'
tolA = varargin{i+1};
case 'TOLERANCED'
tolD = varargin{i+1};
case 'DEBIAS'
debias = varargin{i+1};
case 'MAXITERA'
maxiter = varargin{i+1};
case 'MAXIRERD'
maxiter_debias = varargin{i+1};
case 'MINITERA'
miniter = varargin{i+1};
case 'MINITERD'
miniter_debias = varargin{i+1};
case 'INITIALIZATION'
if prod(size(varargin{i+1})) > 1 % we have an initial x
init = 33333; % some flag to be used below
x = varargin{i+1};
else
init = varargin{i+1};
end
case 'MONOTONE'
enforceMonotone = varargin{i+1};
case 'SPARSE'
sparse = varargin{i+1};
case 'TRUE_X'
compute_mse = 1;
true = varargin{i+1};
size(true)
size(y)
if prod(double((size(true) == size(y))))
plot_ISNR = 1;
end
case 'AT'
AT = varargin{i+1};
case 'VERBOSE'
verbose = varargin{i+1};
otherwise
% Hmmm, something wrong with the parameter string
error(['Unrecognized option: ''' varargin{i} '''']);
end;
end;
end
%%%%%%%%%%%%%%
% twist parameters
rho0 = (1-lam1/lamN)/(1+lam1/lamN);
if alpha == 0
alpha = 2/(1+sqrt(1-rho0^2));
end
if beta == 0
beta = alpha*2/(lam1+lamN);
end
if (sum(stopCriterion == [0 1 2 3])==0)
error(['Unknwon stopping criterion']);
end
% if A is a function handle, we have to check presence of AT,
if isa(A, 'function_handle') & ~isa(AT,'function_handle')
error(['The function handle for transpose of A is missing']);
end
% if A is a matrix, we find out dimensions of y and x,
% and create function handles for multiplication by A and A',
% so that the code below doesn't have to distinguish between
% the handle/not-handle cases
if ~isa(A, 'function_handle')
AT = @(x) reshape(A'*x(:),[64 64]);
A = @(x) reshape(A*x(:),[size(y,1) size(y,2)]);
end
% from this point down, A and AT are always function handles.
% Precompute A'*y since it'll be used a lot
Aty = AT(y);
% psi_function(Aty,tau)
% if phi was given, check to see if it is a handle and that it
% accepts two arguments
if exist('psi_function','var')
if isa(psi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = psi_function(Aty,tau);
psi_ok = 1;
catch
error(['Something is wrong with function handle for psi'])
end
else
error(['Psi does not seem to be a valid function handle']);
end
else %if nothing was given, use soft thresholding
psi_function = @(x,tau) soft(x,tau);
end
% if psi exists, phi must also exist
if (psi_ok == 1)
if exist('phi_function','var')
if isa(phi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = phi_function(Aty);
catch
error(['Something is wrong with function handle for phi'])
end
else
error(['Phi does not seem to be a valid function handle']);
end
else
error(['If you give Psi you must also give Phi']);
end
else % if no psi and phi were given, simply use the l1 norm.
phi_function = @(x) sum(abs(x(:)));
phi_l1 = 1;
end
%--------------------------------------------------------------
% Initialization
%--------------------------------------------------------------
switch init
case 0 % initialize at zero, using AT to find the size of x
x = AT(zeros(size(y)));
case 1 % initialize randomly, using AT to find the size of x
x = randn(size(AT(zeros(size(y)))));
case 2 % initialize x0 = A'*y
x = Aty;
case 33333
% initial x was given as a function argument; just check size
if size(A(x)) ~= size(y)
error(['Size of initial x is not compatible with A']);
end
otherwise
error(['Unknown ''Initialization'' option']);
end
% now check if tau is an array; if it is, it has to
% have the same size as x
if prod(size(tau)) > 1
try,
dummy = x.*tau;
catch,
error(['Parameter tau has wrong dimensions; it should be scalar or size(x)']),
end
end
% if the true x was given, check its size
if compute_mse & (size(true) ~= size(x))
error(['Initial x has incompatible size']);
end
% if tau is large enough, in the case of phi = l1, thus psi = soft,
% the optimal solution is the zero vector
if phi_l1
max_tau = max(abs(Aty(:)));
if (tau >= max_tau)&(psi_ok==0)
x = zeros(size(Aty));
objective(1) = 0.5*(y(:)'*y(:));
times(1) = 0;
if compute_mse
mses(1) = sum(true(:).^2);
end
return
end
end
% define the indicator vector or matrix of nonzeros in x
nz_x = (x ~= 0.0);
num_nz_x = sum(nz_x(:));
% Compute and store initial value of the objective function
resid = y-A(x);
prev_f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
% start the clock
t0 = cputime;
times(1) = cputime - t0;
objective(1) = prev_f;
if compute_mse
mses(1) = sum(sum((x-true).^2));
end
cont_outer = 1;
iter = 1;
if verbose
fprintf(1,'\nInitial objective = %10.6e, nonzeros=%7d\n',...
prev_f,num_nz_x);
end
% variables controling first and second order iterations
IST_iters = 0;
TwIST_iters = 0;
% initialize
xm2=x;
xm1=x;
%--------------------------------------------------------------
% TwIST iterations
%--------------------------------------------------------------
while cont_outer
% gradient
grad = AT(resid);
while for_ever
% IST estimate
x = psi_function(xm1 + grad/max_svd,tau/max_svd);
if (IST_iters >= 2) | ( TwIST_iters ~= 0)
% set to zero the past when the present is zero
% suitable for sparse inducing priors
if sparse
mask = (x ~= 0);
xm1 = xm1.* mask;
xm2 = xm2.* mask;
end
% two-step iteration
xm2 = (alpha-beta)*xm1 + (1-alpha)*xm2 + beta*x;
% compute residual
resid = y-A(xm2);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(xm2);
if (f > prev_f) & (enforceMonotone)
TwIST_iters = 0; % do a IST iteration if monotonocity fails
else
TwIST_iters = TwIST_iters+1; % TwIST iterations
IST_iters = 0;
x = xm2;
if mod(TwIST_iters,10000) == 0
max_svd = 0.9*max_svd;
end
break; % break loop while
end
else
resid = y-A(x);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
if f > prev_f
% if monotonicity fails here is because
% max eig (A'A) > 1. Thus, we increase our guess
% of max_svs
max_svd = 2*max_svd;
if verbose
fprintf('Incrementing S=%2.2e\n',max_svd)
end
IST_iters = 0;
TwIST_iters = 0;
else
TwIST_iters = TwIST_iters + 1;
break; % break loop while
end
end
end
xm2 = xm1;
xm1 = x;
%update the number of nonzero components and its variation
nz_x_prev = nz_x;
nz_x = (x~=0.0);
num_nz_x = sum(nz_x(:));
num_changes_active = (sum(nz_x(:)~=nz_x_prev(:)));
% take no less than miniter and no more than maxiter iterations
switch stopCriterion
case 0,
% compute the stopping criterion based on the change
% of the number of non-zero components of the estimate
criterion = num_changes_active;
case 1,
% compute the stopping criterion based on the relative
% variation of the objective function.
criterion = abs(f-prev_f)/prev_f;
case 2,
% compute the stopping criterion based on the relative
% variation of the estimate.
criterion = (norm(x(:)-xm1(:))/norm(x(:)));
case 3,
% continue if not yet reached target value tolA
criterion = f;
otherwise,
error(['Unknwon stopping criterion']);
end
cont_outer = ((iter <= maxiter) & (criterion > tolA));
if iter <= miniter
cont_outer = 1;
end
iter = iter + 1;
prev_f = f;
objective(iter) = f;
times(iter) = cputime-t0;
if compute_mse
err = true - x;
mses(iter) = (err(:)'*err(:));
end
% print out the various stopping criteria
if verbose
if plot_ISNR
fprintf(1,'Iteration=%4d, ISNR=%4.5e objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, 10*log10(sum((y(:)-true(:)).^2)/sum((x(:)-true(:)).^2) ), ...
f, num_nz_x, criterion/tolA);
else
fprintf(1,'Iteration=%4d, objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, f, num_nz_x, criterion/tolA);
end
end
% figure(999);imagesc(plotdatacube(x));colormap gray;axis image;colorbar;drawnow;
end
%--------------------------------------------------------------
% end of the main loop
%--------------------------------------------------------------
% Printout results
if verbose
fprintf(1,'\nFinished the main algorithm!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
fprintf(1,'Number of non-zero components = %d\n',num_nz_x);
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
%--------------------------------------------------------------
% If the 'Debias' option is set to 1, we try to
% remove the bias from the l1 penalty, by applying CG to the
% least-squares problem obtained by omitting the l1 term
% and fixing the zero coefficients at zero.
%--------------------------------------------------------------
if debias
if verbose
fprintf(1,'\n')
fprintf(1,'Starting the debiasing phase...\n\n')
end
x_debias = x;
zeroind = (x_debias~=0);
cont_debias_cg = 1;
debias_start = iter;
% calculate initial residual
resid = A(x_debias);
resid = resid-y;
resid_prev = eps*ones(size(resid));
rvec = AT(resid);
% mask out the zeros
rvec = rvec .* zeroind;
rTr_cg = rvec(:)'*rvec(:);
% set convergence threshold for the residual || RW x_debias - y ||_2
tol_debias = tolD * (rvec(:)'*rvec(:));
% initialize pvec
pvec = -rvec;
% main loop
while cont_debias_cg
% calculate A*p = Wt * Rt * R * W * pvec
RWpvec = A(pvec);
Apvec = AT(RWpvec);
% mask out the zero terms
Apvec = Apvec .* zeroind;
% calculate alpha for CG
alpha_cg = rTr_cg / (pvec(:)'* Apvec(:));
% take the step
x_debias = x_debias + alpha_cg * pvec;
resid = resid + alpha_cg * RWpvec;
rvec = rvec + alpha_cg * Apvec;
rTr_cg_plus = rvec(:)'*rvec(:);
beta_cg = rTr_cg_plus / rTr_cg;
pvec = -rvec + beta_cg * pvec;
rTr_cg = rTr_cg_plus;
iter = iter+1;
objective(iter) = 0.5*(resid(:)'*resid(:)) + ...
tau*phi_function(x_debias(:));
times(iter) = cputime - t0;
if compute_mse
err = true - x_debias;
mses(iter) = (err(:)'*err(:));
end
% in the debiasing CG phase, always use convergence criterion
% based on the residual (this is standard for CG)
if verbose
fprintf(1,' Iter = %5d, debias resid = %13.8e, convergence = %8.3e\n', ...
iter, resid(:)'*resid(:), rTr_cg / tol_debias);
end
cont_debias_cg = ...
(iter-debias_start <= miniter_debias )| ...
((rTr_cg > tol_debias) & ...
(iter-debias_start <= maxiter_debias));
end
if verbose
fprintf(1,'\nFinished the debiasing phase!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
nz = (x_debias~=0.0);
fprintf(1,'Number of non-zero components = %d\n',sum(nz(:)));
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
end
if compute_mse
mses = mses/length(true(:));
end
%--------------------------------------------------------------
% soft for both real and complex numbers
%--------------------------------------------------------------
function y = soft(x,T)
%y = sign(x).*max(abs(x)-tau,0);
y = max(abs(x) - T, 0);
y = y./(y+T) .* x;
|
github
|
winswang/comp_holo_video-master
|
MyTVphi.m
|
.m
|
comp_holo_video-master/3D/MyTVphi.m
| 281 |
utf_8
|
9b938a61469a38963950ef4d40953c71
|
function y=MyTVphi(x,Nvx,Nvy,Nvz)
% x = x(1:length(x)/2) + 1i*x(length(x)/2+1:end);
X=reshape(x,Nvx,Nvy,Nvz);
[y,dif]=MyTVnorm(X);
% re = real(y); im = imag(y);
% y = [re;im];
function [y,dif]=MyTVnorm(x)
TV=MyTV3D_conv(x);
dif=sqrt(sum(TV.*conj(TV),4));
y=sum(dif(:));
end
end
|
github
|
winswang/comp_holo_video-master
|
TwIST.m
|
.m
|
comp_holo_video-master/Resolution/TwIST.m
| 22,842 |
utf_8
|
64ee75349f89f520998ec0d7afd15ac0
|
function [x,x_debias,objective,times,debias_start,mses,max_svd] = ...
TwIST(y,A,tau,varargin)
%
% Usage:
% [x,x_debias,objective,times,debias_start,mses] = TwIST(y,A,tau,varargin)
%
% This function solves the regularization problem
%
% arg min_x = 0.5*|| y - A x ||_2^2 + tau phi( x ),
%
% where A is a generic matrix and phi(.) is a regularizarion
% function such that the solution of the denoising problem
%
% Psi_tau(y) = arg min_x = 0.5*|| y - x ||_2^2 + tau \phi( x ),
%
% is known.
%
% For further details about the TwIST algorithm, see the paper:
%
% J. Bioucas-Dias and M. Figueiredo, "A New TwIST: Two-Step
% Iterative Shrinkage/Thresholding Algorithms for Image
% Restoration", IEEE Transactions on Image processing, 2007.
%
% and
%
% J. Bioucas-Dias and M. Figueiredo, "A Monotonic Two-Step
% Algorithm for Compressive Sensing and Other Ill-Posed
% Inverse Problems", submitted, 2007.
%
% Authors: Jose Bioucas-Dias and Mario Figueiredo, October, 2007.
%
% Please check for the latest version of the code and papers at
% www.lx.it.pt/~bioucas/TwIST
%
% -----------------------------------------------------------------------
% Copyright (2007): Jose Bioucas-Dias and Mario Figueiredo
%
% TwIST is distributed under the terms of
% the GNU General Public License 2.0.
%
% Permission to use, copy, modify, and distribute this software for
% any purpose without fee is hereby granted, provided that this entire
% notice is included in all copies of any software which is or includes
% a copy or modification of this software and in all copies of the
% supporting documentation for such software.
% This software is being provided "as is", without any express or
% implied warranty. In particular, the authors do not make any
% representation or warranty of any kind concerning the merchantability
% of this software or its fitness for any particular purpose."
% ----------------------------------------------------------------------
%
% ===== Required inputs =============
%
% y: 1D vector or 2D array (image) of observations
%
% A: if y and x are both 1D vectors, A can be a
% k*n (where k is the size of y and n the size of x)
% matrix or a handle to a function that computes
% products of the form A*v, for some vector v.
% In any other case (if y and/or x are 2D arrays),
% A has to be passed as a handle to a function which computes
% products of the form A*x; another handle to a function
% AT which computes products of the form A'*x is also required
% in this case. The size of x is determined as the size
% of the result of applying AT.
%
% tau: regularization parameter, usually a non-negative real
% parameter of the objective function (see above).
%
%
% ===== Optional inputs =============
%
% 'Psi' = denoising function handle; handle to denoising function
% Default = soft threshold.
%
% 'Phi' = function handle to regularizer needed to compute the objective
% function.
% Default = ||x||_1
%
% 'lambda' = lam1 parameters of the TwIST algorithm:
% Optimal choice: lam1 = min eigenvalue of A'*A.
% If min eigenvalue of A'*A == 0, or unknwon,
% set lam1 to a value much smaller than 1.
%
% Rule of Thumb:
% lam1=1e-4 for severyly ill-conditioned problems
% lam1=1e-2 for mildly ill-conditioned problems
% lam1=1 for A unitary direct operators
%
% Default: lam1 = 0.04.
%
% Important Note: If (max eigenvalue of A'*A) > 1,
% the algorithm may diverge. This is be avoided
% by taking one of the follwoing measures:
%
% 1) Set 'Monontone' = 1 (default)
%
% 2) Solve the equivalenve minimization problem
%
% min_x = 0.5*|| (y/c) - (A/c) x ||_2^2 + (tau/c^2) \phi( x ),
%
% where c > 0 ensures that max eigenvalue of (A'A/c^2) <= 1.
%
% 'alpha' = parameter alpha of TwIST (see ex. (22) of the paper)
% Default alpha = alpha(lamN=1, lam1)
%
% 'beta' = parameter beta of twist (see ex. (23) of the paper)
% Default beta = beta(lamN=1, lam1)
%
% 'AT' = function handle for the function that implements
% the multiplication by the conjugate of A, when A
% is a function handle.
% If A is an array, AT is ignored.
%
% 'StopCriterion' = type of stopping criterion to use
% 0 = algorithm stops when the relative
% change in the number of non-zero
% components of the estimate falls
% below 'ToleranceA'
% 1 = stop when the relative
% change in the objective function
% falls below 'ToleranceA'
% 2 = stop when the relative norm of the difference between
% two consecutive estimates falls below toleranceA
% 3 = stop when the objective function
% becomes equal or less than toleranceA.
% Default = 1.
%
% 'ToleranceA' = stopping threshold; Default = 0.01
%
% 'Debias' = debiasing option: 1 = yes, 0 = no.
% Default = 0.
%
% Note: Debiasing is an operation aimed at the
% computing the solution of the LS problem
%
% arg min_x = 0.5*|| y - A' x' ||_2^2
%
% where A' is the submatrix of A obatained by
% deleting the columns of A corresponding of components
% of x set to zero by the TwIST algorithm
%
%
% 'ToleranceD' = stopping threshold for the debiasing phase:
% Default = 0.0001.
% If no debiasing takes place, this parameter,
% if present, is ignored.
%
% 'MaxiterA' = maximum number of iterations allowed in the
% main phase of the algorithm.
% Default = 1000
%
% 'MiniterA' = minimum number of iterations performed in the
% main phase of the algorithm.
% Default = 5
%
% 'MaxiterD' = maximum number of iterations allowed in the
% debising phase of the algorithm.
% Default = 200
%
% 'MiniterD' = minimum number of iterations to perform in the
% debiasing phase of the algorithm.
% Default = 5
%
% 'Initialization' must be one of {0,1,2,array}
% 0 -> Initialization at zero.
% 1 -> Random initialization.
% 2 -> initialization with A'*y.
% array -> initialization provided by the user.
% Default = 0;
%
% 'Monotone' = enforce monotonic decrease in f.
% any nonzero -> enforce monotonicity
% 0 -> don't enforce monotonicity.
% Default = 1;
%
% 'Sparse' = {0,1} accelarates the convergence rate when the regularizer
% Phi(x) is sparse inducing, such as ||x||_1.
% Default = 1
%
%
% 'True_x' = if the true underlying x is passed in
% this argument, MSE evolution is computed
%
%
% 'Verbose' = work silently (0) or verbosely (1)
%
% ===================================================
% ============ Outputs ==============================
% x = solution of the main algorithm
%
% x_debias = solution after the debiasing phase;
% if no debiasing phase took place, this
% variable is empty, x_debias = [].
%
% objective = sequence of values of the objective function
%
% times = CPU time after each iteration
%
% debias_start = iteration number at which the debiasing
% phase started. If no debiasing took place,
% this variable is returned as zero.
%
% mses = sequence of MSE values, with respect to True_x,
% if it was given; if it was not given, mses is empty,
% mses = [].
%
% max_svd = inverse of the scaling factor, determined by TwIST,
% applied to the direct operator (A/max_svd) such that
% every IST step is increasing.
% ========================================================
%--------------------------------------------------------------
% test for number of required parametres
%--------------------------------------------------------------
if (nargin-length(varargin)) ~= 3
error('Wrong number of required parameters');
end
%--------------------------------------------------------------
% Set the defaults for the optional parameters
%--------------------------------------------------------------
stopCriterion = 1;
tolA = 0.01;
debias = 0;
maxiter = 1000;
maxiter_debias = 200;
miniter = 5;
miniter_debias = 5;
init = 0;
enforceMonotone = 1;
compute_mse = 0;
plot_ISNR = 0;
AT = 0;
verbose = 1;
alpha = 0;
beta = 0;
sparse = 1;
tolD = 0.001;
phi_l1 = 0;
psi_ok = 0;
% default eigenvalues
lam1=1e-4; lamN=1;
%
% constants ans internal variables
for_ever = 1;
% maj_max_sv: majorizer for the maximum singular value of operator A
max_svd = 1;
% Set the defaults for outputs that may not be computed
debias_start = 0;
x_debias = [];
mses = [];
%--------------------------------------------------------------
% Read the optional parameters
%--------------------------------------------------------------
if (rem(length(varargin),2)==1)
error('Optional parameters should always go by pairs');
else
for i=1:2:(length(varargin)-1)
switch upper(varargin{i})
case 'LAMBDA'
lam1 = varargin{i+1};
case 'ALPHA'
alpha = varargin{i+1};
case 'BETA'
beta = varargin{i+1};
case 'PSI'
psi_function = varargin{i+1};
case 'PHI'
phi_function = varargin{i+1};
case 'STOPCRITERION'
stopCriterion = varargin{i+1};
case 'TOLERANCEA'
tolA = varargin{i+1};
case 'TOLERANCED'
tolD = varargin{i+1};
case 'DEBIAS'
debias = varargin{i+1};
case 'MAXITERA'
maxiter = varargin{i+1};
case 'MAXIRERD'
maxiter_debias = varargin{i+1};
case 'MINITERA'
miniter = varargin{i+1};
case 'MINITERD'
miniter_debias = varargin{i+1};
case 'INITIALIZATION'
if prod(size(varargin{i+1})) > 1 % we have an initial x
init = 33333; % some flag to be used below
x = varargin{i+1};
else
init = varargin{i+1};
end
case 'MONOTONE'
enforceMonotone = varargin{i+1};
case 'SPARSE'
sparse = varargin{i+1};
case 'TRUE_X'
compute_mse = 1;
true = varargin{i+1};
size(true)
size(y)
if prod(double((size(true) == size(y))))
plot_ISNR = 1;
end
case 'AT'
AT = varargin{i+1};
case 'VERBOSE'
verbose = varargin{i+1};
otherwise
% Hmmm, something wrong with the parameter string
error(['Unrecognized option: ''' varargin{i} '''']);
end;
end;
end
%%%%%%%%%%%%%%
% twist parameters
rho0 = (1-lam1/lamN)/(1+lam1/lamN);
if alpha == 0
alpha = 2/(1+sqrt(1-rho0^2));
end
if beta == 0
beta = alpha*2/(lam1+lamN);
end
if (sum(stopCriterion == [0 1 2 3])==0)
error(['Unknwon stopping criterion']);
end
% if A is a function handle, we have to check presence of AT,
if isa(A, 'function_handle') & ~isa(AT,'function_handle')
error(['The function handle for transpose of A is missing']);
end
% if A is a matrix, we find out dimensions of y and x,
% and create function handles for multiplication by A and A',
% so that the code below doesn't have to distinguish between
% the handle/not-handle cases
if ~isa(A, 'function_handle')
AT = @(x) reshape(A'*x(:),[64 64]);
A = @(x) reshape(A*x(:),[size(y,1) size(y,2)]);
end
% from this point down, A and AT are always function handles.
% Precompute A'*y since it'll be used a lot
Aty = AT(y);
% psi_function(Aty,tau)
% if phi was given, check to see if it is a handle and that it
% accepts two arguments
if exist('psi_function','var')
if isa(psi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = psi_function(Aty,tau);
psi_ok = 1;
catch
error(['Something is wrong with function handle for psi'])
end
else
error(['Psi does not seem to be a valid function handle']);
end
else %if nothing was given, use soft thresholding
psi_function = @(x,tau) soft(x,tau);
end
% if psi exists, phi must also exist
if (psi_ok == 1)
if exist('phi_function','var')
if isa(phi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = phi_function(Aty);
catch
error(['Something is wrong with function handle for phi'])
end
else
error(['Phi does not seem to be a valid function handle']);
end
else
error(['If you give Psi you must also give Phi']);
end
else % if no psi and phi were given, simply use the l1 norm.
phi_function = @(x) sum(abs(x(:)));
phi_l1 = 1;
end
%--------------------------------------------------------------
% Initialization
%--------------------------------------------------------------
switch init
case 0 % initialize at zero, using AT to find the size of x
x = AT(zeros(size(y)));
case 1 % initialize randomly, using AT to find the size of x
x = randn(size(AT(zeros(size(y)))));
case 2 % initialize x0 = A'*y
x = Aty;
case 33333
% initial x was given as a function argument; just check size
if size(A(x)) ~= size(y)
error(['Size of initial x is not compatible with A']);
end
otherwise
error(['Unknown ''Initialization'' option']);
end
% now check if tau is an array; if it is, it has to
% have the same size as x
if prod(size(tau)) > 1
try,
dummy = x.*tau;
catch,
error(['Parameter tau has wrong dimensions; it should be scalar or size(x)']),
end
end
% if the true x was given, check its size
if compute_mse & (size(true) ~= size(x))
error(['Initial x has incompatible size']);
end
% if tau is large enough, in the case of phi = l1, thus psi = soft,
% the optimal solution is the zero vector
if phi_l1
max_tau = max(abs(Aty(:)));
if (tau >= max_tau)&(psi_ok==0)
x = zeros(size(Aty));
objective(1) = 0.5*(y(:)'*y(:));
times(1) = 0;
if compute_mse
mses(1) = sum(true(:).^2);
end
return
end
end
% define the indicator vector or matrix of nonzeros in x
nz_x = (x ~= 0.0);
num_nz_x = sum(nz_x(:));
% Compute and store initial value of the objective function
resid = y-A(x);
prev_f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
% start the clock
t0 = cputime;
times(1) = cputime - t0;
objective(1) = prev_f;
if compute_mse
mses(1) = sum(sum((x-true).^2));
end
cont_outer = 1;
iter = 1;
if verbose
fprintf(1,'\nInitial objective = %10.6e, nonzeros=%7d\n',...
prev_f,num_nz_x);
end
% variables controling first and second order iterations
IST_iters = 0;
TwIST_iters = 0;
% initialize
xm2=x;
xm1=x;
%--------------------------------------------------------------
% TwIST iterations
%--------------------------------------------------------------
while cont_outer
% gradient
grad = AT(resid);
while for_ever
% IST estimate
x = psi_function(xm1 + grad/max_svd,tau/max_svd);
if (IST_iters >= 2) | ( TwIST_iters ~= 0)
% set to zero the past when the present is zero
% suitable for sparse inducing priors
if sparse
mask = (x ~= 0);
xm1 = xm1.* mask;
xm2 = xm2.* mask;
end
% two-step iteration
xm2 = (alpha-beta)*xm1 + (1-alpha)*xm2 + beta*x;
% compute residual
resid = y-A(xm2);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(xm2);
if (f > prev_f) & (enforceMonotone)
TwIST_iters = 0; % do a IST iteration if monotonocity fails
else
TwIST_iters = TwIST_iters+1; % TwIST iterations
IST_iters = 0;
x = xm2;
if mod(TwIST_iters,10000) == 0
max_svd = 0.9*max_svd;
end
break; % break loop while
end
else
resid = y-A(x);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
if f > prev_f
% if monotonicity fails here is because
% max eig (A'A) > 1. Thus, we increase our guess
% of max_svs
max_svd = 2*max_svd;
if verbose
fprintf('Incrementing S=%2.2e\n',max_svd)
end
IST_iters = 0;
TwIST_iters = 0;
else
TwIST_iters = TwIST_iters + 1;
break; % break loop while
end
end
end
xm2 = xm1;
xm1 = x;
%update the number of nonzero components and its variation
nz_x_prev = nz_x;
nz_x = (x~=0.0);
num_nz_x = sum(nz_x(:));
num_changes_active = (sum(nz_x(:)~=nz_x_prev(:)));
% take no less than miniter and no more than maxiter iterations
switch stopCriterion
case 0,
% compute the stopping criterion based on the change
% of the number of non-zero components of the estimate
criterion = num_changes_active;
case 1,
% compute the stopping criterion based on the relative
% variation of the objective function.
criterion = abs(f-prev_f)/prev_f;
case 2,
% compute the stopping criterion based on the relative
% variation of the estimate.
criterion = (norm(x(:)-xm1(:))/norm(x(:)));
case 3,
% continue if not yet reached target value tolA
criterion = f;
otherwise,
error(['Unknwon stopping criterion']);
end
cont_outer = ((iter <= maxiter) & (criterion > tolA));
if iter <= miniter
cont_outer = 1;
end
iter = iter + 1;
prev_f = f;
objective(iter) = f;
times(iter) = cputime-t0;
if compute_mse
err = true - x;
mses(iter) = (err(:)'*err(:));
end
% print out the various stopping criteria
if verbose
if plot_ISNR
fprintf(1,'Iteration=%4d, ISNR=%4.5e objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, 10*log10(sum((y(:)-true(:)).^2)/sum((x(:)-true(:)).^2) ), ...
f, num_nz_x, criterion/tolA);
else
fprintf(1,'Iteration=%4d, objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, f, num_nz_x, criterion/tolA);
end
end
% figure(999);imagesc(plotdatacube(x));colormap gray;axis image;colorbar;drawnow;
end
%--------------------------------------------------------------
% end of the main loop
%--------------------------------------------------------------
% Printout results
if verbose
fprintf(1,'\nFinished the main algorithm!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
fprintf(1,'Number of non-zero components = %d\n',num_nz_x);
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
%--------------------------------------------------------------
% If the 'Debias' option is set to 1, we try to
% remove the bias from the l1 penalty, by applying CG to the
% least-squares problem obtained by omitting the l1 term
% and fixing the zero coefficients at zero.
%--------------------------------------------------------------
if debias
if verbose
fprintf(1,'\n')
fprintf(1,'Starting the debiasing phase...\n\n')
end
x_debias = x;
zeroind = (x_debias~=0);
cont_debias_cg = 1;
debias_start = iter;
% calculate initial residual
resid = A(x_debias);
resid = resid-y;
resid_prev = eps*ones(size(resid));
rvec = AT(resid);
% mask out the zeros
rvec = rvec .* zeroind;
rTr_cg = rvec(:)'*rvec(:);
% set convergence threshold for the residual || RW x_debias - y ||_2
tol_debias = tolD * (rvec(:)'*rvec(:));
% initialize pvec
pvec = -rvec;
% main loop
while cont_debias_cg
% calculate A*p = Wt * Rt * R * W * pvec
RWpvec = A(pvec);
Apvec = AT(RWpvec);
% mask out the zero terms
Apvec = Apvec .* zeroind;
% calculate alpha for CG
alpha_cg = rTr_cg / (pvec(:)'* Apvec(:));
% take the step
x_debias = x_debias + alpha_cg * pvec;
resid = resid + alpha_cg * RWpvec;
rvec = rvec + alpha_cg * Apvec;
rTr_cg_plus = rvec(:)'*rvec(:);
beta_cg = rTr_cg_plus / rTr_cg;
pvec = -rvec + beta_cg * pvec;
rTr_cg = rTr_cg_plus;
iter = iter+1;
objective(iter) = 0.5*(resid(:)'*resid(:)) + ...
tau*phi_function(x_debias(:));
times(iter) = cputime - t0;
if compute_mse
err = true - x_debias;
mses(iter) = (err(:)'*err(:));
end
% in the debiasing CG phase, always use convergence criterion
% based on the residual (this is standard for CG)
if verbose
fprintf(1,' Iter = %5d, debias resid = %13.8e, convergence = %8.3e\n', ...
iter, resid(:)'*resid(:), rTr_cg / tol_debias);
end
cont_debias_cg = ...
(iter-debias_start <= miniter_debias )| ...
((rTr_cg > tol_debias) & ...
(iter-debias_start <= maxiter_debias));
end
if verbose
fprintf(1,'\nFinished the debiasing phase!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
nz = (x_debias~=0.0);
fprintf(1,'Number of non-zero components = %d\n',sum(nz(:)));
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
end
if compute_mse
mses = mses/length(true(:));
end
%--------------------------------------------------------------
% soft for both real and complex numbers
%--------------------------------------------------------------
function y = soft(x,T)
%y = sign(x).*max(abs(x)-tau,0);
y = max(abs(x) - T, 0);
y = y./(y+T) .* x;
|
github
|
winswang/comp_holo_video-master
|
MyTVphi.m
|
.m
|
comp_holo_video-master/Resolution/MyTVphi.m
| 281 |
utf_8
|
9b938a61469a38963950ef4d40953c71
|
function y=MyTVphi(x,Nvx,Nvy,Nvz)
% x = x(1:length(x)/2) + 1i*x(length(x)/2+1:end);
X=reshape(x,Nvx,Nvy,Nvz);
[y,dif]=MyTVnorm(X);
% re = real(y); im = imag(y);
% y = [re;im];
function [y,dif]=MyTVnorm(x)
TV=MyTV3D_conv(x);
dif=sqrt(sum(TV.*conj(TV),4));
y=sum(dif(:));
end
end
|
github
|
winswang/comp_holo_video-master
|
TwIST.m
|
.m
|
comp_holo_video-master/4D/TwIST.m
| 22,842 |
utf_8
|
64ee75349f89f520998ec0d7afd15ac0
|
function [x,x_debias,objective,times,debias_start,mses,max_svd] = ...
TwIST(y,A,tau,varargin)
%
% Usage:
% [x,x_debias,objective,times,debias_start,mses] = TwIST(y,A,tau,varargin)
%
% This function solves the regularization problem
%
% arg min_x = 0.5*|| y - A x ||_2^2 + tau phi( x ),
%
% where A is a generic matrix and phi(.) is a regularizarion
% function such that the solution of the denoising problem
%
% Psi_tau(y) = arg min_x = 0.5*|| y - x ||_2^2 + tau \phi( x ),
%
% is known.
%
% For further details about the TwIST algorithm, see the paper:
%
% J. Bioucas-Dias and M. Figueiredo, "A New TwIST: Two-Step
% Iterative Shrinkage/Thresholding Algorithms for Image
% Restoration", IEEE Transactions on Image processing, 2007.
%
% and
%
% J. Bioucas-Dias and M. Figueiredo, "A Monotonic Two-Step
% Algorithm for Compressive Sensing and Other Ill-Posed
% Inverse Problems", submitted, 2007.
%
% Authors: Jose Bioucas-Dias and Mario Figueiredo, October, 2007.
%
% Please check for the latest version of the code and papers at
% www.lx.it.pt/~bioucas/TwIST
%
% -----------------------------------------------------------------------
% Copyright (2007): Jose Bioucas-Dias and Mario Figueiredo
%
% TwIST is distributed under the terms of
% the GNU General Public License 2.0.
%
% Permission to use, copy, modify, and distribute this software for
% any purpose without fee is hereby granted, provided that this entire
% notice is included in all copies of any software which is or includes
% a copy or modification of this software and in all copies of the
% supporting documentation for such software.
% This software is being provided "as is", without any express or
% implied warranty. In particular, the authors do not make any
% representation or warranty of any kind concerning the merchantability
% of this software or its fitness for any particular purpose."
% ----------------------------------------------------------------------
%
% ===== Required inputs =============
%
% y: 1D vector or 2D array (image) of observations
%
% A: if y and x are both 1D vectors, A can be a
% k*n (where k is the size of y and n the size of x)
% matrix or a handle to a function that computes
% products of the form A*v, for some vector v.
% In any other case (if y and/or x are 2D arrays),
% A has to be passed as a handle to a function which computes
% products of the form A*x; another handle to a function
% AT which computes products of the form A'*x is also required
% in this case. The size of x is determined as the size
% of the result of applying AT.
%
% tau: regularization parameter, usually a non-negative real
% parameter of the objective function (see above).
%
%
% ===== Optional inputs =============
%
% 'Psi' = denoising function handle; handle to denoising function
% Default = soft threshold.
%
% 'Phi' = function handle to regularizer needed to compute the objective
% function.
% Default = ||x||_1
%
% 'lambda' = lam1 parameters of the TwIST algorithm:
% Optimal choice: lam1 = min eigenvalue of A'*A.
% If min eigenvalue of A'*A == 0, or unknwon,
% set lam1 to a value much smaller than 1.
%
% Rule of Thumb:
% lam1=1e-4 for severyly ill-conditioned problems
% lam1=1e-2 for mildly ill-conditioned problems
% lam1=1 for A unitary direct operators
%
% Default: lam1 = 0.04.
%
% Important Note: If (max eigenvalue of A'*A) > 1,
% the algorithm may diverge. This is be avoided
% by taking one of the follwoing measures:
%
% 1) Set 'Monontone' = 1 (default)
%
% 2) Solve the equivalenve minimization problem
%
% min_x = 0.5*|| (y/c) - (A/c) x ||_2^2 + (tau/c^2) \phi( x ),
%
% where c > 0 ensures that max eigenvalue of (A'A/c^2) <= 1.
%
% 'alpha' = parameter alpha of TwIST (see ex. (22) of the paper)
% Default alpha = alpha(lamN=1, lam1)
%
% 'beta' = parameter beta of twist (see ex. (23) of the paper)
% Default beta = beta(lamN=1, lam1)
%
% 'AT' = function handle for the function that implements
% the multiplication by the conjugate of A, when A
% is a function handle.
% If A is an array, AT is ignored.
%
% 'StopCriterion' = type of stopping criterion to use
% 0 = algorithm stops when the relative
% change in the number of non-zero
% components of the estimate falls
% below 'ToleranceA'
% 1 = stop when the relative
% change in the objective function
% falls below 'ToleranceA'
% 2 = stop when the relative norm of the difference between
% two consecutive estimates falls below toleranceA
% 3 = stop when the objective function
% becomes equal or less than toleranceA.
% Default = 1.
%
% 'ToleranceA' = stopping threshold; Default = 0.01
%
% 'Debias' = debiasing option: 1 = yes, 0 = no.
% Default = 0.
%
% Note: Debiasing is an operation aimed at the
% computing the solution of the LS problem
%
% arg min_x = 0.5*|| y - A' x' ||_2^2
%
% where A' is the submatrix of A obatained by
% deleting the columns of A corresponding of components
% of x set to zero by the TwIST algorithm
%
%
% 'ToleranceD' = stopping threshold for the debiasing phase:
% Default = 0.0001.
% If no debiasing takes place, this parameter,
% if present, is ignored.
%
% 'MaxiterA' = maximum number of iterations allowed in the
% main phase of the algorithm.
% Default = 1000
%
% 'MiniterA' = minimum number of iterations performed in the
% main phase of the algorithm.
% Default = 5
%
% 'MaxiterD' = maximum number of iterations allowed in the
% debising phase of the algorithm.
% Default = 200
%
% 'MiniterD' = minimum number of iterations to perform in the
% debiasing phase of the algorithm.
% Default = 5
%
% 'Initialization' must be one of {0,1,2,array}
% 0 -> Initialization at zero.
% 1 -> Random initialization.
% 2 -> initialization with A'*y.
% array -> initialization provided by the user.
% Default = 0;
%
% 'Monotone' = enforce monotonic decrease in f.
% any nonzero -> enforce monotonicity
% 0 -> don't enforce monotonicity.
% Default = 1;
%
% 'Sparse' = {0,1} accelarates the convergence rate when the regularizer
% Phi(x) is sparse inducing, such as ||x||_1.
% Default = 1
%
%
% 'True_x' = if the true underlying x is passed in
% this argument, MSE evolution is computed
%
%
% 'Verbose' = work silently (0) or verbosely (1)
%
% ===================================================
% ============ Outputs ==============================
% x = solution of the main algorithm
%
% x_debias = solution after the debiasing phase;
% if no debiasing phase took place, this
% variable is empty, x_debias = [].
%
% objective = sequence of values of the objective function
%
% times = CPU time after each iteration
%
% debias_start = iteration number at which the debiasing
% phase started. If no debiasing took place,
% this variable is returned as zero.
%
% mses = sequence of MSE values, with respect to True_x,
% if it was given; if it was not given, mses is empty,
% mses = [].
%
% max_svd = inverse of the scaling factor, determined by TwIST,
% applied to the direct operator (A/max_svd) such that
% every IST step is increasing.
% ========================================================
%--------------------------------------------------------------
% test for number of required parametres
%--------------------------------------------------------------
if (nargin-length(varargin)) ~= 3
error('Wrong number of required parameters');
end
%--------------------------------------------------------------
% Set the defaults for the optional parameters
%--------------------------------------------------------------
stopCriterion = 1;
tolA = 0.01;
debias = 0;
maxiter = 1000;
maxiter_debias = 200;
miniter = 5;
miniter_debias = 5;
init = 0;
enforceMonotone = 1;
compute_mse = 0;
plot_ISNR = 0;
AT = 0;
verbose = 1;
alpha = 0;
beta = 0;
sparse = 1;
tolD = 0.001;
phi_l1 = 0;
psi_ok = 0;
% default eigenvalues
lam1=1e-4; lamN=1;
%
% constants ans internal variables
for_ever = 1;
% maj_max_sv: majorizer for the maximum singular value of operator A
max_svd = 1;
% Set the defaults for outputs that may not be computed
debias_start = 0;
x_debias = [];
mses = [];
%--------------------------------------------------------------
% Read the optional parameters
%--------------------------------------------------------------
if (rem(length(varargin),2)==1)
error('Optional parameters should always go by pairs');
else
for i=1:2:(length(varargin)-1)
switch upper(varargin{i})
case 'LAMBDA'
lam1 = varargin{i+1};
case 'ALPHA'
alpha = varargin{i+1};
case 'BETA'
beta = varargin{i+1};
case 'PSI'
psi_function = varargin{i+1};
case 'PHI'
phi_function = varargin{i+1};
case 'STOPCRITERION'
stopCriterion = varargin{i+1};
case 'TOLERANCEA'
tolA = varargin{i+1};
case 'TOLERANCED'
tolD = varargin{i+1};
case 'DEBIAS'
debias = varargin{i+1};
case 'MAXITERA'
maxiter = varargin{i+1};
case 'MAXIRERD'
maxiter_debias = varargin{i+1};
case 'MINITERA'
miniter = varargin{i+1};
case 'MINITERD'
miniter_debias = varargin{i+1};
case 'INITIALIZATION'
if prod(size(varargin{i+1})) > 1 % we have an initial x
init = 33333; % some flag to be used below
x = varargin{i+1};
else
init = varargin{i+1};
end
case 'MONOTONE'
enforceMonotone = varargin{i+1};
case 'SPARSE'
sparse = varargin{i+1};
case 'TRUE_X'
compute_mse = 1;
true = varargin{i+1};
size(true)
size(y)
if prod(double((size(true) == size(y))))
plot_ISNR = 1;
end
case 'AT'
AT = varargin{i+1};
case 'VERBOSE'
verbose = varargin{i+1};
otherwise
% Hmmm, something wrong with the parameter string
error(['Unrecognized option: ''' varargin{i} '''']);
end;
end;
end
%%%%%%%%%%%%%%
% twist parameters
rho0 = (1-lam1/lamN)/(1+lam1/lamN);
if alpha == 0
alpha = 2/(1+sqrt(1-rho0^2));
end
if beta == 0
beta = alpha*2/(lam1+lamN);
end
if (sum(stopCriterion == [0 1 2 3])==0)
error(['Unknwon stopping criterion']);
end
% if A is a function handle, we have to check presence of AT,
if isa(A, 'function_handle') & ~isa(AT,'function_handle')
error(['The function handle for transpose of A is missing']);
end
% if A is a matrix, we find out dimensions of y and x,
% and create function handles for multiplication by A and A',
% so that the code below doesn't have to distinguish between
% the handle/not-handle cases
if ~isa(A, 'function_handle')
AT = @(x) reshape(A'*x(:),[64 64]);
A = @(x) reshape(A*x(:),[size(y,1) size(y,2)]);
end
% from this point down, A and AT are always function handles.
% Precompute A'*y since it'll be used a lot
Aty = AT(y);
% psi_function(Aty,tau)
% if phi was given, check to see if it is a handle and that it
% accepts two arguments
if exist('psi_function','var')
if isa(psi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = psi_function(Aty,tau);
psi_ok = 1;
catch
error(['Something is wrong with function handle for psi'])
end
else
error(['Psi does not seem to be a valid function handle']);
end
else %if nothing was given, use soft thresholding
psi_function = @(x,tau) soft(x,tau);
end
% if psi exists, phi must also exist
if (psi_ok == 1)
if exist('phi_function','var')
if isa(phi_function,'function_handle')
try % check if phi can be used, using Aty, which we know has
% same size as x
dummy = phi_function(Aty);
catch
error(['Something is wrong with function handle for phi'])
end
else
error(['Phi does not seem to be a valid function handle']);
end
else
error(['If you give Psi you must also give Phi']);
end
else % if no psi and phi were given, simply use the l1 norm.
phi_function = @(x) sum(abs(x(:)));
phi_l1 = 1;
end
%--------------------------------------------------------------
% Initialization
%--------------------------------------------------------------
switch init
case 0 % initialize at zero, using AT to find the size of x
x = AT(zeros(size(y)));
case 1 % initialize randomly, using AT to find the size of x
x = randn(size(AT(zeros(size(y)))));
case 2 % initialize x0 = A'*y
x = Aty;
case 33333
% initial x was given as a function argument; just check size
if size(A(x)) ~= size(y)
error(['Size of initial x is not compatible with A']);
end
otherwise
error(['Unknown ''Initialization'' option']);
end
% now check if tau is an array; if it is, it has to
% have the same size as x
if prod(size(tau)) > 1
try,
dummy = x.*tau;
catch,
error(['Parameter tau has wrong dimensions; it should be scalar or size(x)']),
end
end
% if the true x was given, check its size
if compute_mse & (size(true) ~= size(x))
error(['Initial x has incompatible size']);
end
% if tau is large enough, in the case of phi = l1, thus psi = soft,
% the optimal solution is the zero vector
if phi_l1
max_tau = max(abs(Aty(:)));
if (tau >= max_tau)&(psi_ok==0)
x = zeros(size(Aty));
objective(1) = 0.5*(y(:)'*y(:));
times(1) = 0;
if compute_mse
mses(1) = sum(true(:).^2);
end
return
end
end
% define the indicator vector or matrix of nonzeros in x
nz_x = (x ~= 0.0);
num_nz_x = sum(nz_x(:));
% Compute and store initial value of the objective function
resid = y-A(x);
prev_f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
% start the clock
t0 = cputime;
times(1) = cputime - t0;
objective(1) = prev_f;
if compute_mse
mses(1) = sum(sum((x-true).^2));
end
cont_outer = 1;
iter = 1;
if verbose
fprintf(1,'\nInitial objective = %10.6e, nonzeros=%7d\n',...
prev_f,num_nz_x);
end
% variables controling first and second order iterations
IST_iters = 0;
TwIST_iters = 0;
% initialize
xm2=x;
xm1=x;
%--------------------------------------------------------------
% TwIST iterations
%--------------------------------------------------------------
while cont_outer
% gradient
grad = AT(resid);
while for_ever
% IST estimate
x = psi_function(xm1 + grad/max_svd,tau/max_svd);
if (IST_iters >= 2) | ( TwIST_iters ~= 0)
% set to zero the past when the present is zero
% suitable for sparse inducing priors
if sparse
mask = (x ~= 0);
xm1 = xm1.* mask;
xm2 = xm2.* mask;
end
% two-step iteration
xm2 = (alpha-beta)*xm1 + (1-alpha)*xm2 + beta*x;
% compute residual
resid = y-A(xm2);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(xm2);
if (f > prev_f) & (enforceMonotone)
TwIST_iters = 0; % do a IST iteration if monotonocity fails
else
TwIST_iters = TwIST_iters+1; % TwIST iterations
IST_iters = 0;
x = xm2;
if mod(TwIST_iters,10000) == 0
max_svd = 0.9*max_svd;
end
break; % break loop while
end
else
resid = y-A(x);
f = 0.5*(resid(:)'*resid(:)) + tau*phi_function(x);
if f > prev_f
% if monotonicity fails here is because
% max eig (A'A) > 1. Thus, we increase our guess
% of max_svs
max_svd = 2*max_svd;
if verbose
fprintf('Incrementing S=%2.2e\n',max_svd)
end
IST_iters = 0;
TwIST_iters = 0;
else
TwIST_iters = TwIST_iters + 1;
break; % break loop while
end
end
end
xm2 = xm1;
xm1 = x;
%update the number of nonzero components and its variation
nz_x_prev = nz_x;
nz_x = (x~=0.0);
num_nz_x = sum(nz_x(:));
num_changes_active = (sum(nz_x(:)~=nz_x_prev(:)));
% take no less than miniter and no more than maxiter iterations
switch stopCriterion
case 0,
% compute the stopping criterion based on the change
% of the number of non-zero components of the estimate
criterion = num_changes_active;
case 1,
% compute the stopping criterion based on the relative
% variation of the objective function.
criterion = abs(f-prev_f)/prev_f;
case 2,
% compute the stopping criterion based on the relative
% variation of the estimate.
criterion = (norm(x(:)-xm1(:))/norm(x(:)));
case 3,
% continue if not yet reached target value tolA
criterion = f;
otherwise,
error(['Unknwon stopping criterion']);
end
cont_outer = ((iter <= maxiter) & (criterion > tolA));
if iter <= miniter
cont_outer = 1;
end
iter = iter + 1;
prev_f = f;
objective(iter) = f;
times(iter) = cputime-t0;
if compute_mse
err = true - x;
mses(iter) = (err(:)'*err(:));
end
% print out the various stopping criteria
if verbose
if plot_ISNR
fprintf(1,'Iteration=%4d, ISNR=%4.5e objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, 10*log10(sum((y(:)-true(:)).^2)/sum((x(:)-true(:)).^2) ), ...
f, num_nz_x, criterion/tolA);
else
fprintf(1,'Iteration=%4d, objective=%9.5e, nz=%7d, criterion=%7.3e\n',...
iter, f, num_nz_x, criterion/tolA);
end
end
% figure(999);imagesc(plotdatacube(x));colormap gray;axis image;colorbar;drawnow;
end
%--------------------------------------------------------------
% end of the main loop
%--------------------------------------------------------------
% Printout results
if verbose
fprintf(1,'\nFinished the main algorithm!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
fprintf(1,'Number of non-zero components = %d\n',num_nz_x);
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
%--------------------------------------------------------------
% If the 'Debias' option is set to 1, we try to
% remove the bias from the l1 penalty, by applying CG to the
% least-squares problem obtained by omitting the l1 term
% and fixing the zero coefficients at zero.
%--------------------------------------------------------------
if debias
if verbose
fprintf(1,'\n')
fprintf(1,'Starting the debiasing phase...\n\n')
end
x_debias = x;
zeroind = (x_debias~=0);
cont_debias_cg = 1;
debias_start = iter;
% calculate initial residual
resid = A(x_debias);
resid = resid-y;
resid_prev = eps*ones(size(resid));
rvec = AT(resid);
% mask out the zeros
rvec = rvec .* zeroind;
rTr_cg = rvec(:)'*rvec(:);
% set convergence threshold for the residual || RW x_debias - y ||_2
tol_debias = tolD * (rvec(:)'*rvec(:));
% initialize pvec
pvec = -rvec;
% main loop
while cont_debias_cg
% calculate A*p = Wt * Rt * R * W * pvec
RWpvec = A(pvec);
Apvec = AT(RWpvec);
% mask out the zero terms
Apvec = Apvec .* zeroind;
% calculate alpha for CG
alpha_cg = rTr_cg / (pvec(:)'* Apvec(:));
% take the step
x_debias = x_debias + alpha_cg * pvec;
resid = resid + alpha_cg * RWpvec;
rvec = rvec + alpha_cg * Apvec;
rTr_cg_plus = rvec(:)'*rvec(:);
beta_cg = rTr_cg_plus / rTr_cg;
pvec = -rvec + beta_cg * pvec;
rTr_cg = rTr_cg_plus;
iter = iter+1;
objective(iter) = 0.5*(resid(:)'*resid(:)) + ...
tau*phi_function(x_debias(:));
times(iter) = cputime - t0;
if compute_mse
err = true - x_debias;
mses(iter) = (err(:)'*err(:));
end
% in the debiasing CG phase, always use convergence criterion
% based on the residual (this is standard for CG)
if verbose
fprintf(1,' Iter = %5d, debias resid = %13.8e, convergence = %8.3e\n', ...
iter, resid(:)'*resid(:), rTr_cg / tol_debias);
end
cont_debias_cg = ...
(iter-debias_start <= miniter_debias )| ...
((rTr_cg > tol_debias) & ...
(iter-debias_start <= maxiter_debias));
end
if verbose
fprintf(1,'\nFinished the debiasing phase!\nResults:\n')
fprintf(1,'||A x - y ||_2 = %10.3e\n',resid(:)'*resid(:))
fprintf(1,'||x||_1 = %10.3e\n',sum(abs(x(:))))
fprintf(1,'Objective function = %10.3e\n',f);
nz = (x_debias~=0.0);
fprintf(1,'Number of non-zero components = %d\n',sum(nz(:)));
fprintf(1,'CPU time so far = %10.3e\n', times(iter));
fprintf(1,'\n');
end
end
if compute_mse
mses = mses/length(true(:));
end
%--------------------------------------------------------------
% soft for both real and complex numbers
%--------------------------------------------------------------
function y = soft(x,T)
%y = sign(x).*max(abs(x)-tau,0);
y = max(abs(x) - T, 0);
y = y./(y+T) .* x;
|
github
|
winswang/comp_holo_video-master
|
MyTVphi.m
|
.m
|
comp_holo_video-master/4D/MyTVphi.m
| 281 |
utf_8
|
9b938a61469a38963950ef4d40953c71
|
function y=MyTVphi(x,Nvx,Nvy,Nvz)
% x = x(1:length(x)/2) + 1i*x(length(x)/2+1:end);
X=reshape(x,Nvx,Nvy,Nvz);
[y,dif]=MyTVnorm(X);
% re = real(y); im = imag(y);
% y = [re;im];
function [y,dif]=MyTVnorm(x)
TV=MyTV3D_conv(x);
dif=sqrt(sum(TV.*conj(TV),4));
y=sum(dif(:));
end
end
|
github
|
chinmaydas96/Neural-Networks-for-Machine-Learning-master
|
learn_perceptron.m
|
.m
|
Neural-Networks-for-Machine-Learning-master/week-3/Assignment1/Octave/learn_perceptron.m
| 6,030 |
utf_8
|
71f226b260465cb3ec3b5c82e3519382
|
%% Learns the weights of a perceptron and displays the results.
function [w] = learn_perceptron(neg_examples_nobias,pos_examples_nobias,w_init,w_gen_feas)
%%
% Learns the weights of a perceptron for a 2-dimensional dataset and plots
% the perceptron at each iteration where an iteration is defined as one
% full pass through the data. If a generously feasible weight vector
% is provided then the visualization will also show the distance
% of the learned weight vectors to the generously feasible weight vector.
% Required Inputs:
% neg_examples_nobias - The num_neg_examples x 2 matrix for the examples with target 0.
% num_neg_examples is the number of examples for the negative class.
% pos_examples_nobias - The num_pos_examples x 2 matrix for the examples with target 1.
% num_pos_examples is the number of examples for the positive class.
% w_init - A 3-dimensional initial weight vector. The last element is the bias.
% w_gen_feas - A generously feasible weight vector.
% Returns:
% w - The learned weight vector.
%%
%Bookkeeping
num_neg_examples = size(neg_examples_nobias,1);
num_pos_examples = size(pos_examples_nobias,1);
num_err_history = [];
w_dist_history = [];
%Here we add a column of ones to the examples in order to allow us to learn
%bias parameters.
neg_examples = [neg_examples_nobias,ones(num_neg_examples,1)];
pos_examples = [pos_examples_nobias,ones(num_pos_examples,1)];
%If weight vectors have not been provided, initialize them appropriately.
if (~exist('w_init','var') || isempty(w_init))
w = randn(3,1);
else
w = w_init;
end
if (~exist('w_gen_feas','var'))
w_gen_feas = [];
end
%Find the data points that the perceptron has incorrectly classified
%and record the number of errors it makes.
iter = 0;
[mistakes0, mistakes1] = eval_perceptron(neg_examples,pos_examples,w);
num_errs = size(mistakes0,1) + size(mistakes1,1);
num_err_history(end+1) = num_errs;
fprintf('Number of errors in iteration %d:\t%d\n',iter,num_errs);
fprintf(['weights:\t', mat2str(w), '\n']);
plot_perceptron(neg_examples, pos_examples, mistakes0, mistakes1, num_err_history, w, w_dist_history);
key = input('<Press enter to continue, q to quit.>', 's');
if (key == 'q')
return;
end
%If a generously feasible weight vector exists, record the distance
%to it from the initial weight vector.
if (length(w_gen_feas) ~= 0)
w_dist_history(end+1) = norm(w - w_gen_feas);
end
%Iterate until the perceptron has correctly classified all points.
while (num_errs > 0)
iter = iter + 1;
%Update the weights of the perceptron.
w = update_weights(neg_examples,pos_examples,w);
%If a generously feasible weight vector exists, record the distance
%to it from the current weight vector.
if (length(w_gen_feas) ~= 0)
w_dist_history(end+1) = norm(w - w_gen_feas);
end
%Find the data points that the perceptron has incorrectly classified.
%and record the number of errors it makes.
[mistakes0, mistakes1] = eval_perceptron(neg_examples,pos_examples,w);
num_errs = size(mistakes0,1) + size(mistakes1,1);
num_err_history(end+1) = num_errs;
fprintf('Number of errors in iteration %d:\t%d\n',iter,num_errs);
fprintf(['weights:\t', mat2str(w), '\n']);
plot_perceptron(neg_examples, pos_examples, mistakes0, mistakes1, num_err_history, w, w_dist_history);
key = input('<Press enter to continue, q to quit.>', 's');
if (key == 'q')
break;
end
end
%WRITE THE CODE TO COMPLETE THIS FUNCTION
function [w] = update_weights(neg_examples, pos_examples, w_current)
%%
% Updates the weights of the perceptron for incorrectly classified points
% using the perceptron update algorithm. This function makes one sweep
% over the dataset.
% Inputs:
% neg_examples - The num_neg_examples x 3 matrix for the examples with target 0.
% num_neg_examples is the number of examples for the negative class.
% pos_examples- The num_pos_examples x 3 matrix for the examples with target 1.
% num_pos_examples is the number of examples for the positive class.
% w_current - A 3-dimensional weight vector, the last element is the bias.
% Returns:
% w - The weight vector after one pass through the dataset using the perceptron
% learning rule.
%%
w = w_current;
num_neg_examples = size(neg_examples,1);
num_pos_examples = size(pos_examples,1);
for i=1:num_neg_examples
this_case = neg_examples(i,:);
x = this_case'; %Hint
activation = this_case*w;
if (activation >= 0)
%YOUR CODE HERE
end
end
for i=1:num_pos_examples
this_case = pos_examples(i,:);
x = this_case';
activation = this_case*w;
if (activation < 0)
%YOUR CODE HERE
end
end
function [mistakes0, mistakes1] = eval_perceptron(neg_examples, pos_examples, w)
%%
% Evaluates the perceptron using a given weight vector. Here, evaluation
% refers to finding the data points that the perceptron incorrectly classifies.
% Inputs:
% neg_examples - The num_neg_examples x 3 matrix for the examples with target 0.
% num_neg_examples is the number of examples for the negative class.
% pos_examples- The num_pos_examples x 3 matrix for the examples with target 1.
% num_pos_examples is the number of examples for the positive class.
% w - A 3-dimensional weight vector, the last element is the bias.
% Returns:
% mistakes0 - A vector containing the indices of the negative examples that have been
% incorrectly classified as positive.
% mistakes0 - A vector containing the indices of the positive examples that have been
% incorrectly classified as negative.
%%
num_neg_examples = size(neg_examples,1);
num_pos_examples = size(pos_examples,1);
mistakes0 = [];
mistakes1 = [];
for i=1:num_neg_examples
x = neg_examples(i,:)';
activation = x'*w;
if (activation >= 0)
mistakes0 = [mistakes0;i];
end
end
for i=1:num_pos_examples
x = pos_examples(i,:)';
activation = x'*w;
if (activation < 0)
mistakes1 = [mistakes1;i];
end
end
|
github
|
chinmaydas96/Neural-Networks-for-Machine-Learning-master
|
plot_perceptron.m
|
.m
|
Neural-Networks-for-Machine-Learning-master/week-3/Assignment1/Octave/plot_perceptron.m
| 3,409 |
utf_8
|
808099ac46c6f636fa74de07abbcc8bb
|
%% Plots information about a perceptron classifier on a 2-dimensional dataset.
function plot_perceptron(neg_examples, pos_examples, mistakes0, mistakes1, num_err_history, w, w_dist_history)
%%
% The top-left plot shows the dataset and the classification boundary given by
% the weights of the perceptron. The negative examples are shown as circles
% while the positive examples are shown as squares. If an example is colored
% green then it means that the example has been correctly classified by the
% provided weights. If it is colored red then it has been incorrectly classified.
% The top-right plot shows the number of mistakes the perceptron algorithm has
% made in each iteration so far.
% The bottom-left plot shows the distance to some generously feasible weight
% vector if one has been provided (note, there can be an infinite number of these).
% Points that the classifier has made a mistake on are shown in red,
% while points that are correctly classified are shown in green.
% The goal is for all of the points to be green (if it is possible to do so).
% Inputs:
% neg_examples - The num_neg_examples x 3 matrix for the examples with target 0.
% num_neg_examples is the number of examples for the negative class.
% pos_examples- The num_pos_examples x 3 matrix for the examples with target 1.
% num_pos_examples is the number of examples for the positive class.
% mistakes0 - A vector containing the indices of the datapoints from class 0 incorrectly
% classified by the perceptron. This is a subset of neg_examples.
% mistakes1 - A vector containing the indices of the datapoints from class 1 incorrectly
% classified by the perceptron. This is a subset of pos_examples.
% num_err_history - A vector containing the number of mistakes for each
% iteration of learning so far.
% w - A 3-dimensional vector corresponding to the current weights of the
% perceptron. The last element is the bias.
% w_dist_history - A vector containing the L2-distance to a generously
% feasible weight vector for each iteration of learning so far.
% Empty if one has not been provided.
%%
f = figure(1);
clf(f);
neg_correct_ind = setdiff(1:size(neg_examples,1),mistakes0);
pos_correct_ind = setdiff(1:size(pos_examples,1),mistakes1);
subplot(2,2,1);
hold on;
if (~isempty(neg_examples))
plot(neg_examples(neg_correct_ind,1),neg_examples(neg_correct_ind,2),'og','markersize',20);
end
if (~isempty(pos_examples))
plot(pos_examples(pos_correct_ind,1),pos_examples(pos_correct_ind,2),'sg','markersize',20);
end
if (size(mistakes0,1) > 0)
plot(neg_examples(mistakes0,1),neg_examples(mistakes0,2),'or','markersize',20);
end
if (size(mistakes1,1) > 0)
plot(pos_examples(mistakes1,1),pos_examples(mistakes1,2),'sr','markersize',20);
end
title('Classifier');
%In order to plot the decision line, we just need to get two points.
plot([-5,5],[(-w(end)+5*w(1))/w(2),(-w(end)-5*w(1))/w(2)],'k')
xlim([-1,1]);
ylim([-1,1]);
hold off;
subplot(2,2,2);
plot(0:length(num_err_history)-1,num_err_history);
xlim([-1,max(15,length(num_err_history))]);
ylim([0,size(neg_examples,1)+size(pos_examples,1)+1]);
title('Number of errors');
xlabel('Iteration');
ylabel('Number of errors');
subplot(2,2,3);
plot(0:length(w_dist_history)-1,w_dist_history);
xlim([-1,max(15,length(num_err_history))]);
ylim([0,15]);
title('Distance')
xlabel('Iteration');
ylabel('Distance');
|
github
|
chinmaydas96/Neural-Networks-for-Machine-Learning-master
|
train.m
|
.m
|
Neural-Networks-for-Machine-Learning-master/week-5/assignment2/train.m
| 8,675 |
utf_8
|
eb006271f1479b68936e2aeb9c7222f8
|
% This function trains a neural network language model.
function [model] = train(epochs)
% Inputs:
% epochs: Number of epochs to run.
% Output:
% model: A struct containing the learned weights and biases and vocabulary.
if size(ver('Octave'),1)
OctaveMode = 1;
warning('error', 'Octave:broadcast');
start_time = time;
else
OctaveMode = 0;
start_time = clock;
end
% SET HYPERPARAMETERS HERE.
batchsize = 100; % Mini-batch size.
learning_rate = 0.1; % Learning rate; default = 0.1.
momentum = 0.9; % Momentum; default = 0.9.
numhid1 = 50; % Dimensionality of embedding space; default = 50.
numhid2 = 200; % Number of units in hidden layer; default = 200.
init_wt = 0.01; % Standard deviation of the normal distribution
% which is sampled to get the initial weights; default = 0.01
% VARIABLES FOR TRACKING TRAINING PROGRESS.
show_training_CE_after = 100;
show_validation_CE_after = 1000;
% LOAD DATA.
[train_input, train_target, valid_input, valid_target, ...
test_input, test_target, vocab] = load_data(batchsize);
[numwords, batchsize, numbatches] = size(train_input);
vocab_size = size(vocab, 2);
% INITIALIZE WEIGHTS AND BIASES.
word_embedding_weights = init_wt * randn(vocab_size, numhid1);
embed_to_hid_weights = init_wt * randn(numwords * numhid1, numhid2);
hid_to_output_weights = init_wt * randn(numhid2, vocab_size);
hid_bias = zeros(numhid2, 1);
output_bias = zeros(vocab_size, 1);
word_embedding_weights_delta = zeros(vocab_size, numhid1);
word_embedding_weights_gradient = zeros(vocab_size, numhid1);
embed_to_hid_weights_delta = zeros(numwords * numhid1, numhid2);
hid_to_output_weights_delta = zeros(numhid2, vocab_size);
hid_bias_delta = zeros(numhid2, 1);
output_bias_delta = zeros(vocab_size, 1);
expansion_matrix = eye(vocab_size);
count = 0;
tiny = exp(-30);
% TRAIN.
for epoch = 1:epochs
fprintf(1, 'Epoch %d\n', epoch);
this_chunk_CE = 0;
trainset_CE = 0;
% LOOP OVER MINI-BATCHES.
for m = 1:numbatches
input_batch = train_input(:, :, m);
target_batch = train_target(:, :, m);
% FORWARD PROPAGATE.
% Compute the state of each layer in the network given the input batch
% and all weights and biases
[embedding_layer_state, hidden_layer_state, output_layer_state] = ...
fprop(input_batch, ...
word_embedding_weights, embed_to_hid_weights, ...
hid_to_output_weights, hid_bias, output_bias);
% COMPUTE DERIVATIVE.
%% Expand the target to a sparse 1-of-K vector.
expanded_target_batch = expansion_matrix(:, target_batch);
%% Compute derivative of cross-entropy loss function.
error_deriv = output_layer_state - expanded_target_batch;
% MEASURE LOSS FUNCTION.
CE = -sum(sum(...
expanded_target_batch .* log(output_layer_state + tiny))) / batchsize;
count = count + 1;
this_chunk_CE = this_chunk_CE + (CE - this_chunk_CE) / count;
trainset_CE = trainset_CE + (CE - trainset_CE) / m;
fprintf(1, '\rBatch %d Train CE %.3f', m, this_chunk_CE);
if mod(m, show_training_CE_after) == 0
fprintf(1, '\n');
count = 0;
this_chunk_CE = 0;
end
if OctaveMode
fflush(1);
end
% BACK PROPAGATE.
%% OUTPUT LAYER.
hid_to_output_weights_gradient = hidden_layer_state * error_deriv';
output_bias_gradient = sum(error_deriv, 2);
back_propagated_deriv_1 = (hid_to_output_weights * error_deriv) ...
.* hidden_layer_state .* (1 - hidden_layer_state);
%% HIDDEN LAYER.
% FILL IN CODE. Replace the line below by one of the options.
embed_to_hid_weights_gradient = zeros(numhid1 * numwords, numhid2);
% Options:
% (a) embed_to_hid_weights_gradient = back_propagated_deriv_1' * embedding_layer_state;
% (b) embed_to_hid_weights_gradient = embedding_layer_state * back_propagated_deriv_1';
% (c) embed_to_hid_weights_gradient = back_propagated_deriv_1;
% (d) embed_to_hid_weights_gradient = embedding_layer_state;
% FILL IN CODE. Replace the line below by one of the options.
hid_bias_gradient = zeros(numhid2, 1);
% Options
% (a) hid_bias_gradient = sum(back_propagated_deriv_1, 2);
% (b) hid_bias_gradient = sum(back_propagated_deriv_1, 1);
% (c) hid_bias_gradient = back_propagated_deriv_1;
% (d) hid_bias_gradient = back_propagated_deriv_1';
% FILL IN CODE. Replace the line below by one of the options.
back_propagated_deriv_2 = zeros(numhid2, batchsize);
% Options
% (a) back_propagated_deriv_2 = embed_to_hid_weights * back_propagated_deriv_1;
% (b) back_propagated_deriv_2 = back_propagated_deriv_1 * embed_to_hid_weights;
% (c) back_propagated_deriv_2 = back_propagated_deriv_1' * embed_to_hid_weights;
% (d) back_propagated_deriv_2 = back_propagated_deriv_1 * embed_to_hid_weights';
word_embedding_weights_gradient(:) = 0;
%% EMBEDDING LAYER.
for w = 1:numwords
word_embedding_weights_gradient = word_embedding_weights_gradient + ...
expansion_matrix(:, input_batch(w, :)) * ...
(back_propagated_deriv_2(1 + (w - 1) * numhid1 : w * numhid1, :)');
end
% UPDATE WEIGHTS AND BIASES.
word_embedding_weights_delta = ...
momentum .* word_embedding_weights_delta + ...
word_embedding_weights_gradient ./ batchsize;
word_embedding_weights = word_embedding_weights...
- learning_rate * word_embedding_weights_delta;
embed_to_hid_weights_delta = ...
momentum .* embed_to_hid_weights_delta + ...
embed_to_hid_weights_gradient ./ batchsize;
embed_to_hid_weights = embed_to_hid_weights...
- learning_rate * embed_to_hid_weights_delta;
hid_to_output_weights_delta = ...
momentum .* hid_to_output_weights_delta + ...
hid_to_output_weights_gradient ./ batchsize;
hid_to_output_weights = hid_to_output_weights...
- learning_rate * hid_to_output_weights_delta;
hid_bias_delta = momentum .* hid_bias_delta + ...
hid_bias_gradient ./ batchsize;
hid_bias = hid_bias - learning_rate * hid_bias_delta;
output_bias_delta = momentum .* output_bias_delta + ...
output_bias_gradient ./ batchsize;
output_bias = output_bias - learning_rate * output_bias_delta;
% VALIDATE.
if mod(m, show_validation_CE_after) == 0
fprintf(1, '\rRunning validation ...');
if OctaveMode
fflush(1);
end
[embedding_layer_state, hidden_layer_state, output_layer_state] = ...
fprop(valid_input, word_embedding_weights, embed_to_hid_weights,...
hid_to_output_weights, hid_bias, output_bias);
datasetsize = size(valid_input, 2);
expanded_valid_target = expansion_matrix(:, valid_target);
CE = -sum(sum(...
expanded_valid_target .* log(output_layer_state + tiny))) /datasetsize;
fprintf(1, ' Validation CE %.3f\n', CE);
if OctaveMode
fflush(1);
end
end
end
fprintf(1, '\rAverage Training CE %.3f\n', trainset_CE);
end
fprintf(1, 'Finished Training.\n');
if OctaveMode
fflush(1);
end
fprintf(1, 'Final Training CE %.3f\n', trainset_CE);
% EVALUATE ON VALIDATION SET.
fprintf(1, '\rRunning validation ...');
if OctaveMode
fflush(1);
end
[embedding_layer_state, hidden_layer_state, output_layer_state] = ...
fprop(valid_input, word_embedding_weights, embed_to_hid_weights,...
hid_to_output_weights, hid_bias, output_bias);
datasetsize = size(valid_input, 2);
expanded_valid_target = expansion_matrix(:, valid_target);
CE = -sum(sum(...
expanded_valid_target .* log(output_layer_state + tiny))) / datasetsize;
fprintf(1, '\rFinal Validation CE %.3f\n', CE);
if OctaveMode
fflush(1);
end
% EVALUATE ON TEST SET.
fprintf(1, '\rRunning test ...');
if OctaveMode
fflush(1);
end
[embedding_layer_state, hidden_layer_state, output_layer_state] = ...
fprop(test_input, word_embedding_weights, embed_to_hid_weights,...
hid_to_output_weights, hid_bias, output_bias);
datasetsize = size(test_input, 2);
expanded_test_target = expansion_matrix(:, test_target);
CE = -sum(sum(...
expanded_test_target .* log(output_layer_state + tiny))) / datasetsize;
fprintf(1, '\rFinal Test CE %.3f\n', CE);
if OctaveMode
fflush(1);
end
model.word_embedding_weights = word_embedding_weights;
model.embed_to_hid_weights = embed_to_hid_weights;
model.hid_to_output_weights = hid_to_output_weights;
model.hid_bias = hid_bias;
model.output_bias = output_bias;
model.vocab = vocab;
% In MATLAB replace line below with 'end_time = clock;'
if OctaveMode
end_time = time;
diff = end_time - start_time;
else
end_time = clock;
diff = etime(end_time, start_time);
end
fprintf(1, 'Training took %.2f seconds\n', diff);
end
|
github
|
andrewganjinrui/CrackInspection_Matlab-master
|
bilateralFilter.m
|
.m
|
CrackInspection_Matlab-master/bilateralFilter.m
| 7,195 |
utf_8
|
820768914dac0bf852cd298cf3112a76
|
%
% original src: http://people.csail.mit.edu/jiawen/software/bilateralFilter.m
% original author: Jiawen (Kevin) Chen
% <[email protected]>
% http://people.csail.mit.edu/jiawen/
%
% output = bilateralFilter( data, edge, ...
% edgeMin, edgeMax, ...
% sigmaSpatial, sigmaRange, ...
% samplingSpatial, samplingRange )
%
% Bilateral and Cross-Bilateral Filter using the Bilateral Grid.
%
% Bilaterally filters the image 'data' using the edges in the image 'edge'.
% If 'data' == 'edge', then it the standard bilateral filter.
% Otherwise, it is the 'cross' or 'joint' bilateral filter.
% For convenience, you can also pass in [] for 'edge' for the normal
% bilateral filter.
%
% Note that for the cross bilateral filter, data does not need to be
% defined everywhere. Undefined values can be set to 'NaN'. However, edge
% *does* need to be defined everywhere.
%
% data and edge should be of the greyscale, double-precision floating point
% matrices of the same size (i.e. they should be [ height x width ])
%
% data is the only required argument
%
% edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data'
% for the normal bilateral filter) and is useful when the input is in a
% range that's not between 0 and 1. For instance, if you are filtering the
% L channel of an image that ranges between 0 and 100, set edgeMin to 0 and
% edgeMax to 100.
%
% edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge( : ) ).
% This is probably *not* what you want, since the input may not span the
% entire range.
%
% sigmaSpatial and sigmaRange specifies the standard deviation of the space
% and range gaussians, respectively.
% sigmaSpatial defaults to min( width, height ) / 16
% sigmaRange defaults to ( edgeMax - edgeMin ) / 10.
%
% samplingSpatial and samplingRange specifies the amount of downsampling
% used for the approximation. Higher values use less memory but are also
% less accurate. The default and recommended values are:
%
% samplingSpatial = sigmaSpatial
% samplingRange = sigmaRange
%
function output = bilateralFilter( data, edge, edgeMin, edgeMax, sigmaSpatial, sigmaRange, samplingSpatial, samplingRange )
if( ndims( data ) > 2 ),
error( 'data must be a greyscale image with size [ height, width ]' );
end
if( ~isa( data, 'double' ) ),
error( 'data must be of class "double"' );
end
if ~exist( 'edge', 'var' ),
edge = data;
elseif isempty( edge ),
edge = data;
end
if( ndims( edge ) > 2 ),
error( 'edge must be a greyscale image with size [ height, width ]' );
end
if( ~isa( edge, 'double' ) ),
error( 'edge must be of class "double"' );
end
inputHeight = size( data, 1 );
inputWidth = size( data, 2 );
if ~exist( 'edgeMin', 'var' ),
edgeMin = min( edge( : ) );
warning( 'edgeMin not set! Defaulting to: %f\n', edgeMin );
end
if ~exist( 'edgeMax', 'var' ),
edgeMax = max( edge( : ) );
warning( 'edgeMax not set! Defaulting to: %f\n', edgeMax );
end
edgeDelta = edgeMax - edgeMin;
if ~exist( 'sigmaSpatial', 'var' ),
sigmaSpatial = min( inputWidth, inputHeight ) / 16;
fprintf( 'Using default sigmaSpatial of: %f\n', sigmaSpatial );
end
if ~exist( 'sigmaRange', 'var' ),
sigmaRange = 0.1 * edgeDelta;
fprintf( 'Using default sigmaRange of: %f\n', sigmaRange );
end
if ~exist( 'samplingSpatial', 'var' ),
samplingSpatial = sigmaSpatial;
end
if ~exist( 'samplingRange', 'var' ),
samplingRange = sigmaRange;
end
if size( data ) ~= size( edge ),
error( 'data and edge must be of the same size' );
end
% parameters
derivedSigmaSpatial = sigmaSpatial / samplingSpatial;
derivedSigmaRange = sigmaRange / samplingRange;
paddingXY = floor( 2 * derivedSigmaSpatial ) + 1;
paddingZ = floor( 2 * derivedSigmaRange ) + 1;
% allocate 3D grid
downsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ;
gridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
gridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
% compute downsampled indices
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );
% ii =
% 0 0 0 0 0
% 1 1 1 1 1
% 2 2 2 2 2
% jj =
% 0 1 2 3 4
% 0 1 2 3 4
% 0 1 2 3 4
% so when iterating over ii( k ), jj( k )
% get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first)
di = round( ii / samplingSpatial ) + paddingXY + 1;
dj = round( jj / samplingSpatial ) + paddingXY + 1;
dz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1;
% perform scatter (there's probably a faster way than this)
% normally would do downsampledWeights( di, dj, dk ) = 1, but we have to
% perform a summation to do box downsampling
for k = 1 : numel( dz ),
dataZ = data( k ); % traverses the image column wise, same as di( k )
if ~isnan( dataZ ),
dik = di( k );
djk = dj( k );
dzk = dz( k );
gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ;
gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1;
end
end
% make gaussian kernel
kernelWidth = 2 * derivedSigmaSpatial + 1;
kernelHeight = kernelWidth;
kernelDepth = 2 * derivedSigmaRange + 1;
halfKernelWidth = floor( kernelWidth / 2 );
halfKernelHeight = floor( kernelHeight / 2 );
halfKernelDepth = floor( kernelDepth / 2 );
[gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1, 0 : kernelHeight - 1, 0 : kernelDepth - 1 );
gridX = gridX - halfKernelWidth;
gridY = gridY - halfKernelHeight;
gridZ = gridZ - halfKernelDepth;
gridRSquared = ( gridX .* gridX + gridY .* gridY ) / ( derivedSigmaSpatial * derivedSigmaSpatial ) + ( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange );
kernel = exp( -0.5 * gridRSquared );
% convolve
blurredGridData = convn( gridData, kernel, 'same' );
blurredGridWeights = convn( gridWeights, kernel, 'same' );
% divide
blurredGridWeights( blurredGridWeights == 0 ) = -2; % avoid divide by 0, won't read there anyway
normalizedBlurredGrid = blurredGridData ./ blurredGridWeights;
normalizedBlurredGrid( blurredGridWeights < -1 ) = 0; % put 0s where it's undefined
% for debugging
% blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back
% upsample
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); % meshgrid does x, then y, so output arguments need to be reversed
% no rounding
di = ( ii / samplingSpatial ) + paddingXY + 1;
dj = ( jj / samplingSpatial ) + paddingXY + 1;
dz = ( edge - edgeMin ) / samplingRange + paddingZ + 1;
% interpn takes rows, then cols, etc
% i.e. size(v,1), then size(v,2), ...
output = interpn( normalizedBlurredGrid, di, dj, dz );
end
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
colorspace.m
|
.m
|
convolutional_sparse_coding-master/Main/Bilateral Filtering/colorspace.m
| 13,590 |
utf_8
|
b1a9eb973fa39950345a1df707b5d2c8
|
function varargout = colorspace(Conversion,varargin)
%COLORSPACE Convert a color image between color representations.
% B = COLORSPACE(S,A) converts the color representation of image A
% where S is a string specifying the conversion. S tells the
% source and destination color spaces, S = 'dest<-src', or
% alternatively, S = 'src->dest'. Supported color spaces are
%
% 'RGB' R'G'B' Red Green Blue (ITU-R BT.709 gamma-corrected)
% 'YPbPr' Luma (ITU-R BT.601) + Chroma
% 'YCbCr'/'YCC' Luma + Chroma ("digitized" version of Y'PbPr)
% 'YUV' NTSC PAL Y'UV Luma + Chroma
% 'YIQ' NTSC Y'IQ Luma + Chroma
% 'YDbDr' SECAM Y'DbDr Luma + Chroma
% 'JPEGYCbCr' JPEG-Y'CbCr Luma + Chroma
% 'HSV'/'HSB' Hue Saturation Value/Brightness
% 'HSL'/'HLS'/'HSI' Hue Saturation Luminance/Intensity
% 'XYZ' CIE XYZ
% 'Lab' CIE L*a*b* (CIELAB)
% 'Luv' CIE L*u*v* (CIELUV)
% 'Lch' CIE L*ch (CIELCH)
%
% All conversions assume 2 degree observer and D65 illuminant. Color
% space names are case insensitive. When R'G'B' is the source or
% destination, it can be omitted. For example 'yuv<-' is short for
% 'yuv<-rgb'.
%
% MATLAB uses two standard data formats for R'G'B': double data with
% intensities in the range 0 to 1, and uint8 data with integer-valued
% intensities from 0 to 255. As MATLAB's native datatype, double data is
% the natural choice, and the R'G'B' format used by colorspace. However,
% for memory and computational performance, some functions also operate
% with uint8 R'G'B'. Given uint8 R'G'B' color data, colorspace will
% first cast it to double R'G'B' before processing.
%
% If A is an Mx3 array, like a colormap, B will also have size Mx3.
%
% [B1,B2,B3] = COLORSPACE(S,A) specifies separate output channels.
% COLORSPACE(S,A1,A2,A3) specifies separate input channels.
% Pascal Getreuer 2005-2006
%%% Input parsing %%%
if nargin < 2, error('Not enough input arguments.'); end
[SrcSpace,DestSpace] = parse(Conversion);
if nargin == 2
Image = varargin{1};
elseif nargin >= 3
Image = cat(3,varargin{:});
else
error('Invalid number of input arguments.');
end
FlipDims = (size(Image,3) == 1);
if FlipDims, Image = permute(Image,[1,3,2]); end
if ~isa(Image,'double'), Image = double(Image)/255; end
if size(Image,3) ~= 3, error('Invalid input size.'); end
SrcT = gettransform(SrcSpace);
DestT = gettransform(DestSpace);
if ~ischar(SrcT) & ~ischar(DestT)
% Both source and destination transforms are affine, so they
% can be composed into one affine operation
T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
Temp = zeros(size(Image));
Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
Image = Temp;
elseif ~ischar(DestT)
Image = rgb(Image,SrcSpace);
Temp = zeros(size(Image));
Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);
Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);
Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);
Image = Temp;
else
Image = feval(DestT,Image,SrcSpace);
end
%%% Output format %%%
if nargout > 1
varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};
else
if FlipDims, Image = permute(Image,[1,3,2]); end
varargout = {Image};
end
return;
function [SrcSpace,DestSpace] = parse(Str)
% Parse conversion argument
if isstr(Str)
Str = lower(strrep(strrep(Str,'-',''),' ',''));
k = find(Str == '>');
if length(k) == 1 % Interpret the form 'src->dest'
SrcSpace = Str(1:k-1);
DestSpace = Str(k+1:end);
else
k = find(Str == '<');
if length(k) == 1 % Interpret the form 'dest<-src'
DestSpace = Str(1:k-1);
SrcSpace = Str(k+1:end);
else
error(['Invalid conversion, ''',Str,'''.']);
end
end
SrcSpace = alias(SrcSpace);
DestSpace = alias(DestSpace);
else
SrcSpace = 1; % No source pre-transform
DestSpace = Conversion;
if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
end
return;
function Space = alias(Space)
Space = strrep(Space,'cie','');
if isempty(Space)
Space = 'rgb';
end
switch Space
case {'ycbcr','ycc'}
Space = 'ycbcr';
case {'hsv','hsb'}
Space = 'hsv';
case {'hsl','hsi','hls'}
Space = 'hsl';
case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
return;
end
return;
function T = gettransform(Space)
% Get a colorspace transform: either a matrix describing an affine transform,
% or a string referring to a conversion subroutine
switch Space
case 'ypbpr'
T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];
case 'yuv'
% R'G'B' to NTSC/PAL YUV
% Wikipedia: http://en.wikipedia.org/wiki/YUV
T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];
case 'ydbdr'
% R'G'B' to SECAM YDbDr
% Wikipedia: http://en.wikipedia.org/wiki/YDbDr
T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];
case 'yiq'
% R'G'B' in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];
% Wikipedia: http://en.wikipedia.org/wiki/YIQ
T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];
case 'ycbcr'
% R'G'B' (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
% Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion
T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];
case 'jpegycbcr'
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;
case {'rgb','xyz','hsv','hsl','lab','luv','lch'}
T = Space;
otherwise
error(['Unknown color space, ''',Space,'''.']);
end
return;
function Image = rgb(Image,SrcSpace)
% Convert to Rec. 709 R'G'B' from 'SrcSpace'
switch SrcSpace
case 'rgb'
return;
case 'hsv'
% Convert HSV to R'G'B'
Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
case 'hsl'
% Convert HSL to R'G'B'
L = Image(:,:,3);
Delta = Image(:,:,2).*min(L,1-L);
Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));
case {'xyz','lab','luv','lch'}
% Convert to CIE XYZ
Image = xyz(Image,SrcSpace);
% Convert XYZ to RGB
T = [3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B
% Desaturate and rescale to constrain resulting RGB values to [0,1]
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
% Apply gamma correction to convert RGB to Rec. 709 R'G'B'
Image(:,:,1) = gammacorrection(R); % R'
Image(:,:,2) = gammacorrection(G); % G'
Image(:,:,3) = gammacorrection(B); % B'
otherwise % Conversion is through an affine transform
T = gettransform(SrcSpace);
temp = inv(T(:,1:3));
T = [temp,-temp*T(:,4)];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
Image(:,:,1) = R;
Image(:,:,2) = G;
Image(:,:,3) = B;
end
% Clip to [0,1]
Image = min(max(Image,0),1);
return;
function Image = xyz(Image,SrcSpace)
% Convert to CIE XYZ from 'SrcSpace'
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'xyz'
return;
case 'luv'
% Convert CIE L*uv to XYZ
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
L = Image(:,:,1);
Y = (L + 16)/116;
Y = invf(Y)*WhitePoint(2);
U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;
V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;
Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X
Image(:,:,2) = Y; % Y
Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z
case {'lab','lch'}
Image = lab(Image,SrcSpace);
% Convert CIE L*ab to XYZ
fY = (Image(:,:,1) + 16)/116;
fX = fY + Image(:,:,2)/500;
fZ = fY - Image(:,:,3)/200;
Image(:,:,1) = WhitePoint(1)*invf(fX); % X
Image(:,:,2) = WhitePoint(2)*invf(fY); % Y
Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z
otherwise % Convert from some gamma-corrected space
% Convert to Rec. 701 R'G'B'
Image = rgb(Image,SrcSpace);
% Undo gamma correction
R = invgammacorrection(Image(:,:,1));
G = invgammacorrection(Image(:,:,2));
B = invgammacorrection(Image(:,:,3));
% Convert RGB to XYZ
T = inv([3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311]);
Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y
Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z
end
return;
function Image = hsv(Image,SrcSpace)
% Convert to HSV
Image = rgb(Image,SrcSpace);
V = max(Image,[],3);
S = (V - min(Image,[],3))./(V + (V == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = V;
return;
function Image = hsl(Image,SrcSpace)
% Convert to HSL
switch SrcSpace
case 'hsv'
% Convert HSV to HSL
MaxVal = Image(:,:,3);
MinVal = (1 - Image(:,:,2)).*MaxVal;
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,3) = L;
otherwise
Image = rgb(Image,SrcSpace); % Convert to Rec. 701 R'G'B'
% Convert R'G'B' to HSL
MinVal = min(Image,[],3);
MaxVal = max(Image,[],3);
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = L;
end
return;
function Image = lab(Image,SrcSpace)
% Convert to CIE L*a*b* (CIELAB)
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'lab'
return;
case 'lch'
% Convert CIE L*CH to CIE L*ab
C = Image(:,:,2);
Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a*
Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b*
otherwise
Image = xyz(Image,SrcSpace); % Convert to XYZ
% Convert XYZ to CIE L*a*b*
X = Image(:,:,1)/WhitePoint(1);
Y = Image(:,:,2)/WhitePoint(2);
Z = Image(:,:,3)/WhitePoint(3);
fX = f(X);
fY = f(Y);
fZ = f(Z);
Image(:,:,1) = 116*fY - 16; % L*
Image(:,:,2) = 500*(fX - fY); % a*
Image(:,:,3) = 200*(fY - fZ); % b*
end
return;
function Image = luv(Image,SrcSpace)
% Convert to CIE L*u*v* (CIELUV)
WhitePoint = [0.950456,1,1.088754];
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
Image = xyz(Image,SrcSpace); % Convert to XYZ
U = (4*Image(:,:,1))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
V = (9*Image(:,:,2))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
Y = Image(:,:,2)/WhitePoint(2);
L = 116*f(Y) - 16;
Image(:,:,1) = L; % L*
Image(:,:,2) = 13*L.*(U - WhitePointU); % u*
Image(:,:,3) = 13*L.*(V - WhitePointV); % v*
return;
function Image = lch(Image,SrcSpace)
% Convert to CIE L*ch
Image = lab(Image,SrcSpace); % Convert to CIE L*ab
H = atan2(Image(:,:,3),Image(:,:,2));
H = H*180/pi + 360*(H < 0);
Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C
Image(:,:,3) = H; % H
return;
function Image = huetorgb(m0,m2,H)
% Convert HSV or HSL hue to RGB
N = size(H);
H = min(max(H(:),0),360)/60;
m0 = m0(:);
m2 = m2(:);
F = H - round(H/2)*2;
M = [m0, m0 + (m2-m0).*abs(F), m2];
Num = length(m0);
j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
k = floor(H) + 1;
Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
return;
function H = rgbtohue(Image)
% Convert RGB to HSV or HSL hue
[M,i] = sort(Image,3);
i = i(:,:,3);
Delta = M(:,:,3) - M(:,:,1);
Delta = Delta + (Delta == 0);
R = Image(:,:,1);
G = Image(:,:,2);
B = Image(:,:,3);
H = zeros(size(R));
k = (i == 1);
H(k) = (G(k) - B(k))./Delta(k);
k = (i == 2);
H(k) = 2 + (B(k) - R(k))./Delta(k);
k = (i == 3);
H(k) = 4 + (R(k) - G(k))./Delta(k);
H = 60*H + 360*(H < 0);
H(Delta == 0) = nan;
return;
function Rp = gammacorrection(R)
Rp = real(1.099*R.^0.45 - 0.099);
i = (R < 0.018);
Rp(i) = 4.5138*R(i);
return;
function R = invgammacorrection(Rp)
R = real(((Rp + 0.099)/1.099).^(1/0.45));
i = (R < 0.018);
R(i) = Rp(i)/4.5138;
return;
function fY = f(Y)
fY = real(Y.^(1/3));
i = (Y < 0.008856);
fY(i) = Y(i)*(841/108) + (4/29);
return;
function Y = invf(fY)
Y = fY.^3;
i = (Y < 0.008856);
Y(i) = (fY(i) - 4/29)*(108/841);
return;
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
bfilter2.m
|
.m
|
convolutional_sparse_coding-master/Main/Bilateral Filtering/bfilter2.m
| 4,694 |
utf_8
|
c4212b1b128af24576bc68f8b7f09b2b
|
% BFILTER2 Two dimensional bilateral filtering.
% This function implements 2-D bilateral filtering using
% the method outlined in:
%
% C. Tomasi and R. Manduchi. Bilateral Filtering for
% Gray and Color Images. In Proceedings of the IEEE
% International Conference on Computer Vision, 1998.
%
% B = bfilter2(A,W,SIGMA) performs 2-D bilateral filtering
% for the grayscale or color image A. A should be a double
% precision matrix of size NxMx1 or NxMx3 (i.e., grayscale
% or color images, respectively) with normalized values in
% the closed interval [0,1]. The half-size of the Gaussian
% bilateral filter window is defined by W. The standard
% deviations of the bilateral filter are given by SIGMA,
% where the spatial-domain standard deviation is given by
% SIGMA(1) and the intensity-domain standard deviation is
% given by SIGMA(2).
%
% Douglas R. Lanman, Brown University, September 2006.
% [email protected], http://mesh.brown.edu/dlanman
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pre-process input and select appropriate filter.
function B = bfilter2(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);
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.
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 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
% 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
% Close waitbar.
%close(h);
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
deconvtvl2.m
|
.m
|
convolutional_sparse_coding-master/Main/deconvtv_v1/private/deconvtvl2.m
| 6,403 |
utf_8
|
217f733df269e458bcfcea143f50d64f
|
function out = deconvtvl2(g, H, mu, opts)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% out = deconvtv(g, H, mu, opts)
% deconvolves image g by solving the following TV minimization problem
%
% min (mu/2) || Hf - g ||^2 + ||f||_TV
%
% where ||f||_TV = sqrt( a||Dxf||^2 + b||Dyf||^2 c||Dtf||^2),
% Dxf = f(x+1,y, t) - f(x,y,t)
% Dyf = f(x,y+1, t) - f(x,y,t)
% Dtf = f(x,y, t+1) - f(x,y,t)
%
% Input: g - the observed image, can be gray scale, or color
% H - point spread function
% mu - regularization parameter
% opts.rho_r - initial penalty parameter for ||u-Df|| {2}
% opts.rho_o - initial penalty parameter for ||Hf-g-r|| {50}
% opts.beta - regularization parameter [a b c] for weighted TV norm {[1 1 0]}
% opts.gamma - update constant for rho_r {2}
% opts.max_itr - maximum iteration {20}
% opts.alpha - constant that determines constraint violation {0.7}
% opts.tol - tolerance level on relative change {1e-3}
% opts.print - print screen option {false}
% opts.f - initial f {g}
% opts.y1 - initial y1 {0}
% opts.y2 - initial y2 {0}
% opts.y3 - initial y3 {0}
% opts.z - initial z {0}
% ** default values of opts are given in { }.
%
% Output: out.f - output video
% out.itr - total number of iterations elapsed
% out.relchg - final relative change
% out.Df1 - Dxf, f is the output video
% out.Df2 - Dyf, f is the output video
% out.Df3 - Dtf, f is the output video
% out.y1 - Lagrange multiplier for Df1
% out.y2 - Lagrange multiplier for Df2
% out.y3 - Lagrange multiplier for Df3
% out.rho_r - final penalty parameter
%
% Stanley Chan
% Copyright 2010-2011
% University of California, San Diego
%
% Last Modified:
% 30 Apr, 2010 (deconvtv)
% 4 May, 2010 (deconvtv)
% 5 May, 2010 (deconvtv)
% 29 Jul, 2010 (deconvtvl2)
% 11 Feb, 2011 (add Obj Val in output)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[rows cols frames] = size(g);
% Check inputs
if nargin<3
error('not enough input, try again \n');
elseif nargin==3
opts = [];
end
% Check defaults
if ~isfield(opts,'rho_r')
opts.rho_r = 2;
end
if ~isfield(opts,'gamma')
opts.gamma = 2;
end
if ~isfield(opts,'max_itr')
opts.max_itr = 20;
end
if ~isfield(opts,'tol')
opts.tol = 1e-3;
end
if ~isfield(opts,'alpha')
opts.alpha = 0.7;
end
if ~isfield(opts,'print')
opts.print = false;
end
if ~isfield(opts,'f')
opts.f = g;
end
if ~isfield(opts,'y1')
opts.y1 = zeros(rows, cols, frames);
end
if ~isfield(opts,'y2')
opts.y2 = zeros(rows, cols, frames);
end
if ~isfield(opts,'y3')
opts.y3 = zeros(rows, cols, frames);
end
if ~isfield(opts,'u1')
opts.u1 = zeros(rows, cols, frames);
end
if ~isfield(opts,'u2')
opts.u2 = zeros(rows, cols, frames);
end
if ~isfield(opts,'u3')
opts.u3 = zeros(rows, cols, frames);
end
if ~isfield(opts,'beta')
opts.beta = [1 1 0];
end
% initialize
max_itr = opts.max_itr;
tol = opts.tol;
alpha = opts.alpha;
beta = opts.beta;
gamma = opts.gamma;
rho = opts.rho_r;
f = opts.f;
y1 = opts.y1;
y2 = opts.y2;
y3 = opts.y3;
u1 = opts.u1;
u2 = opts.u2;
u3 = opts.u3;
% define operators
eigHtH = abs(fftn(H, [rows cols frames])).^2;
eigDtD = abs(beta(1)*fftn([1 -1], [rows cols frames])).^2 + abs(beta(2)*fftn([1 -1]', [rows cols frames])).^2;
if frames>1
d_tmp(1,1,1)= 1; d_tmp(1,1,2)= -1;
eigEtE = abs(beta(3)*fftn(d_tmp, [rows cols frames])).^2;
else
eigEtE = 0;
end
Htg = imfilter(g, H, 'circular');
[D,Dt] = defDDt(beta);
[Df1 Df2 Df3] = D(f);
out.relchg = [];
out.objval = [];
if opts.print==true
fprintf('Running deconvtv (L2 version) \n');
fprintf('mu = %10.2f \n\n', mu);
fprintf('itr relchg ||Hf-g||^2 ||f||_TV Obj Val rho \n');
end
rnorm = sqrt(norm(Df1(:))^2 + norm(Df2(:))^2 + norm(Df3(:))^2);
for itr=1:max_itr
% solve f-subproblem
f_old = f;
rhs = fftn((mu/rho)*Htg + Dt(u1-(1/rho)*y1, u2-(1/rho)*y2, u3-(1/rho)*y3));
eigA = (mu/rho)*eigHtH + eigDtD + eigEtE;
f = real(ifftn(rhs./eigA));
% solve u-subproblem
[Df1 Df2 Df3] = D(f);
v1 = Df1+(1/rho)*y1;
v2 = Df2+(1/rho)*y2;
v3 = Df3+(1/rho)*y3;
v = sqrt(v1.^2 + v2.^2 + v3.^2);
v(v==0) = 1;
v = max(v - 1/rho, 0)./v;
u1 = v1.*v;
u2 = v2.*v;
u3 = v3.*v;
% update y
y1 = y1 - rho*(u1 - Df1);
y2 = y2 - rho*(u2 - Df2);
y3 = y3 - rho*(u3 - Df3);
% update rho
if (opts.print==true)
r1 = imfilter(f, H, 'circular')-g;
r1norm = sum(r1(:).^2);
r2norm = sum(sqrt(Df1(:).^2 + Df2(:).^2 + Df3(:).^2));
objval = (mu/2)*r1norm+r2norm;
end
rnorm_old = rnorm;
rnorm = sqrt(norm(Df1(:)-u1(:), 'fro')^2 + norm(Df2(:)-u2(:), 'fro')^2 + norm(Df3(:)-u3(:), 'fro')^2);
if rnorm>alpha*rnorm_old
rho = rho * gamma;
end
% relative change
relchg = norm(f(:)-f_old(:))/norm(f_old(:));
out.relchg(itr) = relchg;
if (opts.print==true)
out.objval(itr) = objval;
end
% print
if (opts.print==true)
fprintf('%3g \t %6.4e \t %6.4e \t %6.4e \t %6.4e \t %6.4e\n ', itr, relchg, r1norm, r2norm, objval, rho);
end
% check stopping criteria
if relchg < tol
break
end
end
out.f = f;
out.itr = itr;
out.y1 = y1;
out.y2 = y2;
out.y3 = y3;
out.rho = rho;
out.Df1 = Df1;
out.Df2 = Df2;
out.Df3 = Df3;
if (opts.print==true)
fprintf('\n\n');
end
end
function [D,Dt] = defDDt(beta)
D = @(U) ForwardD(U, beta);
Dt = @(X,Y,Z) Dive(X,Y,Z, beta);
end
function [Dux,Duy,Duz] = ForwardD(U, beta)
frames = size(U, 3);
Dux = beta(1)*[diff(U,1,2), U(:,1,:) - U(:,end,:)];
Duy = beta(2)*[diff(U,1,1); U(1,:,:) - U(end,:,:)];
Duz(:,:,1:frames-1) = beta(3)*diff(U,1,3);
Duz(:,:,frames) = beta(3)*(U(:,:,1) - U(:,:,end));
end
function DtXYZ = Dive(X,Y,Z, beta)
frames = size(X, 3);
DtXYZ = [X(:,end,:) - X(:, 1,:), -diff(X,1,2)];
DtXYZ = beta(1)*DtXYZ + beta(2)*[Y(end,:,:) - Y(1, :,:); -diff(Y,1,1)];
Tmp(:,:,1) = Z(:,:,end) - Z(:,:,1);
Tmp(:,:,2:frames) = -diff(Z,1,3);
DtXYZ = DtXYZ + beta(3)*Tmp;
end
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
deconvtvl1.m
|
.m
|
convolutional_sparse_coding-master/Main/deconvtv_v1/private/deconvtvl1.m
| 6,551 |
utf_8
|
4edd96e4d2a766f65612a717b003a24e
|
function out = deconvtvl1(g, H, mu, opts)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% out = deconvtvl1(g, H, mu, opts)
% deconvolves image g by solving the following TV minimization problem
%
% min (mu/2) || Hf - g ||_1 + ||f||_TV
%
% where ||f||_TV = sqrt( a||Dxf||^2 + b||Dyf||^2 c||Dtf||^2),
% Dxf = f(x+1,y, t) - f(x,y,t)
% Dyf = f(x,y+1, t) - f(x,y,t)
% Dtf = f(x,y, t+1) - f(x,y,t)
%
% Input: g - the observed image, can be gray scale, or color
% H - point spread function
% mu - regularization parameter
% opts.rho_r - initial penalty parameter for ||u-Df|| {2}
% opts.rho_o - initial penalty parameter for ||Hf-g-r|| {50}
% opts.beta - regularization parameter [a b c] for weighted TV norm {[1 1 2.5]}
% opts.gamma - update constant for rho_r {2}
% opts.max_itr - maximum iteration {20}
% opts.alpha - constant that determines constraint violation {0.7}
% opts.tol - tolerance level on relative change {1e-3}
% opts.print - print screen option {false}
% opts.f - initial f {g}
% opts.y1 - initial y1 {0}
% opts.y2 - initial y2 {0}
% opts.y3 - initial y3 {0}
% opts.z - initial z {0}
% ** default values of opts are given in { }.
%
% Output: out.f - output video
% out.itr - total number of iterations elapsed
% out.relchg - final relative change
% out.Df1 - Dxf, f is the output video
% out.Df2 - Dyf, f is the output video
% out.Df3 - Dtf, f is the output video
% out.y1 - Lagrange multiplier for Df1
% out.y2 - Lagrange multiplier for Df2
% out.y3 - Lagrange multiplier for Df3
% out.rho_r - final penalty parameter
%
% Stanley Chan
% Copyright 2010
% University of California, San Diego
%
% Last Modified:
% 30 Apr, 2010 (deconvtv)
% 4 May, 2010 (deconvtv)
% 5 May, 2010 (deconvtv)
% 4 Aug, 2010 (deconvtv_L1)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[rows cols frames] = size(g);
% Check inputs
if nargin<3
error('not enough input, try again \n');
elseif nargin==3
opts = [];
end
if ~isnumeric(mu)
error('mu must be a numeric value! \n');
end
% Check defaults
if ~isfield(opts,'rho_o')
opts.rho_o = 50;
end
if ~isfield(opts,'rho_r')
opts.rho_r = 2;
end
if ~isfield(opts,'gamma')
opts.gamma = 2;
end
if ~isfield(opts,'max_itr')
opts.max_itr = 20;
end
if ~isfield(opts,'tol')
opts.tol = 1e-3;
end
if ~isfield(opts,'alpha')
opts.alpha = 0.7;
end
if ~isfield(opts,'print')
opts.print = false;
end
if ~isfield(opts,'f')
opts.f = g;
end
if ~isfield(opts,'y1')
opts.y1 = zeros(rows, cols, frames);
end
if ~isfield(opts,'y2')
opts.y2 = zeros(rows, cols, frames);
end
if ~isfield(opts,'y3')
opts.y3 = zeros(rows, cols, frames);
end
if ~isfield(opts,'z')
opts.z = zeros(rows, cols, frames);
end
if ~isfield(opts,'beta')
opts.beta = [1 1 0];
end
% initialize
max_itr = opts.max_itr;
tol = opts.tol;
alpha = opts.alpha;
beta = opts.beta;
gamma = opts.gamma;
rho_r = opts.rho_r;
rho_o = opts.rho_o;
f = opts.f;
y1 = opts.y1;
y2 = opts.y2;
y3 = opts.y3;
z = opts.z;
eigHtH = abs(fftn(H, [rows cols frames])).^2;
eigDtD = abs(beta(1)*fftn([1 -1], [rows cols frames])).^2 + abs(beta(2)*fftn([1 -1]', [rows cols frames])).^2;
if frames>1
d_tmp(1,1,1)= 1; d_tmp(1,1,2)= -1;
eigEtE = abs(beta(3)*fftn(d_tmp, [rows cols frames])).^2;
else
eigEtE = 0;
end
Htg = imfilter(g, H, 'circular');
[D,Dt] = defDDt(beta);
[Df1 Df2 Df3] = D(f);
w = imfilter(f, H, 'circular') - g;
rnorm = sqrt(norm(Df1(:))^2 + norm(Df2(:))^2 + norm(Df3(:))^2);
out.relchg = [];
out.objval = [];
if opts.print==true
fprintf('Running deconvtv (L1 version) \n');
fprintf('mu = %10.2f \n\n', mu);
fprintf('itr relchg ||Hf-g||_1 ||f||_TV Obj Val rho_r \n');
end
for itr = 1:max_itr
% u-subproblem
v1 = Df1+(1/rho_r)*y1;
v2 = Df2+(1/rho_r)*y2;
v3 = Df3+(1/rho_r)*y3;
v = sqrt(v1.^2 + v2.^2 + v3.^2);
v(v==0) = 1e-6;
v = max(v - 1/rho_r, 0)./v;
u1 = v1.*v;
u2 = v2.*v;
u3 = v3.*v;
% r-subproblem
r = max(abs(w + 1/rho_o*z)-mu/rho_o, 0).*sign(w+1/rho_o*z);
% f-subproblem
f_old = f;
rhs = rho_o*Htg + imfilter(rho_o*r-z, H, 'circular') + Dt(rho_r*u1-y1, rho_r*u2-y2, rho_r*u3-y3);
eigA = rho_o*eigHtH + rho_r*eigDtD + rho_r*eigEtE;
f = real(ifftn(fftn(rhs)./eigA));
% y and z -update
[Df1 Df2 Df3] = D(f);
w = imfilter(f, H, 'circular') - g;
y1 = y1 - rho_r*(u1 - Df1);
y2 = y2 - rho_r*(u2 - Df2);
y3 = y3 - rho_r*(u3 - Df3);
z = z - rho_o*(r - w);
if (opts.print==true)
r1norm = sum(abs(w(:)));
r2norm = sum(sqrt(Df1(:).^2 + Df2(:).^2 + Df3(:).^2));
objval = mu*r1norm+r2norm;
end
rnorm_old = rnorm;
rnorm = sqrt(norm(Df1(:)-u1(:), 'fro')^2 + norm(Df2(:)-u2(:), 'fro')^2 + norm(Df3(:)-u3(:), 'fro')^2);
if rnorm>alpha*rnorm_old
rho_r = rho_r * gamma;
end
% relative change
relchg = norm(f(:)-f_old(:))/norm(f_old(:));
out.relchg(itr) = relchg;
if (opts.print==true)
out.objval(itr) = objval;
end
% print
if (opts.print==true)
fprintf('%3g \t %6.4e \t %6.4e \t %6.4e \t %6.4e \t %6.4e\n ', itr, relchg, r1norm, r2norm, objval, rho_r);
end
% check stopping criteria
if relchg < tol
break
end
end
out.f = f;
out.itr = itr;
out.y1 = y1;
out.y2 = y2;
out.y3 = y3;
out.z = z;
out.rho_r = rho_r;
out.Df1 = Df1;
out.Df2 = Df2;
out.Df3 = Df3;
if (opts.print==true)
fprintf('\n');
end
end
function [D,Dt] = defDDt(beta)
D = @(U) ForwardD(U, beta);
Dt = @(X,Y,Z) Dive(X,Y,Z, beta);
end
function [Dux,Duy,Duz] = ForwardD(U, beta)
frames = size(U, 3);
Dux = beta(1)*[diff(U,1,2), U(:,1,:) - U(:,end,:)];
Duy = beta(2)*[diff(U,1,1); U(1,:,:) - U(end,:,:)];
Duz(:,:,1:frames-1) = beta(3)*diff(U,1,3);
Duz(:,:,frames) = beta(3)*(U(:,:,1) - U(:,:,end));
end
function DtXYZ = Dive(X,Y,Z, beta)
frames = size(X, 3);
DtXYZ = [X(:,end,:) - X(:, 1,:), -diff(X,1,2)];
DtXYZ = beta(1)*DtXYZ + beta(2)*[Y(end,:,:) - Y(1, :,:); -diff(Y,1,1)];
Tmp(:,:,1) = Z(:,:,end) - Z(:,:,1);
Tmp(:,:,2:frames) = -diff(Z,1,3);
DtXYZ = DtXYZ + beta(3)*Tmp;
end
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
spectrum.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/spectrum.m
| 13,263 |
utf_8
|
5b5df172751851ed1f1f118f129ea9b0
|
function [Spec,f] = spectrum(varargin)
%SPECTRUM Power spectrum estimate of one or two data sequences.
% P=SPECTRUM(X,NFFT,NOVERLAP,WIND) estimates the Power Spectral Density of
% signal vector X using Welch's averaged periodogram method. The signal X
% is divided into overlapping sections, each of which is detrended and
% windowed by the WINDOW parameter, then zero padded to length NFFT. The
% magnitude squared of the length NFFT DFTs of the sections are averaged
% to form Pxx. P is a two column matrix P = [Pxx Pxxc]; the second column
% Pxxc is the 95% confidence interval. The number of rows of P is NFFT/2+1
% for NFFT even, (NFFT+1)/2 for NFFT odd, or NFFT if the signal X is comp-
% lex. If you specify a scalar for WINDOW, a Hanning window of that length
% is used.
%
% [P,F] = SPECTRUM(X,NFFT,NOVERLAP,WINDOW,Fs) given a sampling frequency
% Fs returns a vector of frequencies the same length as Pxx at which the
% PSD is estimated. PLOT(F,P(:,1)) plots the power spectrum estimate
% versus true frequency.
%
% [P, F] = SPECTRUM(X,NFFT,NOVERLAP,WINDOW,Fs,Pr) where Pr is a scalar
% between 0 and 1, overrides the default 95% confidence interval and
% returns the Pr*100% confidence interval for Pxx instead.
%
% SPECTRUM(X) with no output arguments plots the PSD in the current
% figure window, with confidence intervals.
%
% The default values for the parameters are NFFT = 256 (or LENGTH(X),
% whichever is smaller), NOVERLAP = 0, WINDOW = HANNING(NFFT), Fs = 2,
% and Pr = .95. You can obtain a default parameter by leaving it out
% or inserting an empty matrix [], e.g. SPECTRUM(X,[],128).
%
% P = SPECTRUM(X,Y) performs spectral analysis of the two sequences
% X and Y using the Welch method. SPECTRUM returns the 8 column array
% P = [Pxx Pyy Pxy Txy Cxy Pxxc Pyyc Pxyc]
% where
% Pxx = X-vector power spectral density
% Pyy = Y-vector power spectral density
% Pxy = Cross spectral density
% Txy = Complex transfer function from X to Y = Pxy./Pxx
% Cxy = Coherence function between X and Y = (abs(Pxy).^2)./(Pxx.*Pyy)
% Pxxc,Pyyc,Pxyc = Confidence range.
% All input and output options are otherwise exactly the same as for the
% single input case.
%
% SPECTRUM(X,Y) with no output arguments will plot Pxx, Pyy, abs(Txy),
% angle(Txy) and Cxy in sequence, pausing between plots.
%
% SPECTRUM(X,...,DFLAG), where DFLAG can be 'linear', 'mean' or 'none',
% specifies a detrending mode for the prewindowed sections of X (and Y).
% DFLAG can take the place of any parameter in the parameter list
% (besides X) as long as it is last, e.g. SPECTRUM(X,'none');
%
% See also PSD, CSD, TFE, COHERE, SPECGRAM, SPECPLOT, DETREND, PMTM,
% PMUSIC.
% ETFE, SPA, and ARX in the Identification Toolbox.
% Author(s): J.N. Little, 7-9-86
% C. Denham, 4-25-88, revised
% L. Shure, 12-20-88, revised
% J.N. Little, 8-31-89, revised
% L. Shure, 8-11-92, revised
% T. Krauss, 4-15-93, revised
% Copyright 1988-2000 The MathWorks, Inc.
% $Revision: 1.4 $ $Date: 2000/06/09 22:07:37 $
% The units on the power spectra Pxx and Pyy are such that, using
% Parseval's theorem:
%
% SUM(Pxx)/LENGTH(Pxx) = SUM(X.^2)/LENGTH(X) = COV(X)
%
% The RMS value of the signal is the square root of this.
% If the input signal is in Volts as a function of time, then
% the units on Pxx are Volts^2*seconds = Volt^2/Hz.
%
% Here are the covariance, RMS, and spectral amplitude values of
% some common functions:
% Function Cov=SUM(Pxx)/LENGTH(Pxx) RMS Pxx
% a*sin(w*t) a^2/2 a/sqrt(2) a^2*LENGTH(Pxx)/4
%Normal: a*rand(t) a^2 a a^2
%Uniform: a*rand(t) a^2/12 a/sqrt(12) a^2/12
%
% For example, a pure sine wave with amplitude A has an RMS value
% of A/sqrt(2), so A = SQRT(2*SUM(Pxx)/LENGTH(Pxx)).
%
% See Page 556, A.V. Oppenheim and R.W. Schafer, Digital Signal
% Processing, Prentice-Hall, 1975.
error(nargchk(1,8,nargin))
[msg,x,y,nfft,noverlap,window,Fs,p,dflag]=specchk(varargin);
error(msg)
if isempty(p),
p = .95; % default confidence interval even if not asked for
end
n = length(x); % Number of data points
nwind = length(window);
if n < nwind % zero-pad x (and y) if length less than the window length
x(nwind)=0; n=nwind;
if ~isempty(y), y(nwind)=0; end
end
x = x(:); % Make sure x and y are column vectors
y = y(:);
k = fix((n-noverlap)/(nwind-noverlap)); % Number of windows
% (k = fix(n/nwind) for noverlap=0)
index = 1:nwind;
KMU = k*norm(window)^2; % Normalizing scale factor ==> asymptotically unbiased
% KMU = k*sum(window)^2;% alt. Nrmlzng scale factor ==> peaks are about right
if (isempty(y)) % Single sequence case.
Pxx = zeros(nfft,1); Pxx2 = zeros(nfft,1);
for i=1:k
if strcmp(dflag,'linear')
xw = window.*detrend(x(index));
elseif strcmp(dflag,'none')
xw = window.*(x(index));
else
xw = window.*detrend(x(index),0);
end
index = index + (nwind - noverlap);
Xx = abs(fft(xw,nfft)).^2;
Pxx = Pxx + Xx;
Pxx2 = Pxx2 + abs(Xx).^2;
end
% Select first half
if ~any(any(imag(x)~=0)), % if x and y are not complex
if rem(nfft,2), % nfft odd
select = [1:(nfft+1)/2];
else
select = [1:nfft/2+1]; % include DC AND Nyquist
end
else
select = 1:nfft;
end
Pxx = Pxx(select);
Pxx2 = Pxx2(select);
cPxx = zeros(size(Pxx));
if k > 1
c = (k.*Pxx2-abs(Pxx).^2)./(k-1);
c = max(c,zeros(size(Pxx)));
cPxx = sqrt(c);
end
ff = sqrt(2)*erfinv(p); % Equal-tails.
Pxx = Pxx/KMU;
Pxxc = ff.*cPxx/KMU;
P = [Pxx Pxxc];
else
Pxx = zeros(nfft,1); % Dual sequence case.
Pyy = Pxx; Pxy = Pxx; Pxx2 = Pxx; Pyy2 = Pxx; Pxy2 = Pxx;
for i=1:k
if strcmp(dflag,'linear')
xw = window.*detrend(x(index));
yw = window.*detrend(y(index));
elseif strcmp(dflag,'none')
xw = window.*(x(index));
yw = window.*(y(index));
else
xw = window.*detrend(x(index),0);
yw = window.*detrend(y(index),0);
end
index = index + (nwind - noverlap);
Xx = fft(xw,nfft);
Yy = fft(yw,nfft);
Yy2 = abs(Yy).^2;
Xx2 = abs(Xx).^2;
Xy = Yy .* conj(Xx);
Pxx = Pxx + Xx2;
Pyy = Pyy + Yy2;
Pxy = Pxy + Xy;
Pxx2 = Pxx2 + abs(Xx2).^2;
Pyy2 = Pyy2 + abs(Yy2).^2;
Pxy2 = Pxy2 + Xy .* conj(Xy);
end
% Select first half
if ~any(any(imag([x y])~=0)), % if x and y are not complex
if rem(nfft,2), % nfft odd
select = [1:(nfft+1)/2];
else
select = [1:nfft/2+1]; % include DC AND Nyquist
end
else
select = 1:nfft;
end
Pxx = Pxx(select);
Pyy = Pyy(select);
Pxy = Pxy(select);
Pxx2 = Pxx2(select);
Pyy2 = Pyy2(select);
Pxy2 = Pxy2(select);
cPxx = zeros(size(Pxx));
cPyy = cPxx;
cPxy = cPxx;
if k > 1
c = max((k.*Pxx2-abs(Pxx).^2)./(k-1),zeros(size(Pxx)));
cPxx = sqrt(c);
c = max((k.*Pyy2-abs(Pyy).^2)./(k-1),zeros(size(Pxx)));
cPyy = sqrt(c);
c = max((k.*Pxy2-abs(Pxy).^2)./(k-1),zeros(size(Pxx)));
cPxy = sqrt(c);
end
Txy = Pxy./Pxx;
Cxy = (abs(Pxy).^2)./(Pxx.*Pyy);
ff = sqrt(2)*erfinv(p); % Equal-tails.
Pxx = Pxx/KMU;
Pyy = Pyy/KMU;
Pxy = Pxy/KMU;
Pxxc = ff.*cPxx/KMU;
Pxyc = ff.*cPxy/KMU;
Pyyc = ff.*cPyy/KMU;
P = [Pxx Pyy Pxy Txy Cxy Pxxc Pyyc Pxyc];
end
freq_vector = (select - 1)'*Fs/nfft;
if nargout == 0, % do plots
newplot;
c = [max(Pxx-Pxxc,0) Pxx+Pxxc];
c = c.*(c>0);
semilogy(freq_vector,Pxx,freq_vector,c(:,1),'--',...
freq_vector,c(:,2),'--');
title('Pxx - X Power Spectral Density')
xlabel('Frequency')
if (isempty(y)), % single sequence case
return
end
pause
newplot;
c = [max(Pyy-Pyyc,0) Pyy+Pyyc];
c = c.*(c>0);
semilogy(freq_vector,Pyy,freq_vector,c(:,1),'--',...
freq_vector,c(:,2),'--');
title('Pyy - Y Power Spectral Density')
xlabel('Frequency')
pause
newplot;
semilogy(freq_vector,abs(Txy));
title('Txy - Transfer function magnitude')
xlabel('Frequency')
pause
newplot;
plot(freq_vector,180/pi*angle(Txy)), ...
title('Txy - Transfer function phase')
xlabel('Frequency')
pause
newplot;
plot(freq_vector,Cxy);
title('Cxy - Coherence')
xlabel('Frequency')
elseif nargout ==1,
Spec = P;
elseif nargout ==2,
Spec = P;
f = freq_vector;
end
function [msg,x,y,nfft,noverlap,window,Fs,p,dflag] = specchk(P)
%SPECCHK Helper function for SPECTRUM
% SPECCHK(P) takes the cell array P and uses each cell as
% an input argument. Assumes P has between 1 and 7 elements.
% Author(s): T. Krauss, 4-6-93
msg = [];
if length(P{1})<=1
msg = 'Input data must be a vector, not a scalar.';
x = [];
y = [];
elseif (length(P)>1),
if (all(size(P{1})==size(P{2})) & (length(P{1})>1) ) | ...
length(P{2})>1, % 0ne signal or 2 present?
% two signals, x and y, present
x = P{1}; y = P{2};
% shift parameters one left
P(1) = [];
else
% only one signal, x, present
x = P{1}; y = [];
end
else % length(P) == 1
% only one signal, x, present
x = P{1}; y = [];
end
% now x and y are defined; let's get the rest
if length(P) == 1
nfft = min(length(x),256);
window = hanning(nfft);
noverlap = 0;
Fs = 2;
p = [];
dflag = 'linear';
elseif length(P) == 2
if isempty(P{2}), dflag = 'linear'; nfft = min(length(x),256);
elseif isstr(P{2}), dflag = P{2}; nfft = min(length(x),256);
else dflag = 'linear'; nfft = P{2}; end
window = hanning(nfft);
noverlap = 0;
Fs = 2;
p = [];
elseif length(P) == 3
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
if isempty(P{3}), dflag = 'linear'; noverlap = 0;
elseif isstr(P{3}), dflag = P{3}; noverlap = 0;
else dflag = 'linear'; noverlap = P{3}; end
window = hanning(nfft);
Fs = 2;
p = [];
elseif length(P) == 4
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
if isstr(P{4})
dflag = P{4};
window = hanning(nfft);
else
dflag = 'linear';
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
Fs = 2;
p = [];
elseif length(P) == 5
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if isstr(P{5})
dflag = P{5};
Fs = 2;
else
dflag = 'linear';
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
end
p = [];
elseif length(P) == 6
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
if isstr(P{6})
dflag = P{6};
p = [];
else
dflag = 'linear';
if isempty(P{6}), p = .95; else p = P{6}; end
end
elseif length(P) == 7
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
if isempty(P{6}), p = .95; else p = P{6}; end
if isstr(P{7})
dflag = P{7};
else
msg = 'DFLAG parameter must be a string.'; return
end
end
% NOW do error checking
if (nfft<length(window)),
msg = 'Requires window''s length to be no greater than the FFT length.';
end
if (noverlap >= length(window)),
msg = 'Requires NOVERLAP to be strictly less than the window length.';
end
if (nfft ~= abs(round(nfft)))|(noverlap ~= abs(round(noverlap))),
msg = 'Requires positive integer values for NFFT and NOVERLAP.';
end
if ~isempty(p),
if (prod(size(p))>1)|(p(1,1)>1)|(p(1,1)<0),
msg = 'Requires confidence parameter to be a scalar between 0 and 1.';
end
end
if min(size(x))~=1,
msg = 'Requires vector (either row or column) input.';
end
if (min(size(y))~=1)&(~isempty(y)),
msg = 'Requires vector (either row or column) input.';
end
if (length(x)~=length(y))&(~isempty(y)),
msg = 'Requires X and Y be the same length.';
end
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:38 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
getlength.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Utilities/getlength.m
| 638 |
utf_8
|
320d2a4b6bcb9556c70ea5aefc3ff7d4
|
% method of class @signal
%
% INPUT VALUES:
%
% RETURN VALUE:
%
%
% (c) 2003, University of Cambridge, Medical Research Council
% Stefan Bleeck ([email protected])
% http://www.mrc-cbu.cam.ac.uk/cnbh/aimmanual
% $Date: 2003/01/17 16:57:43 $
% $Revision: 1.3 $
function res =getlength(sig)
% returns the length in seconds
nr=size(sig.werte,1);
% r1=bin2time(sig,0);
% r2=bin2time(sig,nr);
% res=r2-r1;
sr=getsr(sig);
res=nr/sr;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:43 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
spectrum.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Browsers/One-D/spectrum.m
| 10,815 |
utf_8
|
2465d1a507f9362e9c0f5bda718e3f80
|
function [Spec,f] = spectrum(varargin)
%SPECTRUM Power spectrum estimate of one or two data sequences.
% SPECTRUM has been replaced by SPECTRUM.WELCH. SPECTRUM still works but
% may be removed in the future. Use SPECTRUM.WELCH (or its functional
% form PWELCH) instead. Type help SPECTRUM/WELCH for details.
%
% See also SPECTRUM/PSD, SPECTRUM/MSSPECTRUM, SPECTRUM/PERIODOGRAM.
% Author(s): J.N. Little, 7-9-86
% C. Denham, 4-25-88, revised
% L. Shure, 12-20-88, revised
% J.N. Little, 8-31-89, revised
% L. Shure, 8-11-92, revised
% T. Krauss, 4-15-93, revised
% Copyright 1988-2004 The MathWorks, Inc.
% $Revision: 1.6.4.3 $ $Date: 2004/10/18 21:09:32 $
% The units on the power spectra Pxx and Pyy are such that, using
% Parseval's theorem:
%
% SUM(Pxx)/LENGTH(Pxx) = SUM(X.^2)/LENGTH(X) = COV(X)
%
% The RMS value of the signal is the square root of this.
% If the input signal is in Volts as a function of time, then
% the units on Pxx are Volts^2*seconds = Volt^2/Hz.
%
% Here are the covariance, RMS, and spectral amplitude values of
% some common functions:
% Function Cov=SUM(Pxx)/LENGTH(Pxx) RMS Pxx
% a*sin(w*t) a^2/2 a/sqrt(2) a^2*LENGTH(Pxx)/4
%Normal: a*rand(t) a^2 a a^2
%Uniform: a*rand(t) a^2/12 a/sqrt(12) a^2/12
%
% For example, a pure sine wave with amplitude A has an RMS value
% of A/sqrt(2), so A = SQRT(2*SUM(Pxx)/LENGTH(Pxx)).
%
% See Page 556, A.V. Oppenheim and R.W. Schafer, Digital Signal
% Processing, Prentice-Hall, 1975.
error(nargchk(1,8,nargin))
[msg,x,y,nfft,noverlap,window,Fs,p,dflag]=specchk(varargin);
error(msg)
if isempty(p),
p = .95; % default confidence interval even if not asked for
end
n = length(x); % Number of data points
nwind = length(window);
if n < nwind % zero-pad x (and y) if length less than the window length
x(nwind)=0; n=nwind;
if ~isempty(y), y(nwind)=0; end
end
x = x(:); % Make sure x and y are column vectors
y = y(:);
k = fix((n-noverlap)/(nwind-noverlap)); % Number of windows
% (k = fix(n/nwind) for noverlap=0)
index = 1:nwind;
KMU = k*norm(window)^2; % Normalizing scale factor ==> asymptotically unbiased
% KMU = k*sum(window)^2;% alt. Nrmlzng scale factor ==> peaks are about right
if (isempty(y)) % Single sequence case.
Pxx = zeros(nfft,1); Pxx2 = zeros(nfft,1);
for i=1:k
if strcmp(dflag,'linear')
xw = window.*detrend(x(index));
elseif strcmp(dflag,'none')
xw = window.*(x(index));
else
xw = window.*detrend(x(index),0);
end
index = index + (nwind - noverlap);
Xx = abs(fft(xw,nfft)).^2;
Pxx = Pxx + Xx;
Pxx2 = Pxx2 + abs(Xx).^2;
end
% Select first half
if ~any(any(imag(x)~=0)), % if x and y are not complex
if rem(nfft,2), % nfft odd
select = 1:(nfft+1)/2;
else
select = 1:nfft/2+1; % include DC AND Nyquist
end
else
select = 1:nfft;
end
Pxx = Pxx(select);
Pxx2 = Pxx2(select);
cPxx = zeros(size(Pxx));
if k > 1
c = (k.*Pxx2-abs(Pxx).^2)./(k-1);
c = max(c,zeros(size(Pxx)));
cPxx = sqrt(c);
end
ff = sqrt(2)*erfinv(p); % Equal-tails.
Pxx = Pxx/KMU;
Pxxc = ff.*cPxx/KMU;
P = [Pxx Pxxc];
else
Pxx = zeros(nfft,1); % Dual sequence case.
Pyy = Pxx; Pxy = Pxx; Pxx2 = Pxx; Pyy2 = Pxx; Pxy2 = Pxx;
for i=1:k
if strcmp(dflag,'linear')
xw = window.*detrend(x(index));
yw = window.*detrend(y(index));
elseif strcmp(dflag,'none')
xw = window.*(x(index));
yw = window.*(y(index));
else
xw = window.*detrend(x(index),0);
yw = window.*detrend(y(index),0);
end
index = index + (nwind - noverlap);
Xx = fft(xw,nfft);
Yy = fft(yw,nfft);
Yy2 = abs(Yy).^2;
Xx2 = abs(Xx).^2;
Xy = Yy .* conj(Xx);
Pxx = Pxx + Xx2;
Pyy = Pyy + Yy2;
Pxy = Pxy + Xy;
Pxx2 = Pxx2 + abs(Xx2).^2;
Pyy2 = Pyy2 + abs(Yy2).^2;
Pxy2 = Pxy2 + Xy .* conj(Xy);
end
% Select first half
if ~any(any(imag([x y])~=0)), % if x and y are not complex
if rem(nfft,2), % nfft odd
select = 1:(nfft+1)/2;
else
select = 1:nfft/2+1; % include DC AND Nyquist
end
else
select = 1:nfft;
end
Pxx = Pxx(select);
Pyy = Pyy(select);
Pxy = Pxy(select);
Pxx2 = Pxx2(select);
Pyy2 = Pyy2(select);
Pxy2 = Pxy2(select);
cPxx = zeros(size(Pxx));
cPyy = cPxx;
cPxy = cPxx;
if k > 1
c = max((k.*Pxx2-abs(Pxx).^2)./(k-1),zeros(size(Pxx)));
cPxx = sqrt(c);
c = max((k.*Pyy2-abs(Pyy).^2)./(k-1),zeros(size(Pxx)));
cPyy = sqrt(c);
c = max((k.*Pxy2-abs(Pxy).^2)./(k-1),zeros(size(Pxx)));
cPxy = sqrt(c);
end
Txy = Pxy./Pxx;
Cxy = (abs(Pxy).^2)./(Pxx.*Pyy);
ff = sqrt(2)*erfinv(p); % Equal-tails.
Pxx = Pxx/KMU;
Pyy = Pyy/KMU;
Pxy = Pxy/KMU;
Pxxc = ff.*cPxx/KMU;
Pxyc = ff.*cPxy/KMU;
Pyyc = ff.*cPyy/KMU;
P = [Pxx Pyy Pxy Txy Cxy Pxxc Pyyc Pxyc];
end
freq_vector = (select - 1)'*Fs/nfft;
if nargout == 0, % do plots
newplot;
c = [max(Pxx-Pxxc,0) Pxx+Pxxc];
c = c.*(c>0);
semilogy(freq_vector,Pxx,freq_vector,c(:,1),'--',...
freq_vector,c(:,2),'--');
title('Pxx - X Power Spectral Density')
xlabel('Frequency')
if (isempty(y)), % single sequence case
return
end
pause
newplot;
c = [max(Pyy-Pyyc,0) Pyy+Pyyc];
c = c.*(c>0);
semilogy(freq_vector,Pyy,freq_vector,c(:,1),'--',...
freq_vector,c(:,2),'--');
title('Pyy - Y Power Spectral Density')
xlabel('Frequency')
pause
newplot;
semilogy(freq_vector,abs(Txy));
title('Txy - Transfer function magnitude')
xlabel('Frequency')
pause
newplot;
plot(freq_vector,180/pi*angle(Txy)), ...
title('Txy - Transfer function phase')
xlabel('Frequency')
pause
newplot;
plot(freq_vector,Cxy);
title('Cxy - Coherence')
xlabel('Frequency')
elseif nargout ==1,
Spec = P;
elseif nargout ==2,
Spec = P;
f = freq_vector;
end
function [msg,x,y,nfft,noverlap,window,Fs,p,dflag] = specchk(P)
%SPECCHK Helper function for SPECTRUM
% SPECCHK(P) takes the cell array P and uses each cell as
% an input argument. Assumes P has between 1 and 7 elements.
% Author(s): T. Krauss, 4-6-93
msg = [];
if length(P{1})<=1
msg = 'Input data must be a vector, not a scalar.';
x = [];
y = [];
elseif (length(P)>1),
if (all(size(P{1})==size(P{2})) && (length(P{1})>1) ) || ...
length(P{2})>1, % 0ne signal or 2 present?
% two signals, x and y, present
x = P{1}; y = P{2};
% shift parameters one left
P(1) = [];
else
% only one signal, x, present
x = P{1}; y = [];
end
else % length(P) == 1
% only one signal, x, present
x = P{1}; y = [];
end
% now x and y are defined; let's get the rest
if length(P) == 1
nfft = min(length(x),256);
window = hanning(nfft);
noverlap = 0;
Fs = 2;
p = [];
dflag = 'linear';
elseif length(P) == 2
if isempty(P{2}), dflag = 'linear'; nfft = min(length(x),256);
elseif ischar(P{2}), dflag = P{2}; nfft = min(length(x),256);
else dflag = 'linear'; nfft = P{2}; end
window = hanning(nfft);
noverlap = 0;
Fs = 2;
p = [];
elseif length(P) == 3
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
if isempty(P{3}), dflag = 'linear'; noverlap = 0;
elseif ischar(P{3}), dflag = P{3}; noverlap = 0;
else dflag = 'linear'; noverlap = P{3}; end
window = hanning(nfft);
Fs = 2;
p = [];
elseif length(P) == 4
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
if ischar(P{4})
dflag = P{4};
window = hanning(nfft);
else
dflag = 'linear';
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
Fs = 2;
p = [];
elseif length(P) == 5
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if ischar(P{5})
dflag = P{5};
Fs = 2;
else
dflag = 'linear';
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
end
p = [];
elseif length(P) == 6
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
if ischar(P{6})
dflag = P{6};
p = [];
else
dflag = 'linear';
if isempty(P{6}), p = .95; else p = P{6}; end
end
elseif length(P) == 7
if isempty(P{2}), nfft = min(length(x),256); else nfft=P{2}; end
window = P{4}; window = window(:); % force window to be a column
if length(window) == 1, window = hanning(window); end
if isempty(window), window = hanning(nfft); end
if isempty(P{3}), noverlap = 0; else noverlap=P{3}; end
if isempty(P{5}), Fs = 2; else Fs = P{5}; end
if isempty(P{6}), p = .95; else p = P{6}; end
if ischar(P{7})
dflag = P{7};
else
msg = 'DFLAG parameter must be a string.'; return
end
end
% NOW do error checking
if (nfft<length(window)),
msg = 'Requires window''s length to be no greater than the FFT length.';
end
if (noverlap >= length(window)),
msg = 'Requires NOVERLAP to be strictly less than the window length.';
end
if (nfft ~= abs(round(nfft)))||(noverlap ~= abs(round(noverlap))),
msg = 'Requires positive integer values for NFFT and NOVERLAP.';
end
if ~isempty(p),
if (numel(p)>1)||(p(1,1)>1)||(p(1,1)<0),
msg = 'Requires confidence parameter to be a scalar between 0 and 1.';
end
end
if min(size(x))~=1,
msg = 'Requires vector (either row or column) input.';
end
if (min(size(y))~=1)&&(~isempty(y)),
msg = 'Requires vector (either row or column) input.';
end
if (length(x)~=length(y))&&(~isempty(y)),
msg = 'Requires X and Y be the same length.';
end
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:39 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
def_signal.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Browsers/One-D/def_signal.m
| 822 |
utf_8
|
3d205982ba291fa4a1490bbc0d3c5032
|
% def_signal -- Called by WLBrowser
% Usage
% def_signal
%
function x = def_signal(i)
do_global; global nsig;
signal_name = Signals_entries( i,: );
while signal_name( length(signal_name) ) == ' '
signal_name( length(signal_name) ) = [];
end
if ~exist('nsig') | nsig == [] | nsig == 0
nsig = 2^8;
end
x = MakeSignal(signal_name, nsig );
[ aa bb ] = size(x);
if aa > bb
x = x';
end
x = ...
x(1:2^(fix(log(length(x))/log(2) )));
x_signal = x;
if max( abs(x_noise) ) > 0
x_use = x_signal + x_noise;
else
x_use = x_signal;
end
n =length(x_use)
plot_new_data;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:39 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
def_data.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Browsers/One-D/def_data.m
| 881 |
utf_8
|
dd6c7b1f269745e207c2f0b62b9125e0
|
% def_data -- Called by WLBrowser
% Usage
% def_data
%
% Description
% Load WaveLab datasets
%
function x = def_data(i)
do_global
data_name = Data____entries( i+1, : );
while data_name( length(data_name) ) == ' '
data_name( length(data_name) ) = [];
end
if i < 7
x = ReadSignal(data_name);
signal_name = data_name;
elseif i == 7
if exist('kitload')
load('kitload');
else
warndlg('Please save your data as "kitload"');
end
end
[ aa bb ] = size(x);
if aa > bb
x = x';
end
x = ...
x(1:2^(fix(log(length(x))/log(2) )));
x_signal = x;
noise_type = 0;
x_noise = zeros( size( x ) );
n = length(x);
x_use = x;
plot_new_data;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:39 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
AdaptDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/Adapt/AdaptDemo.m
| 11,368 |
utf_8
|
180001bdfcbd44bcd54b8cf9120dc5f0
|
%********************************************************
function AdaptDemo(action)
%Usage: AdaptDemo
%Description: Demo for paper Adapting to Unknown Smoothness via Wavelet
%Shrinkage
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 15;
PaperName = 'Adapting to Unknown Smoothness via Wavelet Shrinkage';
MakeFigureFilePrefix = 'adfig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global ADAPTFIGNUM
ADAPTFIGNUM = 0;
clc; help('AdaptIntro')
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,AdaptDemo;end
elseif isequal(action,'AddTitle'),
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','AdaptDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','AdaptDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','AdaptDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','AdaptDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','AdaptDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','AdaptDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'AdaptDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','AdaptDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
AdaptFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%s=num2str(edit1);
%eval(strcat('AdaptFig(',s,')'));
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
% set(text3,' ', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
% set(text3,' ', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
% set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
CSpinDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/SpinCycle/CSpinDemo.m
| 11,707 |
utf_8
|
bc47e62d03b6b2a5bf926f80cd1ea94f
|
%********************************************************
function CSpinDemo(action)
%Usage: CSpinDemo
%Description: Demo for paper Translation-Invariant DeNoisin
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 21;
PaperName = 'Translation-Invariant DeNoisin';
MakeFigureFilePrefix = 'cspinf';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global CSFIGNUM
CSFIGNUM = 0;
clc; help('CSpinIntro');
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,CSpinDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','CSpinDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','CSpinDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','CSpinDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','CSpinDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','CSpinDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','CSpinDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'CSpinDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','CSpinDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
SpinFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:42 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
MESDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/MinEntSeg/MESDemo.m
| 12,121 |
utf_8
|
10c38e6038829379a0e22866c7656a78
|
%********************************************************
function MESDemo(action)
%Usage: MESDemo
%Description: Demo for paper Minimum Entropy Segmentation
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
PaperName = 'Minimum Entropy Segmentation';
MakeFigureFilePrefix = 'mefig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global MESFIGNUM
MESFIGNUM = 0;
clc; help('MESIntro');
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,MESDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
edit_vec=[201:214, 302:306,401:402,601:605];
edit2=edit_vec(edit1);
s=num2str(edit2);
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','MESDemo(''NewWindow'')');
%
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','MESDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','MESDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
% uicontrol( 'tag','edit1', 'style','list', ...
% 'units','normal', 'position',[.85 .50 .12 .30], ...
% 'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
% 'fontsize',fs, 'callback','MESDemo(''ploteach'')');
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',...
'2.01|2.02|2.03|2.04|2.05|2.06|2.07|2.08|2.09|2.10|2.11|2.12|2.13|2.14|3.02|3.03|3.04|3.05|3.06|4.01|4.02|6.01|6.02|6.03|6.04|6.05',...
'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','MESDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','MESDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','MESDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'MESDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','MESDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
edit_vec=[201:214, 302:306,401:402,601:605];
edit2=edit_vec(edit1);
MESFig(edit2);
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
RiskDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/RiskAnalysis/RiskDemo.m
| 11,626 |
utf_8
|
2a233fe2f8463d8c4804916c4bba3f16
|
%********************************************************
function RiskDemo(action)
%Usage: RiskDemo
%Description: Demo for paper EXACT RISK ANALYSIS OF WAVELET REGRESSION
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 13;
PaperName = 'EXACT RISK ANALYSIS OF WAVELET REGRESSION';
MakeFigureFilePrefix = 'RiskFig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
RiskInit;
global RISKFIGNUM
RISKFIGNUM = 0;
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,RiskDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
s=num2str(edit1)
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','RiskDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','RiskDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','RiskDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','RiskDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','RiskDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','RiskDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'RiskDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','RiskDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
RiskFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:42 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
SCDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/ShortCourse/SCDemo.m
| 11,628 |
utf_8
|
2cfe2fd8ea91b4f70eb21adfc3f1722c
|
%********************************************************
function SCDemo(action)
%Usage: SCDemo
%Description: Demo for Short Course
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 28;
PaperName = 'Short Course';
MakeFigureFilePrefix = 'scfig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global SCFIGNUM
SCFIGNUM = 0;
clc; help('SCIntro');
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,SCDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','SCDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','SCDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','SCDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','SCDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','SCDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','SCDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'SCDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','SCDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
SCFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:42 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
BlockyDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/Blocky/BlockyDemo.m
| 11,446 |
utf_8
|
eca745f65c369f6596e97b9b376401b3
|
%********************************************************
function BockyDemo(action)
%Usage: BlockyDemo
%Description: Demo for paper Smooth Wavelet Decompositions with Blocky
%Coefficient Kernels
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 7;
PaperName = 'Smooth Wavelet Decompositions with Blocky Coefficient Kernels';
MakeFigureFilePrefix = 'aifig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global BLOCKYFIGNUM
BLOCKYFIGNUM = 0;
clc; help('BlockyIntro');
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,BlockyDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','BlockyDemo(''NewWindow'')');
%
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','BlockyDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','BlockyDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','BlockyDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','BlockyDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','BlockyDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'BlockyDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','BlockyDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
BlockyFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
VdLDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/VillardDeLans/VdLDemo.m
| 11,692 |
utf_8
|
de5771598e9111e4276abf5d9395a4ce
|
%********************************************************
function VdLDemo(action)
%Usage: VdLDemo
%Description: Demo for paper WaveLab and Reproducible Research
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 11;
PaperName = 'WaveLab and Reproducible Research';
MakeFigureFilePrefix = 'vdlfig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global VDLFIGNUM
VDLFIGNUM = 0;
clc; help('VdLIntro');
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,VdLDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','VdLDemo(''NewWindow'')');
%
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','VdLDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','VdLDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','VdLDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','VdLDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','VdLDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'VdLDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','VdLDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
VdLFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:42 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
TourDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/Tour/TourDemo.m
| 11,732 |
utf_8
|
81919bc6b7d0842b12e02c40a909e027
|
%********************************************************
function TourDemo(action)
%Usage: TourDemo
%Description: Demo for paper Wavelet Shrinkage and W.V.D.: A Ten-Minute
%Tour
%Date: August 1,2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 15;
PaperName = 'Wavelet Shrinkage and W.V.D.: A Ten-Minute Tour';
MakeFigureFilePrefix = 'toufig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global TOURFIGNUM
TOURFIGNUM = 0;
clc; help('TourIntro')
if ~(exist('spectrum') & exist('xcorr'))
disp('This demo requires the signal processing toolbox to run.');
disp('If you see this message, it means that the signal processing');
disp('toolbox is not installed at your system, or that this matlab');
disp('session is not seeing the toolbox in its search path.');
disp(' ');
return
end
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,TourDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','TourDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','TourDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','TourDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','TourDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','TourDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','TourDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'TourDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','TourDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
TourFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:42 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
AsympDemo.m
|
.m
|
convolutional_sparse_coding-master/Main/MCA/Wavelab850/Papers/Asymp/AsympDemo.m
| 11,354 |
utf_8
|
81c6f0550a19608ea51b03a62b22b423
|
%********************************************************
function AsympDemo(action)
%Usage: AsympDemo
%Description: Demo for paper Wavelet Shrinkage: Asymptopia?
%Date: August 1, 2005
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE
global NRfigures
global CRfigures
global UnderConstructionFigures
% -------------------------------------------------------
LastFigureNo = 10;
PaperName = 'Wavelet Shrinkage: Asymptopia?';
MakeFigureFilePrefix = 'asfig';
% NRfigures = {1};
% CRfigures = {8,10,11};
% UnderConstructionFigures = {20};
%--------------------------------------------------------
global ASFIGNUM
ASFIGNUM = 0;
clc; help('AsympIntro');
WLVERBOSE='No';
IfNewWindow = 0;
IfAddTitle = 0;
IfCompute = 0;
if nargin == 0,
Initialize_GUI;
c=get(gcf,'Children');
[m,n]=size(c);
plotOffset = m;
action = '';
end
if isequal(action,'NewWindow'),
IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
if IfNewWindow,AsympDemo;end
% elseif isequal(action,'AddTitle'),
% IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
% elseif isequal(action,'Compute'),
% IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
elseif isequal(action,'ploteach'),
PlotFigure;
elseif isequal(action,'plotall'),
StopPlot = 0;
PlotAllFigures;
elseif isequal(action,'stop'),
StopPlot = 1;
elseif isequal(action,'seecode'),
edit1 = get(findobj(gcf,'tag','edit1'),'value');
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
s = ['edit', ' ', strcat(MakeFigureFilePrefix, s)];
eval(s);
elseif isequal(action,'CloseAllDemo'),
CloseDemoFigures;
ClearGlobalVariables;
end
%********************************************************
function Initialize_GUI
%********************************************************
% -------------------------------------------------------
fs = 9; %default font size
% -------------------------------------------------------
global LastFigureNo
global PaperName;
%CloseDemoFigures
%close all
figure;
figureNoList = (1:LastFigureNo)';
%clf reset;
set(gcf,'pos', [50 55 560*1.45 420*1.45], 'Name', PaperName, 'NumberTitle','off');
set(gcf,'doublebuffer','on','userdata',1);
uicontrol('tag','newWindow', 'style','checkbox', ...
'units','normal', 'position',[.85 .92, .12 .05], ...
'string','New Window', 'fontsize',fs, ...
'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
'callback','AsympDemo(''NewWindow'')');
% uicontrol('tag','iftitle', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .88, .12 .05], ...
% 'string','Title', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','AsympDemo(''AddTitle'')');
% uicontrol( 'tag','IfCompute', 'style','checkbox', ...
% 'units','normal', 'position',[.85 .84, .12 .05], ...
% 'string','Compute', 'fontsize',fs, ...
% 'userdata',0, 'backgroundcolor', [0.8 0.8 0.8],...
% 'callback','AsympDemo(''Compute'')');
uicontrol( 'tag','text1', 'style','text', ...
'units','normal', 'position', [.85 .79, .12 .04], ...
'string','Figure','backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol('tag','text2', 'style','text', ...
'units','normal', 'position', [.04 .93, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','text3', 'style','text', ...
'units','normal', 'position', [.04 .01, .7 .04], ...
'string','', 'backgroundcolor', [0.8 0.8 0.8],...
'fontsize',fs);
uicontrol( 'tag','edit1', 'style','list', ...
'units','normal', 'position',[.85 .50 .12 .30], ...
'string',{num2str(figureNoList)}, 'backgroundcolor',[0.8 0.8 0.8], ...
'fontsize',fs, 'callback','AsympDemo(''ploteach'')');
uicontrol( 'tag','RunAllFig', 'style','pushbutton', ...
'units','normal', 'position',[.85 .40 .12 .06], ...
'string','Run All Fig' , 'fontsize',fs, ...
'interruptible','on', 'callback','AsympDemo(''plotall'')');
uicontrol( 'tag','stop', 'style','pushbutton', ...
'units','normal', 'position',[.85 .32 .12 .06], ...
'string','Stop', 'fontsize',fs, ...
'userdata',0, 'callback','AsympDemo(''stop'');');
%'callback','set(gcbo,''userdata'',1)');
uicontrol( 'tag','SeeCode', 'style','pushbutton', ...
'units','normal', 'position',[.85 .24 .12 .06], ...
'string','See Code' , 'fontsize',fs, ...
'callback', 'AsympDemo(''seecode'')');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .16 .12 .06], 'string','Close', ...
'fontsize',fs, 'callback','close');
uicontrol( 'style','pushbutton', 'units','normal', ...
'position',[.85 .08 .12 .06], 'string','Close All', ...
'fontsize',fs, 'callback','AsympDemo(''CloseAllDemo'')');
%********************************************************
function PlotFigure
%********************************************************
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfCompute
global NRfigures
global CRfigures
global UnderConstructionFigures
ListControl = findobj(gcf,'tag','edit1');
set(ListControl,'Enable','off');
DeleteSubplots;
%set(gcf,'Visible', 'off');
edit1 = get(findobj(gcf,'tag','edit1'),'value');
IfAddTitle = get(findobj(gcf,'tag','iftitle'),'value');
IfCompute = get(findobj(gcf,'tag','IfCompute'),'value');
%IfNewWindow = get(findobj(gcf,'tag','newWindow'),'value');
IfNewWindow = 0;
AsympFig(edit1);
%if edit1 < 10,
% s=strcat('0', num2str(edit1));
%else
%end
%eval(s);
%
% IfLoadData = ~IfCompute;
% switch edit1,
% case UnderConstructionFigures
% fprintf('\n\nFigure %d is still under construction', edit1);
% case NRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ')'];
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% case CRfigures
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),',', num2str(IfLoadData),')'];
% if IfLoadData,
% fprintf('\n\n\nLoading Data for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nData Loaded. Figure %d generated.\n', edit1);
% % toc,
% else
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% end
% otherwise
% s=[strcat(MakeFigureFilePrefix, s), '(', num2str(IfNewWindow), ',', num2str(IfAddTitle),')'];
% fprintf('\n\n\nComputing for Figure %d...\n', edit1);
% % tic;
% eval(s);
% fprintf('\nComputations done. Figure %d generated.\n', edit1);
% % toc,
% end
WriteCaptions(edit1);
AdjustSubplots;
titles= ['Figure ', num2str(edit1)];
text1 = findobj(gcbo,'tag','text1');
set(text1,'string', titles);
set(ListControl,'Enable','on');
%set(gcf,'Visible', 'on');
%********************************************************
function PlotAllFigures
%********************************************************
global LastFigureNo
global StopPlot
global IfNewWindow
for i=1:LastFigureNo,
if StopPlot == 1,
break;
end
h=findobj(gcf,'tag','edit1');
set(h,'Value',i);
PlotFigure;
pause(3);
%DeleteNonDemoFigures
end
%********************************************************
function WriteCaptions(edit1)
%********************************************************
global MakeFigureFilePrefix
global NRfigures
global CRfigures
global UnderConstructionFigures
captions='';
if edit1 < 10,
s=strcat('0', num2str(edit1));
else
s=num2str(edit1);
end
text3 = findobj(gcf,'tag','text3');
switch edit1,
case UnderConstructionFigures
set(text3,'string', ['This figure is still under construction']);
case NRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(NR)']);
case CRfigures
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, num2str(edit1)),'.m',' ','(CR)']);
otherwise
set(text3,'string', ['This figure is produced by', ' ', strcat(MakeFigureFilePrefix, s),'.m', ' ', '(R)']);
end
%********************************************************
function AdjustSubplots
%********************************************************
global plotOffset
% set(gcf,'Visible', 'off');
MagnificationFactor = 0.92;
right = 0.78;
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
p = zeros(m, 4);
for i=m:-1:1,
%get all suplots' positions
p(i,:) = get(c(i),'position');
end
% contract all subplots
p = p * MagnificationFactor;
col=sum(unique(p(:,1))<1);
LegNo = length(findobj(gcf,'tag','legend'));
if ~isempty(LegNo)
col = col- LegNo;
end
diff = length(unique(p(:,1))) - col;
if col > 0,
row = m/col;
end
cond1 = isempty(LegNo);
hshift = .05;
%simpliy do a horizontal shift for children that is not "camera" menu nor legend
for i=m:-1:1
if p(i,1)<1,
cond2 = and(~cond1, ~strcmp(get(c(i),'tag'), 'legend'));
if or(cond1, cond2),
width = p(i,3);
%hshift = (right - col * width) / (col+1);
p(i,1) = p(i,1) - hshift;
set(c(i), 'position', p(i,:));
end
end
end
%********************************************************
function DeleteSubplots
%********************************************************
global plotOffset
c = get(gcf,'Children');
[m1,n1]=size(c);
m=m1-plotOffset;
for i=1:m,
delete(c(i));
end
%********************************************************
function DeleteNonDemoFigures
%********************************************************
h=findobj(0,'Type','figure');
[m,n]=size(h);
for i=1:m,
if h(i)~=1
close(h(i));
end
end
%********************************************************
function CloseDemoFigures
%********************************************************
global PaperName;
h=findobj(0,'Name', PaperName);
[m,n]=size(h);
for i=1:m,
close(h(i))
end
%********************************************************
function ClearGlobalVariables
%********************************************************
global plotOffset
global LastFigureNo
global PaperName
global MakeFigureFilePrefix
global IfNewWindow
global IfAddTitle
global IfLoadData
global StopPlot
global WLVERBOSE;
global NRfigures;
global CRfigures;
global UnderConstructionFigures;
clear plotOffset
clear LastFigureNo
clear PaperName
clear MakeFigureFilePrefix
clear IfNewWindow
clear IfAddTitle
clear IfLoadData
clear StopPlot
clear WLVERBOSE;
clear NRfigures;
clear CRfigures;
clear UnderConstructionFigures;
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdngr.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdngr.m
| 11,600 |
utf_8
|
2e39147180340593eaaa5c1950090018
|
function [Y, optinf] = cbpdngr(D, S, lambda, mu, opt)
% cbpdngr -- Convolutional Basis Pursuit DeNoising with Gradient Regularization
%
% argmin_{x_k} (1/2)||\sum_k d_k * x_k - s||_2^2 +
% lambda \sum_k ||x_k||_1 +
% (mu/2) \sum_k ||G_r x_k||_2^2 +
% (mu/2) \sum_k ||G_c x_k||_2^2
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-convolutional2).
%
% Usage:
% [Y, optinf] = cbpdngr(D, S, lambda, mu, opt);
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter (l1)
% mu Regularization parameter (l2 of gradient)
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, gradient
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% GrdWeight Weighting array for coefficients in l2 norm of
% gradient of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2016-07-01
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 5,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 Grd r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) 1];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
grv = [-1 1];
Grf = fft2(grv, size(S,1), size(S,2));
gcv = [-1 1]';
Gcf = fft2(gcv, size(S,1), size(S,2));
if isscalar(opt.GrdWeight),
opt.GrdWeight = opt.GrdWeight * ones(size(D,3), 1);
end
wgr = reshape(opt.GrdWeight, [1 1 length(opt.GrdWeight)]);
GfW = bsxfun(@times, conj(Grf).*Grf + conj(Gcf).*Gcf, wgr);
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
cn = bsxfun(@rdivide, Df, mu*GfW + rho);
cd = sum(Df.*bsxfun(@rdivide, conj(Df), mu*GfW + rho), 3) + 1.0;
C = bsxfun(@rdivide, cn, cd);
clear cn cd;
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz, class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbd_sm(Df, mu*GfW + rho, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,:,:) = 0;
Y(:,(end-size(D,2)+2):end,:,:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jgr = sum(vec((bsxfun(@times, GfW, conj(Yf).*Yf))))/(2*xsz(1)*xsz(2));
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jgr = sum(vec((bsxfun(@times, GfW, conj(Xf).*Xf))))/(2*xsz(1)*xsz(2));
end
Jfn = Jdf + lambda*Jl1 + mu*Jgr;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 Jgr r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jgr, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jgr, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
cn = bsxfun(@rdivide, Df, mu*GfW + rho);
cd = sum(Df.*bsxfun(@rdivide, conj(Df), mu*GfW + rho), 3) + 1.0;
C = bsxfun(@rdivide, cn, cd);
clear cn cd;
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.mu = mu;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'GrdWeight'),
opt.GrdWeight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
bpdn.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/bpdn.m
| 8,693 |
utf_8
|
16adec7a3bdc2618ca15b5a38b5a5e0f
|
function [Y, optinf] = bpdn(D, S, lambda, opt)
% bpdn -- Basis Pursuit DeNoising
%
% argmin_x (1/2)||D*x - s||_2^2 + lambda*||x||_1
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [Y, optinf] = bpdn(D, S, lambda, opt)
%
% Input:
% D Dictionary matrix
% S Signal vector (or matrix)
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% Y Dictionary coefficient vector (or matrix)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-23
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
lambda = 0.1*max(vec(abs(D'*S)));
end
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
[Nr, Nc] = size(D);
Nm = size(S,2);
Nx = Nc*Nm;
DTS = D'*S;
[luL, luU] = factorise(D, rho);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(Nc,Nm);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(Nc,Nm);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
X = linsolve(D, rho, luL, luU, DTS + rho*(Y - U));
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Objective function and convergence measures
if opt.AuxVarObj,
Jdf = sum(vec(abs(D*Y - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
else
Jdf = sum(vec(abs(D*X - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
end
Jfn = Jdf + lambda*Jl1;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if rsf ~= 1,
[luL, luU] = factorise(D, rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolve(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = U \ (L \ b);
else
x = (b - A'*(U \ (L \ (A*b))))/c;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = 1;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 1;
end
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.